PageSourceSearch

https://tv.mts.by/assets/ssr/sequoia-core-C9opehXT.js

js mts.by collected 2026-10-01 10:18:05 UTC 826,698 bytes, 37 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ssr/mux.js-D3y-SZzd.js","assets/ssr/lodash-nRwxe0ET.js","assets/ssr/shaka-player.ui-BEvA4ZG6.js"])))=>i.map(i=>d[i]);
2var Ve=Object.defineProperty;var He=(t,e,s)=>e in t?Ve(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var $=(t,e,s)=>He(t,typeof e!="symbol"?e+"":e,s);import{m as moize$1,C as Cookies,d as dayjs,c as convertLayoutRu,B as Bowser,A as AxiosError,a as axios,b as Blowfish,p as plurar}from"./vendor-DAO7f7jf.js";import{s as sortBy,u as uniqBy,t as throttle,i as intersectionWith,d as debounce,a as cloneDeep,r as random,b as intersection$1,e as groupBy}from"./lodash-nRwxe0ET.js";import{V as Vue,C as ComponentBase,m as mixins,g as getCurrentInstance,c as computed,r as ref,u as useRoute,a as useRouter,b as reactive,o as onMounted,d as onUnmounted,w as watch,e as onBeforeUnmount,f as decorator,h as onBeforeMount,i as onUpdated}from"./vue-D47mIxKn.js";import{I as IconUz,a as IconUs,b as IconUk,c as IconTj,d as IconKz,e as IconKg,f as IconBr,g as IconRu}from"./svg-BVh902Jo.js";import{g as getDeviceUuid}from"./uuid-ay_OU3Vs.js";const moize=moize$1.default||moize$1,DAYS_IN_MONTH=30,HOURS_IN_DAY=24,MINUTES_IN_HOUR=60,SECONDS_IN_MINUTE=60,MILLISECONDS_IN_SECOND=1e3,names=["month","day","hour","minute","second","millisecond"],constituents=[DAYS_IN_MONTH,HOURS_IN_DAY,MINUTES_IN_HOUR,SECONDS_IN_MINUTE,MILLISECONDS_IN_SECOND,1],convertTo=(t="millisecond")=>(e=0,s="month")=>{s.endsWith("s")&&(s=s.slice(0,-1));let n=names.indexOf(s),i=names.indexOf(t);if([n,i].some(o=>o===-1))throw new Error(`Invalid unit of time is provided. Valid units are: ${names.join(", ")}. Both singular and plural.`);const r=i<n;if(r){const o=n;n=i,i=o}return e*constituents.slice(n,i).reduce((o,a)=>o*a,1)**(r?-1:1)},convertToMilliseconds=moize(convertTo("millisecond")),convertToSeconds=moize(convertTo("second"));moize(convertTo("minute"));const convertToHours=moize(convertTo("hour")),convertToDays=moize(convertTo("day"));moize(convertTo("month"));const secondsToHM=t=>{if(!t)return"";t=Number(t);const e=Math.floor(t/3600),s=Math.floor(t%3600/60),n=e>0?`${e} %h%`:"",i=s>0?`${s} %m%`:"",r=t>0&&t<60?`${Math.floor(t)} %s%`:"";return`${n} ${i} ${r}`},compareStrings=(t,e)=>t>e?1:t<e?-1:0,replaceAt=(t,e,s,n)=>{if(e>=t.length)return t.valueOf();const i=t.split("");let r;for(r=0;r<=i.length;r++)i[r]&&r>=e&&r<=s&&(i[r]="");return i[e]=n,i.join("")},padZero=(t,e)=>t.padStart(e,"0"),getFirstSentence=t=>{var e;return t&&((e=t.split("."))==null?void 0:e[0])||""},replaceByNotEmpty=(t,e,s)=>s?t.replace(e,`${s}`):t,getSafeUserString=t=>typeof t=="string"?t.replaceAll(/['`()\\|~^*@<>$]/gi,""):"";class AbstractStore{constructor(){$(this,"store");this.store=null}set(e,s,n){return this.store.setItem(e,JSON.stringify(s)),s}get(e){const s=this.store.getItem(e);if(typeof s!="string")return null;try{return JSON.parse(s)}catch{return s}}getWithDefault(e,s){const n=this.get(e);return n==null?s:typeof s=="string"?n:typeof n=="string"?s:n}remove(e,s){this.store.removeItem(e)}removeAll(){this.store.clear()}getAll(){const e={};for(let s=0;s<this.store.length;s++){const n=this.store.key(s);if(!n)continue;const i=n.toString();e[i]=this.get(i)}return e}}class Localstore extends AbstractStore{constructor(){super(),this.store=window.localStorage}}class Sessionstore extends AbstractStore{constructor(){super(),this.store=window.sessionStorage}}const processValue=t=>{if(t.substring(0,1)==="{")try{return JSON.parse(getSafeUserString(t))}catch{return t}return t!=="undefined"?decodeURIComponent(t):null};class Cookiestore extends AbstractStore{set(e,s,n={}){const{expires:r=new Date(Date.now()+convertToMilliseconds(120,"months")),path:o="/",secure:a=!1}=n,l={expires:r,path:o,secure:a,sameSite:"lax"},c=s!==void 0&&typeof s=="object"?JSON.stringify(s):s;return Cookies.set(e,c,l),s}get(e){const s=Cookies.get(e);return s?processValue(s):null}getAll(){const e={},s=Cookies.get();for(const n in s)Object.getOwnPropertyDescriptor(s,n)&&(e[n]=this.get(n));return e}remove(e,s){const n={};return s&&(n.path=s),Cookies.remove(e,n),null}
2removeAll(){const e=Cookies.get();for(const s in e)Object.getOwnPropertyDescriptor(e,s)&&Cookies.remove(s)}}class DummyStore extends AbstractStore{set(e,s,n){return s}get(e){return null}remove(e){}removeAll(){}getAll(){return{}}}const storageAvailable=t=>{const e=window[t];try{const s="__storage_test__";return e.setItem(s,s),e.removeItem(s),!0}catch(s){const n={nonFf:22,ff:1024},i={nonFf:"QuotaExceededError",ff:"NS_ERROR_DOM_QUOTA_REACHED"},r=s.code===n.nonFf||s.code===n.ff||s.name===i.nonFf||s.name===i.ff;return s instanceof DOMException&&r&&(e==null?void 0:e.length)!==0}},cookieAvailable=()=>{if(!navigator.cookieEnabled)return!1;document.cookie="cookietest=1";const t=document.cookie.indexOf("cookietest=")!==-1;return document.cookie="cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT",t},dummyStore=new DummyStore;let localStore=dummyStore,sessionStore=dummyStore,cookieStore=dummyStore,storage$1=dummyStore;typeof window<"u"&&(cookieAvailable()&&(cookieStore=new Cookiestore,storage$1=cookieStore),storageAvailable("localStorage")&&(localStore=new Localstore,storage$1=localStore),storageAvailable("sessionStorage")&&(sessionStore=new Sessionstore));const COLORS_BY_SEVERITY={error:"red",warn:"yellow",notice:"green",info:"green",debug:"blue",trace:"blue"},COLORS_HEX_CODES={blue:"#4b88ff"},PROD_MUTED_SEVERITIES=["info","debug","trace"],BROWSER_LOG_METHODS_BY_SEVERITY={error:"log",warn:"log",notice:"log",info:"log",debug:"log",trace:"debug"},consoleLogger=(t,e)=>{const s=COLORS_BY_SEVERITY[t];if(!localStore.get("debug")&&PROD_MUTED_SEVERITIES.includes(t))return Function();{const n=BROWSER_LOG_METHODS_BY_SEVERITY[t]||"log",i=COLORS_HEX_CODES[s]||s;return Function.prototype.bind.call(console[n],console,`%c[${e}]`,`color: ${i}; font-weight: bold;`)}},logger$1=t=>({error:consoleLogger("error",t),warn:consoleLogger("warn",t),notice:consoleLogger("notice",t),info:consoleLogger("info",t),debug:consoleLogger("debug",t),trace:consoleLogger("trace",t)});var define_process_env_default$1={};class LokiLogger{constructor(e){$(this,"error");$(this,"warn");$(this,"info");$(this,"status",0);$(this,"ctx");$(this,"errorDetails");["error","warn","info"].forEach(n=>{define_process_env_default$1.LOG_FORMAT==="loki"?this[n]=this.logLoki(n,e):this[n]=this.logDefault(n,e)})}setStatus(e){return this.status=e,this}setCtx(e){return this.ctx=e,this}setErrorDetails(e){this.errorDetails=e}reset(){this.status=0,this.ctx=void 0,this.errorDetails=void 0}logLoki(e,s){return(...n)=>{var i,r,o;console.log(JSON.stringify({severity:e,date:dayjs().format("YYYY-MM-DD HH:mm:ss:SSS"),message:n.join(" "),errorDetails:this.errorDetails,context:s,ip:((i=this.ctx)==null?void 0:i.ip)||"",method:((r=this.ctx)==null?void 0:r.method)||"",url:((o=this.ctx)==null?void 0:o.originalUrl)||"",status:this.status,pid:define_process_env_default$1.pm_id||""})),this.reset()}}logDefault(e,s){return(...n)=>{var r,o;const i=[];this.ctx&&i.push(`${(r=this.ctx)==null?void 0:r.method} ${(o=this.ctx)==null?void 0:o.originalUrl} - ${this.status}`),this.errorDetails&&i.push(this.errorDetails),logger$1(s)[e](...i,...n),this.reset()}}}const SEO_BOTS_DEFAULT_UA_REGEXP="Googlebot|YandexBot|YandexMobileBot",URLS={account:"/v2/account",login:"/v2/login",qrLogin:"/v2/login/qr",logout:"/logout",genres:"/genres",channels:"/channels",channelsV2:t=>`/tv/v2/channels?tv-asset-token=${t}`,medias:t=>`/tv/v2/medias?tv-asset-token=${t}`,channel:t=>`/channels/${t}`,epg:{onAir:"/epg/v2/on-air",schedules:{index:t=>`/epg/v2/schedules/${t}/index`,spread:t=>`/epg/v2/schedules/${t}/spread`}},profileRestrictions:"/v2/settings/profile/restrictions",recommendedChannels:"/channels-recommendations/v1",recentAndFavChannels:"/walls/1",channelsNotForPurchase:"/subscription-options/tv/channels-not-for-purchase/v2",playbackInfo:t=>`/playback-info/${t}`,playbackInfoMedia:t=>`/playback-info-media/${t}`,dvrAvailability:t=>`/playback-info/${t}/dvr-availability`,appInfo:"/app-info",speedTests:"/app-info/speed-tests/v2",favorites:"/favorites",profile:"/account/profile",managingLogin:"/v2/managing-login",managingLogout:"/v2/managing-logout",managingLoginWithVerifiedContacts:"/v2/managing-login/with-verified-contacts",managingLoginMethods:"/v2/managing-login/methods",currentSubscriptions:"/account/v3/current-subscriptions",changeProfile:"/account/change-profile",changeProfileV2:"/v2/account/change-profile",createProfile:"/v2/account/profile",changePassword:"/account/change-password",updateProfile:t=>`/v2/account/profile/${t}`,deleteProfile:t=>`/v2/account/profile/${t}`,getProfile:t=>`/v2/account/profile/${t}`,vod:{sources:"/vod/v2/",favorites:"/vod-list/v1",categories:t=>`/vod/v2/${t}/categories`,collections:t=>`/vod/v2/${t}/collections`,collectionTitles:(t,e)=>`/vod/v2/${t}/collections/${e}/titles`,similarities:(t,e,s)=>`/vod/v2/${t}/titles/${e}/similarities?audience-token=${s}`,titles:t=>`/vod/v2/${t}/titles`,titlesMeta:t=>`/vod/v2/${t}/titles-meta`,searchTitles:t=>`/vod/v2/${t}/search-titles`,title:(t,e)=>`/vod/v2/${t}/titles/${e}`,season:(t,e,s)=>`/vod/v2/${t}/titles/${e}/seasons/${s}`,seasonEpisodes:(t,e,s)=>`/vod/v2/${t}/titles/${e}/seasons/${s}/episodes`,allEpisodes:(t,e)=>`/vod/v2/${t}/titles/${e}/episodes`,playback:t=>`/playback/vod/v2/${t}`,playbackUpdate:(t,e)=>`/playback-updates/vod/v1?pbs_id=${t}&close_pbs=${e}`,playbackLsHls:t=>`/playback/ls-hls-video/v1/${t}`,ivi:{lightServer:"https://api.ivi.ru/light",lightServerMock:"http://localhost:8081/ivi",session:t=>`/v2/account/services/ivi?session=${t}`,playback:t=>`/playback/vod/ivi/${t}`},amedia:{playback:t=>`/playback/vod/amedia2/v1/${t}`},megogo:{playback:t=>`/playback/vod/megogo/v1/${t}`}},providerInfo:t=>`/providers/v1/internal-providers/${t}/info`,providerInfoV2:"/providers/v2/internal-provider-info",registration:{byPhone:"/account/register"},restorePassword:"/v2/account/restore-password",restorePasswordByLink:(t,e)=>`/account/restore-password/${e}/${t}`,contactsVerification:{methods:"/contacts-verification/v1/methods",startWithAccountSession:"/contacts-verification/v1/start-with-account-session",start:"/contacts-verification/v1/start",startRecaptcha:"/contacts-verification/v1/start-recaptcha",retry:"/contacts-verification/v1/retry",verify:"/contacts-verification/v1/verify",verifyV2:"/contacts-verification/v1/verify/v2",unlinkPhone:"/user/v1/detach-phone-with-verified-cd",setPhone:"/user/v1/set-phone-with-verified-cd",techSim:"/contacts-verification/v1/verify-with-password/tech-sim",captchaData:"/contacts-verification/v1/captcha-data",captchaImage:t=>`/contacts-verification/v1/captcha-image/${t}/image.png`},assetTokens:"/user/v1/asset-tokens",assetTokensV2:"/user/v1/asset-tokens/v2",availableLogins:"/auth/v1/with-verified-contacts/available-logins",register:"/registration/v1/with-verified-contacts/smotreshka/v3",registerMobile:"/registration/v1/with-verified-contacts/mobile",loginWithVerifiedContacts:"/v2/login/methods/with-verified-contacts",sendPassword:"/change-password/v1/with-verified-contacts/methods/send-password",promoCodeCheck:"/promocode/check-value/v1",registerWithPromoCode:"/registration/v1/with-verified-contacts/smotreshka-with-promocode/v2",registerWithPromoCodeMobile:"/registration/v1/with-verified-contacts/mobile-with-promocode",registerSimPassword:"/registration/v1/login-password/mobile-with-promocode",contactsVerificationSimPassword:"/contacts-verification/v1/verify-with-password/tech-sim",regions:"/providers/v1/regions",providers:"/providers/v1/providers",statistics:"/send-stats/channel-playing",trialRegistrationStatus:"/trial/registration/v1/status",quickSubscribe:{allAvailableSubscriptionOptions:"/subscription-options/all-available/v2",vodSubscriptionOptions:"/subscription-options/vod/v2",vodSubscriptionOptionsV3:"/subscription-options/vod/v3",tvSubscriptionOptions:t=>`/subscription-options/tv/v2/${t}`,tvSubscriptionOptionsV3:t=>`/subscription-options/tv/v3/${t}`,createSubscriptionWithVerifiedPhone:"/account/v3/create-subscription/with-verified-phone",createSubscription:"/v2/account/subscriptions",createSubscriptionUpsale:"/account/v3/create-subscription/upsale/v1",createSubscriptionUpsaleV2:"/account/v3/create-subscription/upsale/v2",currentSubscriptions:"/current-subscriptions/v2",enableAutoRenew:t=>`/generic-subscriptions/enable-auto-renew/v1/${t}`,disableAutoRenew:t=>`/generic-subscriptions/disable-auto-renew/v1/${t}`,autoRenew:t=>`/generic-subscriptions/renew/v1/${t}`,offersSet:t=>`/subscription-options/offers-set/v1/${t}`,subscriptionShop:t=>`/subscription-options/subscriptions-shop-promo/v1?audience-token=${t}`},unsubscriptionRetention:{begin:"/unsubscription-retention/begin/v1",end:"/unsubscription-retention/end/v1",subscriptionOptions:"/subscription-options/unsubscription-retention/v1"},yakassa:{paymentMethod:"/yakassa/v1/payment-method",removePaymentMethod:"/yakassa/v1/payment-method/remove",archivedSubscriptions:"/yakassa/v1/archived-subscriptions",subscriptions:"/yakassa/v1/subscriptions",subscription:t=>`/yakassa/v1/subscriptions/${t}`,subscriptionPayments:t=>`/yakassa/v1/subscriptions/${t}/payments`,activateSubscription:t=>`/yakassa/v1/subscriptions/${t}/activate`,cancelSubscription:t=>`/yakassa/v1/subscriptions/${t}/cancel`,renewSubscriptionWithExistedPm:t=>`/yakassa/v1/subscriptions/${t}/renew-with-existed-pm`,renewSubscriptionWithNewPm:t=>`/yakassa/v1/subscriptions/${t}/renew-with-new-pm`,offer:t=>`/yakassa/v1/offers/${t}`,lastPaymentFromKassa:t=>`/yakassa/v1/subscriptions/${t}/last-payment-from-kassa`,createSubscription:"/yakassa/v1/create-subscription/v2"},offers:{listOfOffers:"/offers/v3/",offer:t=>`/offers/v3/${t}`,offerAllChannels:t=>`/offers/v3/${t}/all-channels`,offerShowcaseChannels:t=>`/offers/v3/${t}/showcase-channels`},phoneInfoV1:"/phone-info/v1",phoneInfoV2:"/phone-info/v2",bow:{proxy:"/buy-on-website/proxy",tokenData:"/buy-on-website/token-data",qsStateForTransaction:t=>`/account/v3/qs-state-for-transaction/${t}`},pauses:{vod:{titles:"/pause/vod/v1/titles",title:(t,e)=>`/pause/vod/v1/titles/${t}/${e}`,delete:(t,e)=>`/pause/vod/v1/titles/${t}/${e}/forget`},tv:"/pauses"}
2,home:{banners:"/banners/v1/home-carousel",vodCollectionsV2:t=>`/vod/home/collections/v2?audience-token=${t}`,vodCollectionsV3:t=>`/vod/home/collections/v3?audience-token=${t}`},promoElements:t=>`/promo/v2/elements?audience-token=${t}`,mtsby:{captcha:"/captcha",auth:"/v2/login/methods/mts-bel-sms-auth"},kt:{captcha:"/contacts-verification/v1/captcha"},uztel:{auth:"/v2/login/methods/uztelecom-ip"},megafon:{auth_18p:"/v2/login/methods/megafon-18p-token",auth:"/v2/login/methods/megafon-token"},diagnostics:{ip:{m9:"https://plbl.m9.lfstrm.tv/api/my-ip",uz:"https://plbl.uz.lfstrm.tv/api/my-ip"}},evictedSession:"/evicted-session/v1",appSections:t=>`/app-sections?audience-token=${t}`,oldSmotreshkaPremiumPage:"https://old.smotreshka.tv/api/connection_premium_request",brandingMethods:"/brandingMethodList",premiumPageProviderBySlug:t=>`/premium-page/providers-enhancement/${t}`,seoRules:"/seo-rules",redirects:"/redirects",homeScreenConfig:"/home-screen-config-list",headCustomCode:"/head-custom-code",premiumTwo:"/premiumtwo",ssrPath:"/ssr",favicon:"/favicon.svg",externalPlayer:{tvSettings:"/external-player/tv-settings/v1",vod:{hboMax:t=>`/external-player/vod/amedia2/hbo-max-url/v1/${t}`}},popupNotices:{elements:t=>`/promo/v2/notices?audience-token=${t}`,whatToShow:"/notices/what-to-show/v1",reportAction:"/notices/report-action/v1"},marketingExternalCodes:"/marketing/external-codes",searchHistory:{start:"/search-history/v1/search-started",finish:"/search-history/v1/search-finished",useTvChannel:"/search-history/v1/tv-channel-used",useVodTitle:"/search-history/v1/vod-title-used",getHistory:"/search-history/v1/history",searchV2:"/search/v2",report:"/search-history/v2/report-search",useTvChannelV2:"/search-history/v2/tv-channel-used",useVodTitleV2:"/search-history/v2/vod-title-used"},clientAnalytics:"/client-analytics/unified-events/v1",backgroundJobsFiles:"/background-jobs/files"},STORE_KEYS={genreId:"genreId",player:{mute:"player_mute",volume:"player_volume",audioTrackTv:"player_tv_audio_track",audioTrackAmedia:"player_vod_audio_track_amedia",audioTrackMegogo:"player_vod_audio_track_megogo",channelsSettings:"player_tv_channel_settings"},vod:{titlesLimit:"vod_titlesLimit",sourceId:"vod_sourceId",categoryId:"vod_categoryId",titleId:"vod_titleId",collectionId:"vod_collectionId",genreIds:"vod_genreIds",pauseTimes:"vod_pauseTimes",ivi:{uid:"vod_ivi_uid"}},test:{feUrl:"test_feUrl",showSettings:"test_showSettings"}},EVENTS={changeProfile:"CHANGE_PROFILE",player:{play:"PLAYER_PLAY",pause:"PLAYER_PAUSE",reloadStream:"PLAYER_RELOAD_STREAM",changeLanguage:"PLAYER_CHANGE_LANGUAGE",fastForward:{start:"PLAYER_FAST_FORWARD_START",stop:"PLAYER_FAST_FORWARD_STOP"},rewind:{start:"PLAYER_REWIND_START",stop:"PLAYER_REWIND_STOP"},seek:"PLAYER_SEEK",changeLevel:"PLAYER_CHANGE_LEVEL",loadFrag:"LOAD_FRAG",manifestLoaded:"MANIFEST_LOADED"},qs:{handleClose:"handleClose"}},CHANNEL_LIST_POSTER_HEIGHT=6*16,COMPONENT_TYPES={AboutPage:"AboutPage",Accordion:"Accordion",Advantages:"Advantages",BackgroundWithText:"BackgroundWithText",Banner:"Banner",ButtonFileDownload:"ButtonFileDownload",Device:"Device",HowToWatch:"HowToWatch",ImageSlider:"ImageSlider",ImageTextButton:"ImageTextButton",TextOnly:"TextOnly",TvWizard:"TvWizard"},ACCOUNT_ANONYMOUS={id:"",profiles:[],users:[],provider:void 0,next_provider:void 0,anonymous:!0,delete_reason:"",is_phone_verified:!1,profile:void 0,user:void 0,IVI:void 0},MODALS={adultOnboarding:"adultOnboarding",phoneVerification:"phoneVerification",skipPromoOffers:"skipPromoOffers",subscriptionShop:"subscriptionShop",trialGift:"trialGift",verificationSubscription:"verificationSubscription"},PLAYBACK_METHODS={amedia2V1:"amedia2_v1",iviTwoSteps:"ivi_two_steps",iviWithIntegrationParams:"ivi_with_integration_params",megogoV1:"megogo_v1",smotreshkaPlaybackInfo:"smotreshka-playback-info",smotreshkaVodV2:"smotreshka_vod_v2"},THRESHOLDS={tv:{hideOverlayAfterMilliseconds:3e3,shortJumpSeconds:10,seekStep:{normal:10,medium:30,fast:60},seekLengthToSwitchToMedium:20,seekLengthToSwitchToFast:40,channelSwitchDelay:300},subscribes:{dateUTCMultiplier:1e3},searchDelay:500},CHUNK_LENGTH=6,COOKIE_NAMES={advCake:"advcake_track_id",analyticsToken:"analytics_token",audienceToken:"audience_token",deviceUuid:"ua_uuid",feCookie:"feCookie",hideRetryAlert:"hide_retry_alert",languageCode:"languageCode",profileConfirmationPeriod:"profile_confirmation_period",profileConfirmed:"profileConfirmed",promoCode:"promo_code",retryBlockFor
2Card:"retry_block_for_card",tvAssetToken:"tv_asset_token",welcomeScreenConfirmed:"welcomeScreenConfirmed"},LOCAL_STORAGE_NAMES={archivedSubs:"archivedSubs",feBaseUrl:"feBaseUrl",isSmartAppBannerClosedByUser:"isSmartAppBannerClosedByUser",reviewsDisabled:"reviewsDisabled",userLastItemKey:"userMenuLastItem",utmParameters:"utmParameters",unsubscriptionRetention:"unsubscriptionRetention",lfstrmPartner:"lfstrm_partner",lfstrmPartnerTs:"lfstrm_partner_ts"},TV_SPECIAL_GENRES={all:"",recommended:"__RECOMMENDED__",favourite:"__FAVOURITE__",recentlyWatched:"__LAST_WATCHED__",available:"__AVAILABLE__"},TV_SORTING={ascendingNumber:"ascendingNumber",descendingNumber:"descendingNumber",ascendingName:"ascendingName",descendingName:"descendingName"},TV_SORTING_GENRE_CHANNELS_BLOCK={recommendationPriority:"recommendationPriority",keyNumber:"keyNumber"},PROFILE_ACTIONS={CREATE:"create",CHANGE:"change",UPDATE:"update",DELETE:"delete"},PROFILE_RESTRICTION_IDS={COMMON:"2",ADULT:"adult"},EPG_SLIDER_LEFT_COUNT=3,EPG_SLIDER_RIGHT_COUNT=7,EPG_MIN_PROGRAM_DURATION=180,GTM_EVENT_TIMEOUT=100;convertToMilliseconds(20,"second");const HTTP_CODES={OK:200,NOT_MODIFIED:304,BAD_REQUEST:400,FORBIDDEN:403,NOT_FOUND:404,NOT_ALLOWED:405,CONFLICT:409,GONE:410,PRECONDITION_FAILED:412,NOT_ALLOWED_FOR_LOCATION:451,IVI_NOT_ALLOWED_FOR_LOCATION:4501,SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,IVI_UNAVAILABLE_ON_SITE:4520,IVI_NOT_PURCHASED:4514,IVI_NOT_PAID:4516,EXISTING_LOGIN:4091},HTTP_PLAYER_BAD_RESPONSE_CODES=[HTTP_CODES.NOT_FOUND,HTTP_CODES.GONE,HTTP_CODES.BAD_REQUEST,HTTP_CODES.SERVER_ERROR],IVI_FORBIDDEN_CODES=[HTTP_CODES.IVI_NOT_PAID,HTTP_CODES.IVI_NOT_PURCHASED,HTTP_CODES.IVI_UNAVAILABLE_ON_SITE],REGISTRATION_SMS_CODE_LENGTH=4,MTS_AUTH_SMS_CODE_LENGTH=5,RESEND_SMS_CODE_TIMEOUT=30,PROFILE_PIN_LENGTH=4,REGISTRATION_RESEND_SMS_CODE_IN_SECONDS=10,REGISTRATION_SESSION_LIFETIME=6e5,PLAYER_DEFAULT_VOLUME=.8,TV_PLAYER_HIDE_OVERLAY_TIMEOUT=250,ARCHIVE_PLAYER_TICK_OFFSET=.21,TV_PLAYER_TICK_OFFSET=.06,PLAYER_OFFSET_DURATION=1,CHANNEL_PLAYING_STATISTIC_SAFE_TIME_IN_SECONDS=2,NOTIFICATION_SIMPLE_HIDE_TIMEOUT_5S=5e3,NOTIFICATION_SIMPLE_HIDE_TIMEOUT_10S=1e4,REGISTRATION_CAPTCHA_LENGTH=6,REGISTRATION_TIMEOUT_AFTER_SIGN_IN=3e3,DEFAULT_SLIDES_AMOUNT=18,DEFAULT_TILES_AMOUNT=42,DEFAULT_CHANNELS_AMOUNT=12,MOBILE_WINDOW_WIDTH_MAX=599,TABLET_WINDOW_WIDTH_MIN=600,TABLET_WINDOW_WIDTH_MAX=959,DESKTOP_WINDOW_WIDTH_MIN=960,DESKTOP_S_WINDOW_WIDTH_MAX=1279,SUBSCRIPTION_STATUSES={PENDING:"pending",CANCELED:"canceled",WAITING_FOR_CAPTURE:"waiting_for_capture",SUCCEEDED:"succeeded",ACTIVE:"active",IN_RETRY:"in_retry"},SUBSCRIPTION_STATUSES_REASONS={CANCELED_BY_MERCHANT:"canceled_by_merchant"},YAKASSA_RESPONSE_CODES={SUBSCRIPTION_ALREADY_EXISTS:"yakassa.subscription_already_exists",NO_VERIFIED_PHONE:"yakassa.no_verified_phone_number"},CONTACT_VERIFICATION_OUTDATED_ERROR_CODE=4031,CONTACT_VERIFICATION_ERROR_CODE=4032,SUBSCRIPTION_FORBIDDEN_ERROR_CODE=4033,GET_TRIAL_STATUS_ERROR_CODE=9991,SUBSCRIPTION_STEPS={SELECT_VERIFICATION:"SelectVerificationSubscription",PASSWORD_VERIFICATION:"PasswordVerificationSubscription",PHONE_VERIFICATION:"PhoneVerificationSubscription",DETAIL:"SubscriptionDetails"},SUBSCRIBE_STEP_WITH_BACK_BUTTON=[SUBSCRIPTION_STEPS.SELECT_VERIFICATION,SUBSCRIPTION_STEPS.PASSWORD_VERIFICATION,SUBSCRIPTION_STEPS.PHONE_VERIFICATION,SUBSCRIPTION_STEPS.DETAIL],EPG_TOP_MARGIN=350,PHONE_INFO_STATUSES={SUPPORTED:"SUPPORTED",UNSUPPORTED:"UNSUPPORTED",TECHSIM:"TECHSIM"},MEGAFON_IS_TECHNICAL_PARAM="techSimPassword",PLAYER_ERROR_CODES={COMMON:"common",DVR:"dvr",PROVIDER_ERROR:"provider-error",INTERNAL:"internal"},VERIFICATION_METHODS={PHONE_WITH_ACCOUNT_SESSION:"phone-with-account-session"},REGISTRATION_TRIAL_STATUSES={unknown:"unknown",processStarted:"process_started",created:"trial_is_created"},HIDE_PLAYER_ALERT_DELAY=3e3,SUBSCRIPTION_METHOD_NAMES={AUTHENTICATED:"authenticated",PHONE_COLLECT_INSTANT:"sub20-phone-collect-instant",PHONE_COLLECT_DELAYED:"sub20-phone-collect-delayed",UPSALE:"sub20-upsale-v1",UPSALE_V2:"sub20-upsale-v2",UPSALE_V21:"sub20-upsale-v21",PROMO_OFFER:"qs22-promo-offer",SUB21_YAKASSA:"sub21-yakassa",SUB20_YAKASSA_MVP:"sub20-yakassa-mvp"},YAKASSA_SUBSCRIPTION_METHODS=[SUBSCRIPTION_METHOD_NAMES.SUB20_YAKASSA_MVP,SUBSCRIPTION_METHOD_NAMES.SUB21_YAKASSA],RENDERING_METHOD_NAMES={BILLING_PERIOD:"qs21-billing-period-option",OPERATOR_CONTACT_INFO:"operator-contact-info",SUBSCRIPTION_SHOP:"qs-subscription-shop",SUBSCRIPTION_SHOP_ADJUSTED:"qs-subscription-shop-adjusted"},MANAGEMENT_METHOD_NAMES={YAKASSA:"mm-yakassa-v1",AUTO_RENEWABLE:"mm-autorenewable-v1",UNSUB_INFO:"mm-unsub-info-v1"},SUPPORTED_MANAGEMENT_METHODS=Object.values(MANAGEMENT_METHOD_NAMES),KEY_CODE={backspace:8,enter:13},BLANK_IMAGE="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",FALLBACK_RENDERING_METHODS=["qs10-legacy-default","qs20-yakassa-v2","qs22-promo-offer","qs22-unsub-retention-offer"],AUTH_STEPS={start:"start",captcha:"captcha",checkCode:"checkCode",provider:"provider",finish:"finish",multipleLogins:"multipleLogins",phoneFoundBeforeReset:"phoneFoundBeforeReset",phoneFoundAfterReset:"phoneFoundAfterReset",retryTrialStatus:"retryTrialStatus",error:"error",outdated:"outdated",phoneNotFound:"phoneNotFound",unlinkLogin:"unlinkLogin",success:"success",fail:"fail",unlinkOneOfMultipleLogins:"unlinkOneOfMultipleLogins",emailFinish:"emailFinish",auth:"auth",authMts:"authMts",phoneIsNotAttached:"phoneIsNotAttached",phoneUnsupported:"phoneUnsupported",promoCode:"promoCode",promoCodeNotFound:"promoCodeNotFound",promoCodeUserExist:"promoCodeUserExist",promoCodeSuccess:"promoCodeSuccess",simPassword:"simPassword",autoLoginFailed:"autoLoginFailed",recommendProvider:"recommendProvider",skipProvider:"skipProvider",confirmProvider:"confirmProvider",promoOffers:"promoOffers",subscriptionSuccess:"subscriptionSuccess",subscriptionFailed:"subscriptionFailed",promoCodeError:"promoCodeError",autoLoginMegafonFailed:"autoLoginMegafonFailed",evictedDevices:"evictedDevices"},GA_AUTH_STEPS=[AUTH_STEPS.error,AUTH_STEPS.outdated],AUTH_AND_REG_URLS={defaultReg:"/reg",defaultLogin:"/login",defaultLoginSmotreshka:"/login/smotreshka",defaultLoginSms:"/login/sms",defaultLoginN3:"/login/n3",defaultLoginPasswd:"/login/passwd",defaultReset:"/reset",defaultCode:"/code",defaultRestore:"/restore-password",qrLogin:"/qr-login",qrSuccess:"/qr-success"},AUTO_LOGIN_MEGAFON_ROUTES_NAMES={autoLogin18p:"login-mf",autoLogin:"login-mf-main"},AUTH_METHODS={sms:"sms",smsAndPasswd:"smsAndPasswd",n3:"n3",smotreshka:"smotreshka"},CORRECT_PHONE_LENGTH=12,DEFAULT_VOD_CATEGORIES={amedia:"series",ivi:"14",megogo:"16",moretv:"4",newbasevod:"series",premier:"novinki",start:"mov
2ies",vipplay:"movies"},VOD_SESSION_LIFETIME=10*60*1e3,VOD_SESSION_QUEUE_LIMIT=20,VOD_SESSION_SEEK_EVENTS_TIMEOUT=1e3,VOD_SESSION_STATE={playing:"playing",paused:"paused",stopped:"stopped"},VOD_SESSION_USER_EVENT={start:"start",timeline:"timeline",displayMode:"displayMode",continue:"continue",stop:"stop"},VIDEO_DISPLAY_MODE={audioOnly:"audio-only",fullscreen:"fullscreen",windowed:"windowed"},VOD_TITLE_ENHANCED_TEMPLATE={preview:void 0,details:void 0,pauses:[],loaded:!1,loading:!1},VOD_DETAILS_TOP_BACKGROUND_WIDTH=1440,VOD_DETAILS_TOP_BACKGROUND_HEIGHT=576,BRANDING_METHODS_OPTIONS_ID={showIcon:"showIcon",showLegal:"showLegal"},BRANDING_METHODS_DEFAULT="default",ADULT_ONBOARDING_STEPS={EnterPin:"EnterPin",VerifySession:"VerifySession",NoProfile:"NoProfile",OneProfile:"OneProfile",SetPin:"SetPin",StartStep:"StartStep",YourPin:"YourPin"},ADULT_ONBOARDING_PIN_ACTION={create:"create"},ADULT_ONBOARDING_PROFILE_CHANGE_TIMEOUT=3500,ADULT_ONBOARDING_MAX_NUMBER_OF_TRIES=3,ADULT_OFFER_ID="6481a2afc9e80accd93d5dda",ADULT_CHANNELS={"5aead51021887f04724d177e":{title:"Barely Legal",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL2JhcmVseV9sZWdhbF9uZXcucG5n"},"59ac8dcf21887f680800fc71":{title:"Blue Hustler HD",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL2JsdWVfaHVzdGxlci5wbmc="},"5a3a31c121887fb740dc5969":{title:"Erox",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL2Vyb3gucG5n"},"58bdcf5021887f26e6d9b432":{title:"О-ля-ля",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL29sYWxhLnBuZw=="},"62e406074b4b5eba1d6cf609":{title:"Red Lips HD",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cHM6Ly9pbWcuYjYxMi50aWdodHZpZGVvLmNvbS9jaGFubmVscy9yZWRfbGlwcy5wbmc="},"57a5a3ca8daaa84636062cde":{title:"Русская ночь HD",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL3J1c3NrYXlhLW5vY2gucG5n"},"5a65d08921887ff2831c1e99":{title:"Шалун HD",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL3NoYWx1bi5wbmc="},"6405daef652c7818e3e76fa6":{title:"Brazzers TV Europe",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL2JyYXp6ZXJzLnBuZw=="},"641d94056bda72612718db63":{title:"Playboy",logo:"https://megafon.server-img.lfstrm.tv/image/aHR0cDovL2ltZy5iNjEyLnRpZ2h0dmlkZW8uY29tL2NoYW5uZWxzL3BsYXlib3kucG5n"}},DRM_SYSTEMS={fairplay:"fairplay",playready:"playready",widevine:"widevine"},MOUSE_EVENT_BUTTONS={MAIN_BUTTON:0},MANAGING_LOGIN_METHODS={password:"password",widthVerifiedContacts:"with-verified-contacts"},PHONE_INFO_VERIFICATION_METHODS={fixedProvider:"fixedProvider",recommendProvider:"recommendProvider",selectProvider:"selectProvider"},BILLING_RENDERING_METHOD_NAME="qs21-billing-period-option",FALLBACK_RENDERING_METHOD_NAME="qs21-yakassa",SENTRY_DSN="https://[email protected]/38",PREROLL_TIME=5e3,PROMO_CODE_METHODS={registration:"registration"},HOME_SCREEN_SEQUOIA_COMPONENTS=["home-banners","home-history","home-suggested-channels","home-recent-channels","home-channel-collections","home-vod-tiles","home-vod-mega-collections","home-vod-collections"],DEFAULT_HOME_SCREEN_CONFIG=[...HOME_SCREEN_SEQUOIA_COMPONENTS],DEFAULT_VOD_SCREEN_CONFIG=["home-vod-tiles","home-vod-mega-collections","home-vod-collections"],DEFAULT_SEARCH_SCREEN_CONFIG=["home-vod-tiles","plain-image-16x9","home-vod-collections"],POPUP_NOTICE_RENDERING_METHODS={defaultPopup:"default-popup",windowBgPopup:"window-bg-popup"},POPUP_NOTICE_IMAGE_TYPES={[POPUP_NOTICE_RENDERING_METHODS.defaultPopup]:"default-1x1",[`${POPUP_NOTICE_RENDERING_METHODS.windowBgPopup}-regular`]:"window-bg-2x1",[`${POPUP_NOTICE_RENDERING_METHODS.windowBgPopup}-mobile`]:"window-bg-1x2"},SUPPORTED_POPUP_NOTICE_RENDERING_METHODS=Object.values(POPUP_NOTICE_RENDERING_METHODS),BANNER_CAROUSEL_RENDERING_METHODS_NAMES={plainImage:"plain-image"},BANNER_VIDEO_RENDERING_METHODS_NAMES={contentBanner:"content-banner",promoBanner:"promo-banner"},BANNER_STRIP_RENDERING_METHODS_NAMES={plainImage1x1:"plain-image-1x1",plainImage16x9:"plain-image-16x9",plainPoster:"plain-poster"},BANNER_TEXT={textButton:"text-button"},BANNER_RENDERING_METHODS_NAMES={...BANNER_CAROUSEL_RENDERING_METHODS_NAMES,...BANNER_STRIP_RENDERING_METHODS_NAMES,...BANNER_VIDEO_RENDERING_METHODS_NAMES,...BANNER_TEXT},BANNER_RENDERING_METHODS=Object.values(BANNER_RENDERING_METHODS_NAMES),PROMO_ELEMENTS_ACTION_METHODS={adultOnboarding:"adult-onboarding",externalUrl:"external-url",internalRef:"internal-ref",internalRefV2:"internal-ref-v2",internalRefV3:"internal-ref-v3",internalRefV4:"internal-ref-v4",internalRefV6:"internal-ref-v6",qsOffersSetV1:"qs-offers-set-v1",noAction:"no-action"},PROMO_ELEMENTS_PLACEMENT_BLOCKS={default:"default",home:"home",homeCarouselV2:"home-carou
2sel-v2"},INTERNAL_REF_PROMO_ELEMENTS_ACTION_METHODS=Object.values(PROMO_ELEMENTS_ACTION_METHODS).filter(t=>t.startsWith("internal-ref")),INTERNAL_PROMO_ELEMENTS_ACTION_METHODS=[...INTERNAL_REF_PROMO_ELEMENTS_ACTION_METHODS,PROMO_ELEMENTS_ACTION_METHODS.qsOffersSetV1],SUPPORTED_SECTION_RENDERING_METHODS={verticalBlockV1:"vertical-blocks-v1"},SUPPORTED_PROMO_ELEMENTS_ACTION_METHODS=Object.values(PROMO_ELEMENTS_ACTION_METHODS),PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING={tvContentWall:{id:"tv-content-wall",path:t=>`/channels/${t}/about`},tvStartPlayback:{id:"tv-start-playback",path:t=>`/channels/now/${t}/watch`},vodContentWall:{id:"vod-content-wall",path:t=>t==="archive"?"/archive":`/vod/${t}`},vodCollectionPage:{id:"vod-collection-page",path:(t,e)=>`/collection/${t}/${e}`},vodTitlePage:{id:"vod-title-page",path:(t,e)=>t==="archive"?`/archive/${e}`:`/vod/${t}/${e}`},vodStartPlayback:{id:"vod-start-playback",path:(t,e,s)=>t==="archive"?`/archive/${e}`:`/vod/${t}/${e}/${s?s+"/":""}watch`},appSections:{id:"app-section",path:t=>`/s/${t}`},searchPage:{id:"global-search",path:t=>`/search?q=${t}`},subscriptionShopSubscribe:{id:"subscription-shop-subscribe",path:t=>{let e="/personal/subscriptions";const s={};return t!=null&&t.subscribeOnly&&(s.subscribe_only="true"),t!=null&&t.scrollToSection&&(s.scroll_to=t==null?void 0:t.scrollToSection),Object.keys(s).length&&(e+="?",e+=new URLSearchParams(s)),e}},subscriptionShopManage:{id:"subscription-shop-manage",path:"/personal/subscriptions?t=1"}},QS_CALLBACK_TIMEOUT=3e3,QS_STEP_NAMES={CONFIRMED:"TrialConfirmed",ERROR:"Error"},QS_SOURCE_TYPES={VOD:"vod",CHANNEL:"channel"},QS_VERIFICATION_SUBSCRIPTION_STEPS={passwordVerification:"passwordVerification",phoneVerification:"phoneVerification",selectVerification:"selectVerification"},QS_VERIFICATION_PHONE_STEPS={phoneSending:"phoneSending",verificationError:"verificationError"},QS_ADDITIONAL_ACTIONS_STEP_INDEX_DICTIONARY={phoneSending:0,verificationCode:1,verificationError:2,passwordVerification:0,phoneVerification:1,selectVerification:2},DOM_SCROLL_CONTAINER_ID="scroll-container",CONTENT_RATING_DEFAULT_AGE=12,DEFAULT_DVR_DEPTH_LIMIT_HOURS=168,DEFAULT_SEARCH_TEXT_BANNERS_BLOCK_ID="searchpage-text",DEFAULT_SEARCH_BANNERS_BLOCK_ID="searchpage-banners",UNSUBSCRIPTION_RETENTION_STEPS={advantages:"advantages",question:"question",offer:"offer"},SUPPORTED_RETENTION_METHODS=["unsubscription_retention_v1"],UNSUBSCRIPTION_RESULTS={error:"error",completed:"completed",retained:"retained"},RETENTION_OFFER_RESULT={declined:"declined",error:"error",subscribed:"subscribed",unfinished:"unfinished",unoffered:"unoffered",unsupported:"unsupported"},AUTO_RENEW_DISABLED_CUSTOM_ERROR_CODE="autoRenewDisableError",ADDITIONAL_SUBSCRIPTIONS_DEFAULT_CATEGORY_ID="all",WELCOME_SCREEN_STEPS={Welcome:"Welcome",SetPin:"SetPin",EnterPin:"EnterPin",Verification:"Verification",SuccessPin:"SuccessPin"},PROFILE_PROTECTED_STEPS={Start:"Start",DisablePin:"DisablePin",SetPin:"SetPin",Verification:"Verification"};var SEARCH_STRING_SOURCE=(t=>(t.MANUAL="manual",t.SEARCH_HISTORY="search-history",t.VOICE_INPUT="voice-input",t.CLIPBOARD="clipboard",t.DEEPLINK="deeplink",t))(SEARCH_STRING_SOURCE||{}),COLOR_CLASS=(t=>(t.accent="color-accent",t.brand="color-brand",t.error="color-error",t.success="color-success",t.warning="color-warning",t))(COLOR_CLASS||{});const SEARCH_GROUP_RENDERING_METHODS={defaultV1:"default-v1"},SUPPORTED_SEARCH_GROUP_RENDERING_METHODS=Object.values(SEARCH_GROUP_RENDERING_METHODS),CLIENT_ANALYTICS_MAX_EVENTS_COUNT=50,CLIENT_ANALYTICS_AUTH_AND_REG_SUB_FLOW={"start-reg":"startup","checkCode-reg":"phone-registration","skipProvider-reg":"phone-registration","provider-reg":"phone-registration","confirmProvider-reg":"phone-registration","outdated-reg":"phone-registration","error-reg":"phone-registration","phoneFoundBeforeReset-reg":"verify-phone","promoCode-reg":"promocode-input","start-reg-promoCode":"promocode-input","promoCodeNotFound-reg":"promocode-input","promoCodeUserExist-reg-promoCode":"promocode-input","start-login":"startup","start-login-sms":"startup","start-login-password":"startup","checkCode-login":"verify-phone","simPassword-login":"verify-phone","multipleLogins-login":"verify-phone","start-reset-sm
2s":"password-recovery","checkCode-reset":"password-recovery","start-reset-password":"password-recovery","emailFinish-reset":"password-recovery","multipleLogins-reset":"verify-phone"},CLIENT_ANALYTICS_AUTH_AND_REG_UI_PAGE={"start-reg":"auth_reg_start_login","start-reg-sms":"auth_reg_start_login","checkCode-reg":"reg_auth_phone_code_input","skipProvider-reg":"reg_phone_confirmed","provider-reg":"reg_provider_region_select","confirmProvider-reg":"reg_provider_confirmed","outdated-reg":"reg_unsuccess_reg_error","error-reg":"reg_unsuccess_reg_error","phoneFoundBeforeReset-reg":"reg_account_exist_error","promoCode-reg":"reg_promocode_input","start-reg-promoCode":"reg_promocode_success","promoCodeNotFound-reg":"reg_promocode_invalid_error","promoCodeUserExist-reg-promoCode":"reg_promocode_account_exist_error","start-login":"auth_phone_login_input","start-login-sms":"auth_phone_login_input","start-login-password":"auth_login_login_input","checkCode-login":"auth_phone_code_input","simPassword-login":"reg_techsim_password_input","multipleLogins-login":"auth_account_select","start-reset-sms":"recovery_login_sms","checkCode-reset":"recovery_login_code_from_sms","start-reset-password":"recovery_login_
2input","emailFinish-reset":"recovery_login_success","multipleLogins-reset":"recovery_login_account_select"},HBO_MAX_BRANDING_METHOD="amedia-hbo-max",CHECKBOX_ADS_AGREEMENT_ID="reg_checkbox_ads_agreement",normalizeWlAppId=t=>{switch(t){case"sm":return"smotreshka";case"galam":case"glm":return"galamtv";case"o":return"otv";case"mts":return"mtstv"}return t},getEnvVars=()=>{let t,e,s,n;if(t=window.FE_BASE_URL||"",e=window.BE_BASE_URL||"",s=window.WL_APP_ID||"",n=window.SEQUOIA_HOSTNAME||"",s=normalizeWlAppId(s),!t)throw new Error("feBaseUrl is not defined!");if(!e)throw new Error("beBaseUrl is not defined!");if(!s)throw new Error("wlAppId is not defined!");return{beBaseUrl:e,feBaseUrl:t,wlAppId:s,sequoiaHostname:n}},isEveryEnvVarValidOnClientSide=()=>{var t,e,s;return!!((t=window.FE_BASE_URL)!=null&&t.replace("%feBaseUrl%",""))&&!!((e=window.BE_BASE_URL)!=null&&e.replace("%beBaseUrl%",""))&&!!((s=window.WL_APP_ID)!=null&&s.replace("%wlAppId%",""))},storage=storage$1,wlDetector=()=>{const{wlAppId:t}=getEnvVars();return{isAkado:t==="akado",isAltel:t==="altel",isGalam:t==="galamtv",isIns:t==="ins",isIntersv:t==="intersv",isKcell:t==="kcell",isKt:t==="kt",isMegacom:t==="megacom",isMegafon:t==="megafon",isMftv:t==="mftv",isMtr:t==="mtr",isMts:t==="mtsby",isOtv:t==="otv",isOyna:t==="oyna",isN3:t==="n3",isRumo:t==="rumotv",isRzd:t==="rzd",isSanta:t==="santa",isSevensky:t==="sevensky",isSmotreshka:t.startsWith("sm"),isTele2:t==="tele2",isTtk:t==="ttk",isUcell:t==="ucell",isUztel:t==="uztel"}},sleep=t=>new Promise(e=>setTimeout(e,t)),hasAdBlock=()=>window.hasAdBlock,isAutologinEnabled=()=>wlDetector().isUztel,isOkUrl=t=>{try{new URL(t)}catch{return!1}return!0},matchUrlProtocolWithLocationProtocol=(t,e)=>e?useHttpsProtocol(t):t,useHttpsProtocol=t=>{try{return(t||"").replace("http://","https://")}catch{return t}},removePortFromServerUrl=t=>{const e=t.split("/"),s=e[2].split(":");return e[2]=s[0],e.join("/")},isUrlExternal=t=>t?new RegExp("^(?:[a-z]+:)?//","i").test(t):void 0,getTitlePath=(t,e,s="",n="")=>(t==="archive"?["/archive",e,s,n]:["/vod",t,e,s]).filter(i=>i).join("/"),getTitlePathWithSeason=(t,e,s)=>(t==="archive"?["/archive",e,`season${s}`]:["/vod",t,e,`season${s}`]).filter(n=>n).join("/"),getMyCollectionPath=t=>`/my/${t}`,getTitleWatchPath=(t,e,s="",n="")=>`${getTitlePath(t,e,s,n)}/watch`,getChannelPath=(t,e="")=>{const s=wlDetector().isRzd?"list":"now";return`/channels/${e||s}/${t}`},getChannelAboutPath=t=>`/channels/${t}/about`,getChannelWatchPath=(t,e="")=>`${getChannelPath(t,e)}/watch`,createLinkTag=t=>{const e=document.createElement("a");return e.href=t,e},makePath=(t,e)=>{var r;const s=t.languageCode,n=((r=t.languages.find(o=>o.isDefault))==null?void 0:r.code)||"ru";return s===n?e===""?"/":e:`/${s}${e}`},makePathInHtml=(t,e)=>e.replace(/<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/g,(s,n,i)=>{const r=makePath(t,i);return`<a href=${n}${r}${n}`}),hasBadSymbols=t=>/['"`()\\|~^*@!<>$]/i.test(t),getStackTrace=()=>{try{throw new Error}catch(t){return t.stack}},log$V=logger$1("language"),getByLanguage=(t,e,s)=>!t||typeof t!="object"?null:Object.keys(t).length?e?t[e]||t[s]||null:(log$V.error("getByLanguage: languageCode was not provided. It must be provided",getStackTrace()),null):(log$V.warn("getByLanguage: translations are empty",getStackTrace()),null),enToRu=t=>t?convertLayoutRu.fromEn(t):"",transliterate=t=>{const e={а:"a",б:"b",в:"v",г:"g",д:"d",е:"e",ё:"e",ж:"j",з:"z",и:"i",к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",х:"h",ц:"c",ч:"ch",ш:"sh",щ:"shch",ы:"y",э:"e",ю:"u",я:"ya",h:"h",d:"d"};return t.toLowerCase().trim().split("").map(s=>e[s]||"").join("")},cleanupPhone=(t="",e=!0)=>{const s=String(t).trim().replace(/\D/g,"");return wlDetector().isUztel?s.slice(3):(e?"+":"")+s},formatPhone=(t="")=>{const e=String(t).trim().replace(/\D/g,"");if(e.length!==11)return e;{const s=(n,i)=>e.substring(n,i);return`+${e[0]} (${s(1,4)}) ${s(4,7)}-${s(7,9)}-${s(9,11)}`}},accountSelector=t=>t.account,isAnonymousSelector=t=>{var e;return!!((e=accountSelector(t))!=null&&e.anonymous)},providerSelector=t=>{var e,s;return(s=(e=accountSelector(t))==null?void 0:e.provider)==null?void 0:s.provider},providerIdSelector=t=>{var e;
2return((e=providerSelector(t))==null?void 0:e.id)||""},providerNameSelector=t=>{var e;return((e=providerSelector(t))==null?void 0:e.name)||""},userSelector=t=>{var e;return(e=accountSelector(t))==null?void 0:e.user},userIdSelector=t=>{var e;return((e=accountSelector(t))==null?void 0:e.id)||""},userEmailSelector=t=>{var e;return((e=userSelector(t))==null?void 0:e.email)||""},userLoginSelector=t=>{var e;return((e=userSelector(t))==null?void 0:e.login)||""},profilesSelector=t=>{var e;return((e=accountSelector(t))==null?void 0:e.profiles)||[]},cleanupPhoneSelector=t=>{var e,s;return cleanupPhone((s=(e=t.account)==null?void 0:e.user)==null?void 0:s.phone,t.authAndReg.usePlusInPhoneMethods.registration)},account=Object.freeze(Object.defineProperty({__proto__:null,accountSelector,cleanupPhoneSelector,isAnonymousSelector,profilesSelector,providerIdSelector,providerNameSelector,providerSelector,userEmailSelector,userIdSelector,userLoginSelector,userSelector},Symbol.toStringTag,{value:"Module"})),currentStepSelector$1=t=>t.adultOnboarding.currentStep,nextStepSelector=t=>t.adultOnboarding.nextStep,stepsHistorySelector=t=>t.adultOnboarding.stepsHistory,pinActionSelector=t=>t.adultOnboarding.pinAction,adultProfileSelector=t=>{var e,s;return(((s=(e=t.account)==null?void 0:e.profiles)==null?void 0:s.filter(n=>n.restriction===PROFILE_RESTRICTION_IDS.ADULT))||[])[0]},adultOnboarding$1=Object.freeze(Object.defineProperty({__proto__:null,adultProfileSelector,currentStepSelector:currentStepSelector$1,nextStepSelector,pinActionSelector,stepsHistorySelector},Symbol.toStringTag,{value:"Module"})),serverTimeSelector=t=>{var e;return((e=t.appInfo)==null?void 0:e.currentTime)||0},commonServerTimeSelector=t=>{var e;return((e=t.common)==null?void 0:e.serverTime)||0},serverTimeMsSelector=t=>{const e=serverTimeSelector(t);return e?convertToMilliseconds(e,"second"):0},appInfo$1=Object.freeze(Object.defineProperty({__proto__:null,commonServerTimeSelector,serverTimeMsSelector,serverTimeSelector},Symbol.toStringTag,{value:"Module"})),isVercontCaptchaImageEnabledSelector=t=>{var e;return((e=t.authAndReg)==null?void 0:e.isVercontCaptchaImageEnabled)===!0},authAndReg$1=Object.freeze(Object.defineProperty({__proto__:null,isVercontCaptchaImageEnabledSelector},Symbol.toStringTag,{value:"Module"})),brandingMethodsSelector=t=>t.brandingMethods,brandingMethods$1=Object.freeze(Object.defineProperty({__proto__:null,brandingMethodsSelector},Symbol.toStringTag,{value:"Module"})),imageServerUrl=(t,e,s)=>`${t}?width=${e}&height=${s}`,calculateSizeByAspectRatio=(t,e,s,n)=>{let i=t,r=e;return s<n?i=Math.round(s*r/n):r=Math.round(n*i/s),{width:i,height:r}},calculateSizeWithMaxWidth=(t,e,s)=>{const n=Math.min(t,s),i=t>s?n*e/t:e;return{width:n,height:i}},getResizedImageUrlSmotreshka=(t,e,s,n,i,r)=>{try{const o=new URL(t),l=calculateSizeWithMaxWidth(e,s,3e3);return o.searchParams.set("width",l.width.toString()),o.searchParams.set("height",l.height.toString()),o.searchParams.set("quality","93"),typeof i<"u"&&o.searchParams.set("crop",i.toString()),typeof r<"u"&&o.searchParams.set("axis",r),n&&o.searchParams.set("format","png"),o.toString()}catch{return t}},getResizedImageUrl=(t,e,s,n="imageserver",i=!1,r,o)=>{if(!(e&&s))return t;switch(n){case"plain":case"start":return t;case"ivi":case"ivi.ru":return`${t}/${e}x${s}/`;case"megogo":return`${t}/pt/r${e}x${s}`;default:return getResizedImageUrlSmotreshka(t,e,s,i,r,o)}},parseMd=t=>{let e="",s=!1;const n=t.split(`
3`);for(let i=0;i<=n.length-1;i++){if(n[i]===""||n[i]==="\r")continue;let r=n[i];if(r=r.replace(/[#]{6}(.+)/g,"<h6>$1</h6>"),r=r.replace(/[#]{5}(.+)/g,"<h5>$1</h5>"),r=r.replace(/[#]{4}(.+)/g,"<h4>$1</h4>"),r=r.replace(/[#]{3}(.+)/g,"<h3>$1</h3>"),r=r.replace(/[#]{2}(.+)/g,"<h2>$1</h2>"),r=r.replace(/[#]{1}(.+)/g,"<h1>$1</h1>"),r.trim().startsWith("-")||r.trim().startsWith("+")){const o=r[0];r=r.replace(/^-(.+|-)/gm,"<li>$1</li>"),s||(s=!0,r="<ul>"+r),n[i+1]&&!n[i+1].trim().startsWith(o)&&(r=r+"</ul>")}else s&&(s=!1);r=r.replace(/^\s*(\n)?(.+)/gm,o=>/<(\/)?(h\d|ul|ol|li)/.test(o)?o:"<p>"+o+"</p>"),r=r.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3">$2</a>'),r=r.replace(/(<a [^>]*)(target="[^"]*")([^>]*>)/gi,"$1$3"),r=r.replace(/(<a [^>]*)(>)/gi,'$1 target="_blank" class="link nav-hidden"$2'),r=r.replace(/[*_]{2}([^*_]+)[*_]{2}/g,"<b>$1</b>"),r=r.replace(/[*_]{1}([^*_]+)[*[^"]_]{1}/g,"<i>$1</i>"),r=r.replace(/[~]{2}([^~]+)[~]{2}/g,"<del>$1</del>"),e=e+r}return e},log$U=logger$1("utils-channels"),getChannelTitle=t=>t?t.title:(log$U.warn("getChannelTitle: channel was not provided"),""),getChannelNumber=t=>((t==null?void 0:t.keyNumber)||"").toString(),getChannelNumberPadded=t=>padZero(getChannelNumber(t),3),getChannelDescription=t=>parseMd((t==null?void 0:t.description)||""),getChannelGenres=t=>t==null?void 0:t.relevantGenres,getChannelGenresMapped=t=>{var e,s,n;return((e=t==null?void 0:t.relevantGenres)==null?void 0:e.map(i=>i.genreId))||((n=(s=t==null?void 0:t.info)==null?void 0:s.metaInfo)==null?void 0:n.genres)||[]},getChannelIsLocked=t=>{var e;return(e=t==null?void 0:t.medias)==null?void 0:e.find(s=>
3s.isLocked)},getChannelLogo=t=>{var e,s,n,i;return(t==null?void 0:t.logoUrl)||((i=(n=(s=(e=t==null?void 0:t.info)==null?void 0:e.mediaInfo)==null?void 0:s.thumbnails)==null?void 0:n[0])==null?void 0:i.url)||""},getChannelLogoResized=(t,e=CHANNEL_LIST_POSTER_HEIGHT,s)=>{const n=getChannelLogo(t);return n?(s||(s=Math.round(e*16/9)),imageServerUrl(n,s,e)):""},getChannelMedia=t=>{var e;return(e=t.medias)==null?void 0:e[0]},getChannelMediaScheduleId=t=>{var e;return((e=getChannelMedia(t))==null?void 0:e.scheduleId)||""},processChannel=t=>({...t,genres:getChannelGenresMapped(t),image:getChannelLogoResized(t,140,248),name:getChannelTitle(t)}),isChannelIdValid=t=>typeof t=="string"&&!/[^a-z0-9.\-+_\s;\\:%=]+/i.test(t),isDvrDepthEqualZero=t=>{var e,s;return((s=(e=t==null?void 0:t.info)==null?void 0:e.playbackInfo)==null?void 0:s.dvrDepth)===0},isDvrAvailable=t=>{var e,s;return!t.liveOnly&&!((s=(e=t.medias)==null?void 0:e[0])!=null&&s.liveOnly)},isDvrDisabled=t=>(t==null?void 0:t.id)?!isDvrAvailable(t):!0,isDvrRestricted=t=>t?!isDvrAvailable(t)||isDvrDepthEqualZero(t):!0,hasDvr=t=>!isDvrDisabled(t)&&!isDvrRestricted(t),getDvrDepthLimit=t=>{var e,s;return convertToSeconds(Math.min(((s=(e=t==null?void 0:t.medias)==null?void 0:e[0])==null?void 0:s.dvrDepthLimitHours)||DEFAULT_DVR_DEPTH_LIMIT_HOURS,(t==null?void 0:t.dvrDepthLimitHours)||DEFAULT_DVR_DEPTH_LIMIT_HOURS),"hour")},getChannelById=(t,e)=>t[e],filterChannels=(t,e)=>Object.entries(t).reduce((s,[n,i])=>e(s,n,i),{}),filterChannelsByChannelsArray=(t,e)=>e.reduce((s,n)=>{const i=t[n.id];return i&&(s[i.id]={...i,priority:n.priority}),s},{}),sortChannels=(t,e)=>{switch(e){case TV_SORTING.ascendingNumber:case TV_SORTING_GENRE_CHANNELS_BLOCK.keyNumber:return t.sort((s,n)=>parseInt(getChannelNumber(s))-parseInt(getChannelNumber(n)));case TV_SORTING.descendingNumber:return t.sort((s,n)=>parseInt(getChannelNumber(n))-parseInt(getChannelNumber(s)));case TV_SORTING.ascendingName:return t.sort((s,n)=>getChannelTitle(s).localeCompare(getChannelTitle(n)));case TV_SORTING.descendingName:return t.sort((s,n)=>getChannelTitle(n).localeCompare(getChannelTitle(s)));case TV_SORTING_GENRE_CHANNELS_BLOCK.recommendationPriority:return t.sort((s,n)=>((s==null?void 0:s.priority)||0)-((n==null?void 0:n.priority)||0))}return t},languageCodeSelector=t=>t.languageCode,currentLanguageSelector=t=>t.languages.find(e=>e.code===languageCodeSelector(t)),defaultLanguageSelector=t=>t.languages.find(e=>e.isDefault),defaultLanguageCodeSelector=t=>{var e;return(e=t.languages.find(s=>s.isDefault))==null?void 0:e.code},isOfflineSelector=t=>t.common.isOffline,bodyScrollLockCountSelector=t=>t.common.bodyScrollLockCount,isHeaderTransparentSelector=t=>t.common.isHeaderTransparent,isHeaderAboveContentSelector=t=>t.common.isHeaderAboveContent,authAndRegPasswordMinSelector=t=>{var s,n;const e=(n=(s=t.authAndReg)==null?void 0:s.password)==null?void 0:n.min;return Number(e)||4},authAndRegPasswordMaxSelector=t=>{var s,n;const e=(n=(s=t.authAndReg)==null?void 0:s.password)==null?void 0:n.max;return Number(e)||32},activeTrialIdFromAdminSelector=t=>{var e,s;return(s=(e=t.authAndReg)==null?void 0:e.regTrials)==null?void 0:s.activeTrialId},common$1=Object.freeze(Object.defineProperty({__proto__:null,activeTrialIdFromAdminSelector,authAndRegPasswordMaxSelector,authAndRegPasswordMinSelector,bodyScrollLockCountSelector,currentLanguageSelector,defaultLanguageCodeSelector,defaultLanguageSelector,isHeaderAboveContentSelector,isHeaderTransparentSelector,isOfflineSelector,languageCodeSelector},Symbol.toStringTag,{value:"Module"})),TIME_TRANSLATIONS=[{placeholder:/%h%/g,translationId:"h"},{placeholder:/%m%/g,translationId:"m"},{placeholder:/%s%/g,translationId:"s"}],translationSelector=(t,e)=>{if(!e)return"";const s=t.translations[e],n=`{${e}}`;return s&&getByLanguage(s,languageCodeSelector(t),t.defaultLanguageCode)||n},hasTranslationIdSelector=(t,e)=>!!e&&!!t.translations[e],secondsToHMSelector=(t,e)=>{const s=secondsToHM(e);return TIME_TRANSLATIONS.reduce((n,{placeholder:i,translationId:r})=>{const o=hasTranslationIdSelector(t,r)?translationSelector(t,r):`{${r}}`;return n.replace(i,o)},s)},translations=Object.freeze(Object.defineProperty({__proto__:null,hasTranslationIdSelector,secondsToHMSelector,translationSelector},Symbol.toStringTag,{value:"Module"})),channelsLoadedSelector=t=>t.tvChannels.loaded,channelsLoadingSelector=t=>t.tvChannels.loading,channelsRecentAndFavLoadedSelector=t=>t.tvChannels.recentAndFavLoaded,channelsRecentAndFavLoadingSelector=t=>t.tvChannels.recentAndFavLoading,allChannelsSelector=t=>{var s;const e=((s=t.tvChannels)==null?void 0:s.channelsNotForPurchase)||{};return Object.keys(e).length?Object.entries(t.tvChannels.list).reduce((n,[i,r])=>(typeof e[i]>"u"?n[i]=r:getChannelIsLocked(r)||(n[i]=r),n),{}):t.tvChannels.list},filteredChannelsSelector=(t,e=t.tvChannels.currentGenre,s=!1)=>{let n={...allChannelsSelector(t)};if(e){const i=recommendedSelector(t);switch(e){case TV_SPECIAL_GENRES.favourite:n=filterChannelsByChannelsArray(n,favoritesArraySelector(t));break;case TV_SPECIAL_GENRES.recommended:n=Object.values(i).length?i:n;break;case TV_SPECIAL_GENRES.recentlyWatched:n=filterChannelsByChannelsArray(n,Object.values(recentlyWatchedSelector(t)));break;case TV_SPECIAL_GENRES.available:n=filterChannels(n,(r,o,a)=>(isChannelBoughtSelector(t,a)&&(r[o]=a),r));break;default:n=filterChannels(n,(r,o,a)=>{var d,u,h;const l=(d=a==null?void 0:a.relevantGenres)==null?void 0:d.find(f=>{var g;return((g=t.tvChannels.genres.find(p=>(p==null?void 0:p.id)===(f==null?void 0:f.genreId)))==null?void 0:g.title)===e}),c=(((h=(u=a.info)==null?void 0:u.metaInfo)==null?void 0:h.genres)||[]).findIndex(f=>f===e)!==-1;return(a!=null&&a.keyNumber&&l||c)&&(r[o]=a),r})}}if(!s&&t.tvChannels.searchQuery){const i=t.tvChannels.searchQuery.toLocaleLowerCase();n=filterChannels(n,(r,o,a)=>{const l=getChannelTitle(a).toLocaleLowerCase()||"",c=getChannelNumber(a);return(l.indexOf(i)!==-1||c.indexOf(i)!==-1)&&(r[o]=a),r})}return n},isChannelsCatalogNowOpen=(t,e)=>(typeof e.name=="string"&&(e.name.includes("channels-now")||e.name.includes("channels-list"))&&(t.tvChannels.isChannelsCatalogNowOpen=e.name.includes("channels-now")),t.tvChannels.isChannelsCatalogNowOpen),isChannelBoughtSelector=(t,e)=>!getChannelIsLocked(e)||!!channelVitrinaSelector(t,e.id),isChannelLockedSelector=(t,e)=>!isChannelBoughtSelector(t,e),recentlyWatchedSelector=t=>filterChannelsByChannelsArray(t.tvChannels.list,Object.values(t.tvChannels.recentlyWatched||{})),favoritesSelector$1=t=>filterChannelsByChannelsArray(allChannelsSelector(t),Object.values(t.tvChannels.favorites||{})),favoritesArraySelector=t=>Object.values(favoritesSelector$1(t)),recommendedSelector=t=>filterChannelsByChannelsArray(allChannelsSelector(t),Object.values(t.tvChannels.recommended||{})),recommendedArraySelector=t=>Object.values(recommendedSelector(t)),channelByIdSelector=(t,e)=>t.tvChannels.list[e],channelFirstGenreTitleSelector=(t,e)=>{var n,i,r,o;return(e!=null&&e.keyNumber?(n=t.tvChannels.genres.find(a=>{var l,c;return a.id===((c=(l=e==null?void 0:e.relevantGenres)==null?void 0:l[0])==null?void 0:c.genreId)}))==null?void 0:n.title:(o=(r=(i=e==null?void 0:e.info)==null?void 0:i.metaInfo)==null?void 0:r.genres)==null?void 0:o[0])||""},channelVitrinaSelector=(t,e)=>{var s;return((s=t.tvChannels.settings)==null?void 0:s[e])||null},genresSelector=t=>t.tvChannels.genres,currentGenreSelector=t=>t.tvChannels.currentGenre,genreTitleSelector=(t,e)=>{switch(e){case TV_SPECIAL_GENRES.all:return translationSelector(t,"all_channels");case TV_SPECIAL_GENRES.available:return translationSelector(t,"available");case TV_SPECIAL_GENRES.recommended:return translationSelector(t,"recommended");case TV_SPECIAL_GENRES.favourite:return translationSelector(t,"favourite");case TV_SPECIAL_GENRES.recentlyWatched:return translationSelector(t,"recentlyWatched");default:return e}},currentGenreNameSelector=t=>genreTitleSelector(t,currentGenreSelector(t)),genreIconSelector=(t,e)=>{var o,a,l;const s=genreTitleSelector(t,e.title),n=languageCodeSelector(t),i=(a=(o=t.siteConfig)==null?void 0:o.genreIcons)==null?void 0:a.find(c=>translationSelector(t,c.translationId)===s||c.id!==""&&c.id===e.id),r=getByLanguage((i==null?void 0:i.image)||((l=t.siteConfig)==null?void 0:l.genreIconDefault),n,t.defaultLanguageCode);return(r==null?void 0:r.url)||""},clientPlatformSelector=t=>t.tvChannels.clientPlatform,dvrLeftBoundSelector=(t,e)=>{var n,i;return!((n=t.appInfo)!=null&&n.currentTime)||!e?((i=t.appInfo)==null?void 0:i.dvrAvailable)||0:dayjs().unix()-getDvrDepthLimit(e)},tvChannels$1=Object.freeze(Object.defineProperty({__proto__:null,allChannelsSelector,channelByIdSelector,channelFirstGenreTitleSelector,channelVitrinaSelector,channelsLoadedSelector,channelsLoadingSelector,channelsRecentAndFavLoadedSelector,channelsRecentAndFavLoadingSelector,clientPlatformSelector,currentGenreNameSelector,currentGenreSelector,dvrLeftBoundSelector,favoritesArraySelector,favoritesSelector:favoritesSelector$1,filteredChannelsSelector,genreIconSelector,genreTitleSelector,genresSelector,isChannelBoughtSelector,isChannelLockedSelector,isChannelsCatalogNowOpen,recentlyWatchedSelector,recommendedArraySelector,recommendedSelector},Symbol.toStringTag,{value:"Module"})),channelCollectionsSelector=t=>{var e;return((e=t.siteConfig)==null?void 0:e.channelCollections)||[]},channelCollectionsToShowOnMainSelector=t=>{var e;return((e=channelCollectionsSelector(t))==null?void 0:e.filter(s=>s.showOnMain&&s.slug&&channelsFromCollectionSelector(t,s).length))||[]},channelsFromCollectionSelector=(t,e)=>Object.values(filteredChannelsSelector(t)).filter(i=>{const r=getChannelGenresMapped(i);return r.includes(e.genreId)||r.includes(translationSelector(t,e.genre))}).sort((i,r)=>parseInt(getChannelNumber(i))-parseInt(getChannelNumber(r)))||[],channelsImagesFromCollectionSelector=(t,e)=>{var s;return((s=channelsFromCollectionSelector(t,e))==null?void 0:s.map(n=>getChannelLogo(n)))||[]},channelCollections=Object.freeze(Object.defineProperty({__proto__:null,channelCollectionsSelector,channelCollectionsToShowOnMainSelector,channelsFromCollectionSelector,channelsImagesFromCollectionSelector},Symbol.toStringTag,{value:"Module"})),modalsParamsSelector=t=>t.modals.params,modalsScrollPositionSelector=t=>t.modals.scrollPosition,modalsTitleSelector=t=>t.modals.title,modalsVisibilitySelector=t=>t.modals.visibility,isAnyModalOpenSelector=t=>Object.values(t.modals.visibility).includes(!0),isAdultOnboardingOpenSelector=t=>t.modals.visibility.adultOnboarding,isByRouteOpenSelector=t=>t.modals.visibility.byRoute,isDvrErrorOpenSelector=t=>t.modals.visibility.dvrError,isDvrWarningOpenSelector=t=>t.modals.visibility.dvrWarning,isFeSettingsOpenSelector=t=>t.modals.visibility.feSettings,isMobileAppsOpenSelector=t=>
3t.modals.visibility.mobileApps,isOfferDetailsOpenSelector=t=>t.modals.visibility.offerDetails,isOfferExitConfirmationOpenSelector=t=>t.modals.visibility.offerExitConfirmation,isOfferGiftOpenSelector=t=>t.modals.visibility.offerGift,isPersonalDataOpenSelector=t=>t.modals.visibility.personalData,isPhoneVerificationOpenSelector=t=>t.modals.visibility.phoneVerification,isPlayerHelpOpenSelector=t=>t.modals.visibility.playerHelp,isProfileActionOpenSelector=t=>t.modals.visibility.profileAction,isProfileProtectedOpenSelector=t=>t.modals.visibility.profileProtected,isPromoOfferSkippedOpenSelector=t=>t.modals.visibility.skipPromoOffers,isQsOpenSelector=t=>t.modals.visibility.qs,isSubscriptionConfirmationOpenSelector=t=>t.modals.visibility.subscriptionConfirmation,isSubscriptionShopOpenSelector=t=>t.modals.visibility.subscriptionShop,isSubscriptionV2OpenSelector=t=>t.modals.visibility.subscriptionV2,isTrialGiftOpenSelector=t=>t.modals.visibility.trialGift,isUnsubscriptionRetentionOfferDetailsOpenSelector=t=>t.modals.visibility.unsubscriptionRetentionOfferDetails,isVerificationSubscriptionOpenSelector=t=>t.modals.visibility.verificationSubscription,isWelcomeScreenOpenSelector=t=>t.modals.visibility.welcomeScreen,modals$1=Object.freeze(Object.defineProperty({__proto__:null,isAdultOnboardingOpenSelector,isAnyModalOpenSelector,isByRouteOpenSelector,isDvrErrorOpenSelector,isDvrWarningOpenSelector,isFeSettingsOpenSelector,isMobileAppsOpenSelector,isOfferDetailsOpenSelector,isOfferExitConfirmationOpenSelector,isOfferGiftOpenSelector,isPersonalDataOpenSelector,isPhoneVerificationOpenSelector,isPlayerHelpOpenSelector,isProfileActionOpenSelector,isProfileProtectedOpenSelector,isPromoOfferSkippedOpenSelector,isQsOpenSelector,isSubscriptionConfirmationOpenSelector,isSubscriptionShopOpenSelector,isSubscriptionV2OpenSelector,isTrialGiftOpenSelector,isUnsubscriptionRetentionOfferDetailsOpenSelector,isVerificationSubscriptionOpenSelector,isWelcomeScreenOpenSelector,modalsParamsSelector,modalsScrollPositionSelector,modalsTitleSelector,modalsVisibilitySelector},Symbol.toStringTag,{value:"Module"})),notificationsSelector=t=>t.notifications,queueSelector=t=>notificationsSelector(t).queue,isFirstInQueue=(t,e)=>queueSelector(t).indexOf(e)===0,isAnyComplexNotificationVisibleSelector=t=>!!Object.values(t.notifications.complex).find(({isVisible:e})=>e),adultOnboardingSelector=t=>t.notifications.complex.adultOnboarding,isAdultOnboardingFromQueueVisible=t=>isFirstInQueue(t,"adultOnboarding"),isAuthAndRegVisibleSelector=t=>t.notifications.complex.authAndReg.isVisible,isAuthAndRegFromQueueVisible=t=>isFirstInQueue(t,"authAndReg"),notificationAutoLoginMegafonSelector=t=>t.notifications.complex.autologinMegafon.isVisible,isAutologinMegafonFromQueueVisible=t=>isFirstInQueue(t,"autologinMegafon"),isDvrRestrictionVisibleSelector=t=>t.notifications.complex.dvrRestriction.isVisible,isDvrRestrictionFromQueueVisible=t=>isFirstInQueue(t,"dvrRestriction"),isDvrRestrictionWithButtonVisibleSelector=t=>t.notifications.complex.dvrRestrictionWithButton.isVisible,isDvrRestrictionWithButtonFromQueueVisible=t=>isFirstInQueue(t,"dvrRestrictionWithButton"),isPlayerErrorVisibleSelector=t=>t.notifications.complex.playerError.isVisible,isPlayerErrorFromQueueVisible=t=>isFirstInQueue(t,"playerError"),isProviderInfoVisibleSelector=t=>t.notifications.complex.providerContactInfo.isVisible,isProviderContactInfoFromQueueVisible=t=>isFirstInQueue(t,"providerContactInfo"),isRetryVisibleSelector=t=>t.notifications.complex.retry.isVisible,isRetryFromQueueVisible=t=>isFirstInQueue(t,"retry"),isReviewVisibleSelector=t=>t.notifications.complex.review.isVisible,isReviewFromQueueVisible=t=>isFirstInQueue(t,"review"),isSubscriptionPaymentErrorVisibleSelector=t=>t.notifications.complex.subscriptionPaymentError.isVisible,isSubscriptionPaymentErrorFromQueueVisible=t=>isFirstInQueue(t,"subscriptionPaymentError"),subscriptionProlongationErrorSelector=t=>t.notifications.complex.subscriptionProlongationError,isSubscriptionProlongationErrorFromQueueVisible=t=>isFirstInQueue(t,"subscriptionProlongationError"),unavailableContentSelector=t=>
3t.notifications.complex.unavailableContent,unavailableContentImageSelector=t=>unavailableContentSelector(t).image,isUnavailableContentVisible=t=>unavailableContentSelector(t).isVisible,unavailableContentSourceIdSelector=t=>unavailableContentSelector(t).sourceId,unavailableContentTitleIdSelector=t=>unavailableContentSelector(t).titleId,unavailableContentTitleTextSelector=t=>unavailableContentSelector(t).titleText,isUnavailableContentFromQueueVisible=t=>isFirstInQueue(t,"unavailableContent"),notificationsSimpleSelector=t=>t.notifications.simple,notificationsAutoRenew=t=>t.notifications.simple.filter(e=>e.type==="autoRenew"),notificationsDiagnosticsStatusSelector=t=>t.notifications.simple.filter(e=>e.type==="diagnosticsStatus"),notificationsErrorSelector=t=>t.notifications.simple.filter(e=>e.type==="error"),notificationsFavoriteSelector=t=>t.notifications.simple.filter(e=>e.type==="favorite"),notificationsLoginSuccessSelector=t=>t.notifications.simple.filter(e=>e.type==="loginSuccess"),notificationsPauseRemovedSelector=t=>t.notifications.simple.filter(e=>e.type==="pauseRemoved"),notificationsProfileSelector=t=>t.notifications.simple.filter(e=>e.type==="profile"),notificationsQsSelector=t=>t.notifications.simple.filter(e=>e.type==="qs"),notifications$1=Object.freeze(Object.defineProperty({__proto__:null,adultOnboardingSelector,isAdultOnboardingFromQueueVisible,isAnyComplexNotificationVisibleSelector,isAuthAndRegFromQueueVisible,isAuthAndRegVisibleSelector,isAutologinMegafonFromQueueVisible,isDvrRestrictionFromQueueVisible,isDvrRestrictionVisibleSelector,isDvrRestrictionWithButtonFromQueueVisible,isDvrRestrictionWithButtonVisibleSelector,isFirstInQueue,isPlayerErrorFromQueueVisible,isPlayerErrorVisibleSelector,isProviderContactInfoFromQueueVisible,isProviderInfoVisibleSelector,isRetryFromQueueVisible,isRetryVisibleSelector,isReviewFromQueueVisible,isReviewVisibleSelector,isSubscriptionPaymentErrorFromQueueVisible,isSubscriptionPaymentErrorVisibleSelector,isSubscriptionProlongationErrorFromQueueVisible,isUnavailableContentFromQueueVisible,isUnavailableContentVisible,notificationAutoLoginMegafonSelector,notificationsAutoRenew,notificationsDiagnosticsStatusSelector,notificationsErrorSelector,notificationsFavoriteSelector,notificationsLoginSuccessSelector,notificationsPauseRemovedSelector,notificationsProfileSelector,notificationsQsSelector,notificationsSelector,notificationsSimpleSelector,queueSelector,subscriptionProlongationErrorSelector,unavailableContentImageSelector,unavailableContentSelector,unavailableContentSourceIdSelector,unavailableContentTitleIdSelector,unavailableContentTitleTextSelector},Symbol.toStringTag,{value:"Module"})),itemsSelector=(t,e)=>t.promoElements.items[e]||[],isBannersDataLoadedSelector=t=>t.promoElements.isBannersDataLoaded,isBannersDataLoadingSelector=t=>t.promoElements.isBannersDataLoading,mediaIdSelector=(t,e,s)=>Object.values(t.promoElements.items).reduce((n,i)=>{var r,o,a,l,c,d,u;return n||((u=(d=(c=(l=(a=(o=(r=i.find(h=>{var S,y;const f=(S=h.internalReference)==null?void 0:S.vodContent,g=f==null?void 0:f.source,p=f==null?void 0:f.contentId,m=h.renderingMethods.find(C=>Object.values(BANNER_VIDEO_RENDERING_METHODS_NAMES).includes(C.method)),v=(y=h==null?void 0:h.mediaItems)==null?void 0:y.length;return g===e&&p===s&&m&&v}))==null?void 0:r.mediaItems)==null?void 0:o[0])==null?void 0:a.playbackMethods)==null?void 0:l[0])==null?void 0:c.params)==null?void 0:d.find(h=>h.key==="mediaId"))==null?void 0:u.value)||""},""),promoElements=Object.freeze(Object.defineProperty({__proto__:null,isBannersDataLoadedSelector,isBannersDataLoadingSelector,itemsSelector,mediaIdSelector},Symbol.toStringTag,{value:"Module"})),getRenderingMethods=t=>Object.values(t.reduce((e,s)=>{var i;const n=((i=s.renderingMethods.sort((r,o)=>r.priority-o.priority)[0])==null?void 0:i.method)||"";return n&&(e[n]=n),e},{})),componentsListSelector=t=>{var s,n;return((n=(s=t.homeScreenConfig)==null?void 0:s.config_list)!=null&&n.length?t.homeScreenConfig.config_list:DEFAULT_HOME_SCREEN_CONFIG.map((i,r)=>({key:i,sort:r,active:!0}))).reduce((i,r)=>{let o;if(["home-suggested-channels","home-recent-channels"].includes(r.key)&&(o={showCurrentTVProgram:!0}),HOME_SCREEN_SEQUOIA_COMPONENTS.includes(r.key)||r.key===PROMO_ELEMENTS_PLACEMENT_BLOCKS.homeCarouselV2){const a=r.key;i.push({...r,renderingMethods:[a],placementId:"",blockSettings:o})}else{const a=r.key,l=itemsSelector(t,a);getRenderingMethods(l).forEach(d=>{i.push({...r,renderingMethods:[d],blockSettings:{showCurrentTVProgram:!0},placementId:a})})}return i},[])},home$1=Object.freeze(Object.defineProperty({__proto__:null,componentsListSelector},Symbol.toStringTag,{value:"Module"})),prepareFileRecord$1=(t,e)=>typeof t!="string"||!t?{}:e[t]||{},fileRecordSelector=(t,e)=>prepareFileRecord$1(e,t.fileRecords.items),fileRecords=Object.freeze(Object.defineProperty({__proto__:null,fileRecordSelector},Symbol.toStringTag,{value:"Module"})),gaParamsSelector=t=>t.gaParams,metrics$1=Object.freeze(Object.defineProperty({__proto__:null,gaParamsSelector},Symbol.toStringTag,{value:"Module"})),packagesSelector=t=>t.packages.items.sort((e,s)=>e.sorting-s.sorting),packages$1=Object.freeze(Object.defineProperty({__proto__:null,packagesSelector},Symbol.toStringTag,{value:"Module"})),BROWSERS={safari:"Safari",chrome:"Chrome",firefox:"Firefox",ie:"Internet Explorer",edge:"Microsoft Edge",yandex:"Yandex Browser"},OS_LIST={ios:"ios",macos:"macos"},PLATFORMS={mobile:"mobile",tablet:"tablet"},huaweiDevicesRegex=/HUAWEI|HMS|ALP-|AMN-|ANA-|ANE-|ANG-|AQM-|ARS-|ART-|ATU-|BAC-|BLA-|BRQ-|CAG-|CAM-|CAN-|CAZ-|CDL-|CDY-|CLT-|CRO-|CUN-|DIG-|DRA-|DUA-|DUB-|DVC-|ELE-|ELS-|EML-|EVA-|EVR-|FIG-|FLA-|FRL-|GLK-|HMA-|HW-|HWI-|INE-|JAT-|JEF-|JER-|JKM-|JNY-|JSC-|LDN-|LIO-|LON-|LUA-|LYA-|LYO-|MAR-|MED-|MHA-|MLA-|MRD-|MYA-|NCE-|NEO-|NOH-|NOP-|OCE-|PAR-|PIC-|POT-|PPA-|PRA-|RNE-|SEA-|SLA-|SNE-|SPN-|STK-|TAH-|TAS-|TET-|TRT-|VCE-|VIE-|VKY-|VNS-|VOG-|VTR-|WAS-|WLZ-|WKG-|MLD-|RTE-|NAM-|NEN-|BAL-|JAD-|JLN-|YAL|MRA/i,getBowserInstance=t=>Bowser.getParser(t),getPlatformType=t=>getBowserInstance(t).getPlatformType(!0),getBrowserVersion=t=>getBowserInstance(t).getBrowserVersion(),getOsName=t=>getBowserInstance(t).getOSName(!0),getBrowserName=t=>getBowserInstance(t).getBrowserName(),getAndroidDeviceType=t=>{const e={artel:/Artel/i.test(t),huawei:huaweiDevicesRegex.test(t),oppo:/OPPO/i.test(t),vivo:/vivo/i.test(t)};return Object.keys(e).find(n=>e[n])||""},getPlatformName=t=>{const e={ipad:/iPad/i.test(t),ipod:/iPod/i.test(t),iphone:/iPhone/i.test(t),android:/Android/i.test(t),winphone:/Windows Phone/i.test(t),dune:/arora/i.test(t)||/dune/i.test(t),eltex:/eltex/i.test(t),mag:/mag/i.test(t),netcast:/netcast/i.test(t)||/LG SimpleSmart/i.test(t),samsung:/smart-tv/i.test(t),tizen:/Tizen/i.test(t),webos:/Web0S/i.test(t),pc:/Opera/i.test(t)||/Mozilla/i.test(t)};return Object.keys(e).find(n=>e[n])||""},getDeviceFlags=t=>{const e=getPlatformName(t),s=getAndroidDeviceType(t),n=getPlatformType(t),i=typeof window>"u";return{isAndroid:e==="android",isAndroidWithoutGooglePlay:["artel","huawei","oppo","vivo","winphone"].indexOf(s)!==-1,isIphone:e==="iphone",isArtel:s==="artel",isHuawei:s==="huawei",isOppo:s==="oppo",isVivo:s==="vivo",isWinphone:e==="winphone",isMobile:n===PLATFORMS.mobile,isTablet:n===PLATFORMS.tablet,isiPadPro:i?!1:navigator.userAgent.match(/Mac/)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,isSmartTv:["netcast","webos","samsung","tizen"].indexOf(e)!==-1,isStb:["dune","eltex","mag"].indexOf(e)!==-1,isPc:e==="pc"||!e}},getOsFlags=t=>{const e=getOsName(t);return{isIos:e===OS_LIST.ios,isMacos:e===OS_LIST.macos}},getBrowserFlags=t=>{const e=getBrowserName(t);return{isMicrosoft:[BROWSERS.ie,BROWSERS.edge].includes(e),isSafari:e===BROWSERS.safari,isEdge:e===BROWSERS.edge,isYandex:e
3===BROWSERS.yandex}},getDeviceType=t=>{const e=getDeviceFlags(t);return e.isMobile?"phone":e.isTablet?"tablet":e.isiPadPro?"iPadPro":e.isSmartTv||e.isStb?"smarttv":"pc"},isAndroidWebview=t=>t.includes("wv")&&getDeviceFlags(t).isAndroid,getUserAgent=t=>window.navigator.userAgent,getCookieFromCtx=(t,e)=>e?getSafeUserString(e.cookies[t]):"",getFeCookie=t=>{const e={session:""};try{const s=cookieStore.get(COOKIE_NAMES.feCookie);return s||e}catch{return e}},setFeCookie=({session:t},e)=>{const s={session:t};cookieStore.set(COOKIE_NAMES.feCookie,JSON.stringify(s))},clearFeCookie=()=>cookieStore.remove(COOKIE_NAMES.feCookie),getPromoCodeCookie=t=>cookieStore.get(COOKIE_NAMES.promoCode),getProfileConfirmedCookie=t=>cookieStore.get(COOKIE_NAMES.profileConfirmed),getProfileConfirmationPeriodCookie=t=>cookieStore.get(COOKIE_NAMES.profileConfirmationPeriod),getWelcomeScreenConfirmedCookie=t=>cookieStore.get(COOKIE_NAMES.welcomeScreenConfirmed),isOkObject=t=>typeof t=="object"&&!!t,isEmptyObject=t=>!isOkObject(t)||Object.keys(t).length===0,sortByPriority=t=>sortBy(t,"priority"),flattenObjectRecursive=(t,e,s="")=>{let n={};for(const i in t)Object.getOwnPropertyDescriptor(t,i)&&(typeof t[i]!="object"?n[`${s}${i}`]=t[i]:n={...n,...flattenObjectRecursive(t[i],e,`${i}${e}`)});return n},flattenObject=(t,e=".")=>flattenObjectRecursive(t,e),deleteFromObject=(t,e)=>{for(const s in e)~s.indexOf(t)&&delete e[s]},getDrmSystem=t=>getOsFlags(t).isIos&&!getBrowserFlags(t).isSafari?"":getBrowserFlags(t).isSafari?DRM_SYSTEMS.fairplay:DRM_SYSTEMS.widevine,getDeviceDrmQueryParamValue=t=>{switch(getDrmSystem(t)){case DRM_SYSTEMS.fairplay:return"fp";case DRM_SYSTEMS.playready:return"prdsh";case DRM_SYSTEMS.widevine:return"wvm"}return""},getAmediaDrmStreamUrl=(t,e)=>{var s,n,i,r,o,a;switch(e){case DRM_SYSTEMS.fairplay:return((n=(s=t.streams)==null?void 0:s.hls)==null?void 0:n.fairplay)||"";case DRM_SYSTEMS.playready:return((r=(i=t.streams)==null?void 0:i.dash)==null?void 0:r.playready)||"";case DRM_SYSTEMS.widevine:return((a=(o=t.streams)==null?void 0:o.dash)==null?void 0:a.widevine)||""}return""},getAppVersionParams=t=>{const e=getUserAgent(),s={app:{version:"3.9.15",hash:"e83e2943",buildDate:"1778762378000",id:"sequoia",buildType:"portal",whitelabel:getEnvVars().wlAppId,hostname:"",env:""},device:{type:getDeviceType(e)==="iPadPro"?"tablet":getDeviceType(e),brand:getPlatformName(e)||"none",model:"none",uuid:getDeviceUuid()}};t!=null&&t.script&&(s.app.script=t==null?void 0:t.script);const n=getDeviceDrmQueryParamValue(e);return n&&(s.device.drm=n),s},getAppVersionParamsFlattened=t=>flattenObject(getAppVersionParams(t));class ApiError extends AxiosError{get reqUrl(){if(!this.config)return"";let e=`${this.config.baseURL}${this.config.url}`;return isEmptyObject(this.config.params)||(e+=`?${new URLSearchParams(this.config.params).toString()}`),e}get reqInfo(){var s;if(!this.config)return"";let e=`${(s=this.config.method)==null?void 0:s.toUpperCase()} ${this.reqUrl}`;return this.resMessage&&(e+=` - ${this.resMessage}`),e}get resStatus(){var e;return(e=this.response)==null?void 0:e.status}get resMessage(){var n,i,r,o;const e=(this==null?void 0:this.code)==="ECONNABORTED";let s="";return e?(s="Request timeout",(n=this.config)!=null&&n.timeout&&(s+=` after ${(i=this.config)==null?void 0:i.timeout}ms`)):(r=this==null?void 0:this.response)!=null&&r.status&&(s=`${(o=this.response)==null?void 0:o.status} -> ${this.message}`),s}}const errorHandler=t=>{var e,s,n,i,r;if(((e=t.response)==null?void 0:e.status)!==HTTP_CODES.NOT_MODIFIED){let o=((n=(s=t.response)==null?void 0:s.data)==null?void 0:n.message)||((r=(i=t.response)==null?void 0:i.data)==null?void 0:r.msg)||t.message;const a=t.config;let l,c;if(a){l={timeout:a.timeout,headers:a.headers,withCredentials:a.withCredentials,url:a.url,method:a.method,params:a.params,data:a.data,baseURL:a.baseURL};let d="";a.method&&(d+=`${a.method.toUpperCase()} `),d+=`${a.baseURL}${a.url}`}throw t.response&&(c={status:t.response.status,data:t.response.data,statusText:t.response.statusText,headers:t.response.headers}),new ApiError(o,t.code,l,void 0,c)}};var define_process_env_default={};const log$T=logger$1("api"),createRequest=(t,e={})=>({get:requestFactory(t,"get",e),head:requestFactory(t,"head",e),delete:requestFactory(t,"delete",e),post:requestFactory(t,"post",e),put:requestFactory(t,"put",e),patch:requestFactory(t,"patch",e),sendBeacon:sendBeacon(e)}),prepareConfig=(t,e,s,n)=>{s.formUrlEncoded&&!n.jsonData&&(n.data=new URLSearchParams(n.data).toString()),n.headers=n.headers||{},n.headers["Accept-Language"]=n.languageCode,n.jsonData&&(n.headers["content-type"]="application/json");const i={url:t,method:e,params:{},data:{},...s,...n};if(s.isFe?i.baseURL=getEnvVars().feBaseUrl:s.isBe&&(i.baseURL=getEnvVars().beBaseUrl),!i.bowProxyDisabled&&i.params.token)i.url=URLS.bow.proxy+t;else if(i.withSession){const r=getFeCookie(n.ctx);i.params.session=(r==null?void 0:r.session)||void 0}return i.withAppVersion&&(i.params={...i.params,...getAppVersionParamsFlattened(n.ctx)}),i},requestFactory=(t,e,s)=>async(n,i)=>{const r=prepareConfig(n,e,s,i),o=r.onResponse?r.onResponse:()=>{},a=r.onError?r.onError:()=>{},{session:l,...c}=r.params;try{const d=await t(r),u=getReqInfo(d,r);return isEmptyObject(c)?log$T.debug(u):log$T.debug(u,c),log$T.trace(getStackTrace().split(`
4`)[3]),o(d,r),d.data}catch(d){return d instanceof AxiosError&&(a(d,r),errorHandler(d)),null}},sendBeacon=t=>(e,s)=>{const n=prepareConfig(e,"post",t,s),i=new URLSearchParams(Object.entries(n.params)),r=new 
4URL(`${e}?${i}`,n.baseURL),o={type:"application/x-www-form-urlencoded"},a=new Blob([n.data],o);navigator.sendBeacon(r,a)},createNetworkAdapter=t=>axios.create(t),defaultTimeout=1e4,feServerTimeout=7e3,feClientTimeout=2e4,origin=typeof window>"u"?`http://127.0.0.1:${define_process_env_default.PORT}`:window.location.origin;createNetworkAdapter({baseURL:origin,timeout:defaultTimeout,withCredentials:!0});const feInstance=createNetworkAdapter({timeout:typeof window>"u"?feServerTimeout:feClientTimeout,withCredentials:!0}),fe=createRequest(feInstance,{isFe:!0,formUrlEncoded:!0,withSession:!0,withAppVersion:!0}),beInstance=createNetworkAdapter({timeout:defaultTimeout,withCredentials:!0}),be=createRequest(beInstance,{isBe:!0}),iviLightInstance=createNetworkAdapter({baseURL:URLS.vod.ivi.lightServer,timeout:defaultTimeout,withCredentials:!1}),iviLight=createRequest(iviLightInstance),feOldInstance=createNetworkAdapter({baseURL:URLS.oldSmotreshkaPremiumPage,timeout:defaultTimeout,withCredentials:!1}),oldFe=createRequest(feOldInstance,{formUrlEncoded:!0}),getReqInfo=(t,e)=>{var s;return`${(((s=t==null?void 0:t.config)==null?void 0:s.method)||e.method||"").toUpperCase()} ${axios.getUri(e)} - ${(t==null?void 0:t.status)||0}`},getAppInfo=t=>fe.get(URLS.appInfo,t),getSpeedTests=async t=>await fe.get(URLS.speedTests,t)||{speedTests:[]},getAppSections=async(t="",e)=>fe.get(URLS.appSections(t),e),login$1=async t=>fe.post(URLS.login,t),qrLogin$1=async t=>fe.post(URLS.qrLogin,t),logout$1=async t=>fe.get(URLS.logout,t),getAccount$1=async t=>fe.get(URLS.account,t),registerByPhone=async t=>fe.post(URLS.registration.byPhone,t),restorePassword=async t=>{var e;return(e=t==null?void 0:t.params)!=null&&e.captchaid?fe.post(URLS.restorePassword,t):(t.withAppVersion=!0,be.post(URLS.restorePassword,t))},restorePasswordByLink=async({id:t,accountId:e},s)=>fe.put(URLS.restorePasswordByLink(t,e),s),contactsVerification={async getMethods(t){const e=await fe.get(URLS.contactsVerification.methods,t);return(e==null?void 0:e.methods)||[]},startWithAccountSession:t=>fe.post(URLS.contactsVerification.startWithAccountSession,t),start:t=>{var e;return(e=t==null?void 0:t.params)!=null&&e.captchaid?fe.post(URLS.contactsVerification.start,t):(t.withAppVersion=!0,be.post(URLS.contactsVerification.start,t))},startRecaptcha:t=>fe.post(URLS.contactsVerification.startRecaptcha,t),verify:t=>fe.post(URLS.contactsVerification.verify,t),verifyV2:t=>fe.post(URLS.contactsVerification.verifyV2,t),retry:t=>fe.post(URLS.contactsVerification.retry,t),setPhone:t=>fe.post(URLS.contactsVerification.setPhone,t),unlinkPhone:t=>fe.post(URLS.contactsVerification.unlinkPhone,t)},availableLogins=t=>fe.get(URLS.availableLogins,t),loginWithVerifiedContacts$1=t=>fe.post(URLS.loginWithVerifiedContacts,t),sendPassword$1=t=>fe.post(URLS.sendPassword,t),registerWithToken$1=t=>fe.post(URLS.register,t),registerMobileWithToken$1=t=>fe.post(URLS.registerMobile,t),getPhoneInfoV1=t=>fe.post(URLS.phoneInfoV1,t),getPhoneInfoV2=t=>fe.get(URLS.phoneInfoV2,t),promoCodeCheck=t=>fe.get(URLS.promoCodeCheck,t),registerWithPromoCode=t=>fe.post(URLS.registerWithPromoCode,t),uztelAuth$1=t=>fe.post(URLS.uztel.auth,t),registerWithPromoCodeMobile=async t=>{const e=await fe.post(URLS.registerWithPromoCodeMobile,t);return(e==null?void 0:e.message)||""},registerSimPassword=t=>fe.post(URLS.registerSimPassword,t),contactsVerificationSimPassword=t=>fe.post(URLS.contactsVerificationSimPassword,t),megafonAuthBy18pToken=t=>fe.post(URLS.megafon.auth_18p,t),megafonAuthByToken=t=>fe.post(URLS.megafon.auth,t),evictedSession$1=t=>fe.get(URLS.evictedSession,t),getTokenData=async t=>fe.get(URLS.bow.tokenData,t),qsStateForTransaction=async(t,e)=>fe.get(URLS.bow.qsStateForTransaction(t),e),log$S=logger$1("actions-tv-channels"),addToFavorites$1=async(t,e)=>fe.post(`${URLS.favorites}/${t}`,e),removeFromFavorites$1=async(t,e)=>fe.delete(`${URLS.favorites}/${t}`,e),getPlaybackInfoEnhanced=(t,e=0,s=0)=>({...t,dvrAvailability:null,dvrRestriction:!1,playUrl:"",languageIndex:e,renditionIndex:s}),getPlaybackInfo=async t=>{t.enable50fps=t.enable50fps===!0;const e=await fe.get(`${URLS.playbackInfo(t.channelId)}?enable50fps=${t.enable50fps}`,t);return e?getPlaybackInfoEnhanced(e,t.languageIndex,t.renditionIndex):null},getPlaybackInfoMedia=async t=>{t.enable50fps=t.enable50fps===!0;const e=await fe.get(`${URLS.playbackInfoMedia(t.mediaId)}?enable50fps=${t.enable50fps}`,t);return e?getPlaybackInfoEnhanced(e,t.languageIndex,t.renditionIndex):null},getDvrAvailability=async(t,e)=>fe.get(URLS.dvrAvailability(t),e),prepareChannels=t=>t.map(e=>{var o,a;const s=!!(e!=null&&e.keyNumber),n=((a=(o=e==null?void 0:e.info)==null?void 0:o.metaInfo)==null?void 0:a.title)||(e==null?void 0:e.title)||"",i=3,r=s?{...e}:{...e,title:n,name:s?n:n.slice(i+1),strNumber:(e==null?void 0:e.keyNumber)||n.slice(0,i)};if(e.info){const{socialInfo:l,updateInfo:c,...d}=e.info;r.info=d}return r}).sort((e,s)=>
4parseInt(getChannelNumber(e))-parseInt(getChannelNumber(s))).reduce((e,s)=>(e[s.id]=s,e),{}),getChannels=async t=>{var i;const{tvAssetToken:e,...s}=t||{};if(!e)return;log$S.debug("Loading TV API 2.0...");let n;try{n=await fe.get(URLS.channelsV2(e),s)}catch(r){n=null,log$S.error(r),log$S.warn("TV API 2.0: Could not load channels")}if(n){const{genres:r,channels:o}=n,a=((i=await fe.get(URLS.medias(e),s).catch(c=>(log$S.error(c),{medias:[]})))==null?void 0:i.medias)||[],l={};return a.forEach(c=>{const d=o.find(u=>u.id===c.channelId);d&&(l[d.id]=l[d.id]||d,l[d.id].medias=l[d.id].medias||[],l[d.id].medias.push(c))}),log$S.info("TV API 2.0 was loaded!"),{channels:prepareChannels(Object.values(l)),genres:r}}},getRecentAndFavChannels=async t=>{let e=[],s=[];try{const n=await fe.get(URLS.recentAndFavChannels,t);e=(n==null?void 0:n.favouriteChannels)||[],s=(n==null?void 0:n.recentlyWatchedChannels)||[]}catch(n){log$S.error("getRecentAndFavChannels",n)}return{favouriteChannels:e.reverse().reduce((n,i)=>(n[i.id]=i,n),{})||{},recentlyWatchedChannels:s.reduce((n,i)=>(n[i.id]=i,n),{})||{}}},getRecommendedChannels=async t=>{try{const e=await fe.get(URLS.recommendedChannels,t);return e!=null&&e.channelRecommendations?sortBy(e.channelRecommendations.map(n=>
4({id:n.channelId,priority:n.priority})),"priority").reduce((n,i)=>(n[i.id]=i,n),{}):{}}catch(e){return log$S.error("Recommended channels were not loaded",e),{}}},getChannelsNotForPurchase$1=async t=>{const e=Date.now();let s;try{t.params=t.params||{},t.params.timeout=5e3,s=await fe.get(`${URLS.channelsNotForPurchase}`,t)}catch(i){log$S.error(i),s={channelsNotForPurchase:[]}}const n=(s==null?void 0:s.channelsNotForPurchase)||[];return log$S.info(`tvData [channelsNotForPurchase]: ${Date.now()-e}ms`),n.reduce((i,r)=>(i[r]=r,i),{})},getTvData=async(t,e,s)=>{let n={},i=[],r={};try{const o=await getChannels({tvAssetToken:s,languageCode:t,ctx:e});n=(o==null?void 0:o.channels)||{},i=(o==null?void 0:o.genres)||[]}catch(o){log$S.error(o)}try{r=await getRecommendedChannels({languageCode:t,ctx:e})}catch(o){log$S.error(o)}return{genresResponse:i,channelsResponse:n,recommendedChannelsResponse:r}},getExternalPlayerSettings=async t=>fe.get(URLS.externalPlayer.tvSettings,t),log$R=logger$1("api-cms"),getAllComponents=async()=>{const t={languageCode:"ru",ctx:void 0},e=await be.get("/component",t);return(e==null?void 0:e.components)||null},getAllContentBlocks=async()=>{const t={languageCode:"ru",ctx:void 0},e=await be.get("/cleanContentBlock",t);return(e==null?void 0:e.contentBlocks)||null},getFilePath=(t,e)=>`${getEnvVars().beBaseUrl}${t}/${e}`,prepareFileRecord=(t,e)=>Object.entries(t).reduce((s,[n,i])=>(s[n]={...i,url:getFilePath(e,i.name)},s),{}),prepareFileRecords=(t,e)=>Object.entries(t).reduce((s,[n,i])=>(s[n]=prepareFileRecord(i,e),s),{}),getAllFiles=async()=>{var e;const t={languageCode:"ru",ctx:void 0};try{const s=await be.get("/file-records",t);return s!=null&&s.fileRecords&&(s!=null&&s.filesPath)?prepareFileRecords(s.fileRecords,s.filesPath):(log$R.error("invalid response from /file-records",s),{})}catch(s){if(((e=s.response)==null?void 0:e.status)===HTTP_CODES.NOT_FOUND)try{const n=await be.get("/cleanFileRecord",t);return n?prepareFileRecords(n.files,"/upload"):{}}catch(n){return log$R.error(`/cleanFileRecord was not loaded: ${n}`),{}}else log$R.error(`/file-records were not loaded: ${s}`);return{}}},getAllPages=async()=>{try{const t={languageCode:"ru",ctx:void 0},e=await be.get("/page",t);return{pages:(e==null?void 0:e.pages)||[],pageFolders:(e==null?void 0:e.pageFolders)||[]}}catch{return{pages:[],pageFolders:[]}}},getAllTranslations=async()=>{var e,s;const t={languageCode:"ru",ctx:void 0};try{const n=await be.get("/translations",t);return n!=null&&n.translations?(n==null?void 0:n.translations)||{}:(log$R.error("invalid response from /translations",n),{})}catch(n){if(((e=n.response)==null?void 0:e.status)===HTTP_CODES.NOT_FOUND||((s=n.response)==null?void 0:s.status)===HTTP_CODES.NOT_ALLOWED)try{const i=await be.get("/cleanTranslation",t);return(i==null?void 0:i.translations)||{}}catch(i){return log$R.error(`legacy-translations were not loaded: ${i}`),{}}else log$R.error(`translations were not loaded: ${n}`);return{}}},getSiteConfig=async()=>{const t={languageCode:"ru",ctx:void 0},e=await be.get("/siteConfig",t);return(e==null?void 0:e.siteConfig)||null},getLanguages=async()=>{var e;let t=[];try{const s=await be.get("/languages",{languageCode:"ru",ctx:void 0});t=(s==null?void 0:s.languages)||[]}catch(s){if(((e=s.response)==null?void 0:e.status)===HTTP_CODES.NOT_FOUND)try{const n=await be.get("/language",{languageCode:"ru",ctx:void 0}),i=(n==null?void 0:n.defaultLanguage)||"ru";t=n!=null&&n.languages?n.languages.filter(r=>r.isOnSite).map(r=>({code:r.locale,name:r.shortName,navigatorLanguages:r.forWhichLocales,isDefault:r.locale===i})):[]}catch(n){log$R.error(`/language was not loaded: ${n}`)}else log$R.error(`/languages were not loaded: ${s}`)}return t},getPremiumPageProvider=async(t="")=>await be.get(URLS.premiumPageProviderBySlug(t),{languageCode:"",ctx:void 0})||{provider:null},getPackages=async()=>{var e;const t={languageCode:"ru",ctx:void 0};return((e=await be.get("/packages",t))==null?void 0:e.packages)||null},getSeoRules=async()=>{var s;const t={languageCode:"ru",ctx:void 0},e=((s=await be.get(URLS.seoRules,t))==null?void 0:s.rules)||void 0;return e==null?void 0:e.reduce((n,i)=>(n[i.url]=i,n),{})}
4,getMarketingExternalCode=async t=>{var s,n;const e={languageCode:"ru",ctx:void 0,params:{"utm-source":t}};try{return((n=(s=await be.get(URLS.marketingExternalCodes,e))==null?void 0:s.items)==null?void 0:n[0])||null}catch(i){return log$R.error(i),null}},getOnAir=t=>fe.get(URLS.epg.onAir,t),getScheduleIndex=async(t,e)=>{try{const s=await fe.get(URLS.epg.schedules.index(t),e);return{pages:(s==null?void 0:s.pages)||[],regularUpdate:(s==null?void 0:s.regularUpdate)||void 0}}catch{return{pages:[],regularUpdate:void 0}}},getScheduleSpread=(t,e)=>fe.get(URLS.epg.schedules.spread(t),e),BS=8,strxor=(t,e)=>{if(t.length!==e.length)throw new Error(`strxor: string lengths are not equal. a: ${t}. b: ${e}`);return t.split("").map((s,n)=>String.fromCharCode(t.charCodeAt(n)^e.charCodeAt(n))).join("")},decodeHex=t=>{if(t.length%2!==0)throw new Error("hex string length is not odd");let e="";for(let s=0;s<t.length-1;s+=2){const n=parseInt(t[s]+t[s+1],16);e+=String.fromCharCode(n)}return e},repeatString=(t,e)=>{let s="";for(let n=0;n<e;n++)s+=t;return s};class IVICMACBF{constructor(e){$(this,"cipher");$(this,"k1");$(this,"k2");this.cipher=new Blowfish(decodeHex(e[0])),this.k1=decodeHex(e[1]),this.k2=decodeHex(e[2])}calculateSign(e){let s=repeatString("\0",BS);const n=e.length,i=n%BS===0?n-BS:n-n%BS;for(let a=0;a<i;a+=BS)s=decodeHex(this.cipher.encrypt(strxor(e.slice(a,a+BS),s)));let r=e.slice(i),o;return r.length===BS?o=this.k1:(o=this.k2,r+="€"+repeatString("\0",BS-r.length-1)),this.cipher.encrypt(strxor(strxor(r,s),o)).toLowerCase()}}const getIviUid=()=>{const t=STORE_KEYS.vod.ivi.uid,e=storage.get(t);if(e)return e;const s=Math.random().toString(10).slice(2);return storage.set(t,s),s},savedCmacs={},getCmac=t=>{const e=[t.cmakKey||"",t.cmakK1||"",t.cmakK2||""],s=e.join("_");return savedCmacs[s]||(savedCmacs[s]=new IVICMACBF(e)),savedCmacs[s]},sendMessageToIvi=async(t,e,s)=>{const i=(await iviLight.post("/",{languageCode:s.languageCode,ctx:s.ctx,data:'{"method":"da.timestamp.get","params":[]}'})).result,r=JSON.stringify(e),a=getCmac(t).calculateSign(i+r),l=await iviLight.post(`/?app_version=${t.appVersion}&ts=${i}&sign=${a}`,{languageCode:"",ctx:void 0,data:r});if(l.error)throw l.error;return l},getContentInfo=async(t,e)=>{const s={params:[parseInt(t.id||"",10),{uid:getIviUid(),session:t.iviSession||"",app_version:parseInt(t.appVersion||"",10)}],method:"da.content.get"},{result:n}=await sendMessageToIvi(t,s,e);return n},fetchLoaderData=t=>axios.get(t).then(e=>e.data).catch(errorHandler),getOffer=(t,e)=>fe.get(URLS.offers.offer(t),e),getOfferAllChannels=(t,e)=>fe.get(URLS.offers.offerAllChannels(t),e),getOfferShowcaseChannels=(t,e)=>fe.get(URLS.offers.offerShowcaseChannels(t),e),log$Q=logger$1("pauses-api"),sortPausesByCreatedAt=(t,e)=>e.createdAt-t.createdAt,prepareVodPause=t=>{const e=convertToSeconds(t.totalDurationMsec,"millisecond"),s=Math.ceil(convertToSeconds(t.msecFromStart,"millisecond"));return{...t,currentProgress:parseFloat((t.msecFromStart/t.totalDurationMsec).toFixed(4)),fromStart:s,duration:e.toString(),timeLeft:s.toString()}},getVodPauses=async t=>{let e=[];const s=URLS.pauses.vod.titles;try{const n=await fe.get(s,t);e=(n==null?void 0:n.pauses)||[]}catch(n){log$Q.error(`Unable to load ${s}`,n)}return e.map(prepareVodPause)},getVodTitlePauses=async(t,e,s)=>{let n=[];const i=URLS.pauses.vod.title(t,e);try{const r=await fe.get(i,s);n=(r==null?void 0:r.pauses)||[],n.length&&n.sort(sortPausesByCreatedAt)}catch(r){log$Q.error(`Unable to load ${i}`,r)}return n.map(prepareVodPause)},saveVodPause$1=async(t,e,s,n,i,r,o="",a="",l=0)=>{if(i){if(!e||!n||!r||r<=1e3){log$Q.warn("Could not save pause",{sourceId:e,titleId:s,mediaItemId:n,msecFromStart:i,totalDurationMsec:r});return}try{await fe.post(URLS.pauses.vod.titles,{data:{sourceId:e,titleId:s,mediaItemId:n,msecFromStart:i,totalDurationMsec:r,episodeId:o,seasonId:a,expiresAt:l},...t})}catch(c){log$Q.error(c)}}},deleteVodPause$1=async(t,e,s)=>fe.post(URLS.pauses.vod.delete(t,e),s),getTvPauses=async(t,e)=>{var n;const s=await fe.get(`${URLS.pauses.tv}/${t}`,e);return(n=s==null?void 0:s.programPauses)!=null&&n.length&&(s==null||s.programPauses.sort(sortPausesByCreatedAt)),(s==null?void 0:s.programPauses)||[]},saveTvPause=async t=>fe.put(URLS.pauses.tv,t),getPopupNotices=async(t,e)=>{const s=await fe.get(URLS.popupNotices.elements(t),e);return s==null?void 0:s.elements},whatToShow=async t=>await fe.post(URLS.popupNotices.whatToShow,{...t,jsonData:!0}),reportAction$1=async t=>await fe.post(URLS.popupNotices.reportAction,t),reportExitAction$1=t=>{t.data.actionType="exit",fe.sendBeacon(URLS.popupNotices.reportAction,t)},change$1=t=>fe.post(wlDetector().isSmotreshka?URLS.changeProfileV2:URLS.changeProfile,t),create=t=>fe.post(URLS.createProfile,t),update$1=(t,e)=>fe.put(URLS.updateProfile(t),e),remove=(t,e)=>fe.delete(URLS.deleteProfile(t),e),getProfile=(t,e)=>fe.get(URLS.getProfile(t),e),managing=t=>fe.post(URLS.managingLogin,t),managingLogout=t=>fe.post(URLS.managingLogout,t),managingWithVerifiedContacts=t=>fe.post(URLS.managingLoginWithVerifiedContacts,t),getProfileRestrictions$1=async t=>{const e=await fe.get(URLS.profileRestrictions,t);return(e==null?void 0:e.restrictions)||[]},changePassword=t=>fe.post(URLS.changePassword,t),activateSubscription=(t,e)=>fe.post(URLS.yakassa.activateSubscription(t),e),cancelSubscription=(t,e)=>fe.post(URLS.yakassa.cancelSubscription(t),e),managingMethods=async t=>{const e=await fe.get(URLS.managingLoginMethods,t);return sortBy(e==null?void 0:e.methods,"priority")||[]},enableAutoRenewSubscription=(t,e)=>fe.post(URLS.quickSubscribe.enableAutoRenew(t),e),disableAutoRenewSubscription=(t,e)=>fe.post(URLS.quickSubscribe.disableAutoRenew(t),e),renewSubscription=(t,e)=>fe.post(URLS.quickSubscribe.autoRenew(t),e),getPromoElements=async(t="",e)=>{const s=await fe.get(URLS.promoElements(t),e);return(s==null?void 0:s.elements)||[]},log$P=logger$1("quick-subscribe-api"),vod$3=t=>fe.get(URLS.quickSubscribe.vodSubscriptionOptions,t),tv=(t,e)=>fe.get(URLS.quickSubscribe.tvSubscriptionOptions(t),e),tvV3=(t,e)=>fe.get(URLS.quickSubscribe.tvSubscriptionOptionsV3(t),e),vodV3=t=>fe.get(URLS.quickSubscribe.vodSubscriptionOptionsV3,t),offersSet=(t,e)=>fe.get(URLS.quickSubscribe.offersSet(t),e),paymentMethod=t=>fe.get(URLS.yakassa.paymentMethod,t),yakassaSubscriptions=t=>fe.get(URLS.yakassa.subscriptions,t),currentSubscriptions=t=>fe.get(URLS.quickSubscribe.currentSubscriptions,t),subscription=(t,e)=>fe.get(URLS.yakassa.subscription(t),e),renewSubscriptionWithExistedPm=(t,e)=>fe.post(URLS.yakassa.renewSubscriptionWithExistedPm(t),e),renewSubscriptionWithNewPm=(t,e)=>fe.post(URLS.yakassa.renewSubscriptionWithNewPm(t),e),removePaymentMethod$1=t=>fe.post(URLS.yakassa.removePaymentMethod,t),createYakassaSubscription$1=t=>fe.post(URLS.yakassa.subscriptions,t),createYakassaSubscriptionV2$1=t=>fe.post(URLS.yakassa.createSubscription,t),createSubscription$2=t=>fe.post(URLS.quickSubscribe.createSubscription,t),createSubscriptionWithVerifiedPhone$1=t=>fe.post(URLS.quickSubscribe.createSubscriptionWithVerifiedPhone,t),createSubscriptionUpsale$1=t=>fe.post(URLS.quickSubscribe.createSubscriptionUpsale,t),createSubscriptionUpsaleV2$1=t=>fe.post(URLS.quickSubscribe.createSubscriptionUpsaleV2,t),getArchivedSubscriptions=t=>fe.get(URLS.yakassa.archivedSubscriptions,t),getLastPaymentFromKassa=(t,e)=>fe.get(URLS.yakassa.lastPaymentFromKassa(t),e),loadAllAvailableSubscriptionOptions$1=t=>fe.get(URLS.quickSubscribe.allAvailableSubscriptionOptions,t),loadShopSubscriptionOptions$1=(t="",e)=>fe.get(URLS.quickSubscribe.subscriptionShop(t),e),getLastPayment=async(t,e,s=!1,n=1)=>{const r=s?120:5,o=await getLastPaymentFromKassa(t,e).catch(l=>{log$P.error(l)});if(!o)return{status:""};const a=o.status;return new Promise(l=>{a!==SUBSCRIPTION_STATUSES.PENDING||n>=r?l(o):setTimeout(async()=>
4{l(await getLastPayment(t,e,s,n+1))},5e3)})},checkPaymentStatusTrials=async(t,e,s,n="")=>{const i=await subscription(s,{params:{token:n},ctx:t,languageCode:e}),r=[SUBSCRIPTION_STATUSES.CANCELED,SUBSCRIPTION_STATUSES.SUCCEEDED,SUBSCRIPTION_STATUSES.WAITING_FOR_CAPTURE];return(i==null?void 0:i.subscription_renew_status)==="active"&&r.includes(i.last_payment.status)},sendStatistics=(t,e,s)=>{e.ChannelId&&fe.sendBeacon(URLS.statistics,{ctx:t,languageCode:"ru",params:{externalPlayerPlatform:s},data:e})},loadThumbnails=async(t,e)=>{const{data:n}=await axios.get(t,{params:{timestamp:e,before:200,after:200}});return((n==null?void 0:n.images)||[]).map(r=>{const o=parseFloat(n.base);return{...r,url:`${n.prefix}${r.u}${n.suffix}`,from:o+r.b,to:o+r.e}})},log$O=logger$1("api-tokens"),getAssetTokensV2=async t=>(t.params={"device.drm":getDeviceDrmQueryParamValue(getUserAgent(t.ctx))},await fe.get(URLS.assetTokensV2,t)),postAssetTokensV2=async(t,e)=>(e.data={contextToken:t},e.params={"device.drm":getDeviceDrmQueryParamValue(getUserAgent(e.ctx))},fe.post(URLS.assetTokensV2,e)),getAssetTokensV1=async t=>{let e;try{e=await fe.get(URLS.assetTokens,t)}catch(o){e=null,log$O.error(o)}if(!e)return null;const s=dayjs(),n=dayjs(e==null?void 0:e.expiresAt),i=n.diff(s)*.1,r=new Date(n.valueOf()-i);return e.expiresAt=r.toString(),e},log$N=logger$1("api-vod"),vod$2=URLS.vod,getSources=async t=>fe.get(vod$2.sources,t),getCategories=async(t,e)=>fe.get(vod$2.categories(t),e),getFavorites=async t=>fe.get(vod$2.favorites,t),addToFavorites=async(t,e,s)=>fe.post(`${vod$2.favorites}?sourceId=${e}&titleId=${t}`,s),removeFromFavorites=async(t,e,s)=>fe.delete(`${vod$2.favorites}?sourceId=${e}&titleId=${t}`,s),getCategoryTitles=async({sourceId:t,categoryId:e,genreIds:s,limit:n=DEFAULT_TILES_AMOUNT,offset:i=0,sort:r="asc",languageCode:o="",ctx:a=void 0})=>{const l={categoryId:e,genreIds:s,limit:n,offset:i,sort:r};l.categoryId=l.categoryId==="-1"?l.categoryId="":l.categoryId;let c=[],d=c.length;for(;c.length<n;){const u=await getTitles(t,{params:l,languageCode:o,ctx:a});if(c=c.concat((u==null?void 0:u.titles)||[]),c=uniqBy(c,h=>h.id),l.offset+=c.length,c.length===d||c.length<DEFAULT_TILES_AMOUNT)break;d=c.length}return c.slice(0,n)},getSimilarities=async(t,e,s,n)=>fe.get(vod$2.similarities(t,e,s),n),getTitles=async(t,e)=>fe.get(vod$2.titles(t),e),getTitlesMeta=async(t,e)=>fe.get(vod$2.titlesMeta(t),e),getSearchTitles=async(t,e)=>fe.get(vod$2.searchTitles(t),e),getHboMaxUrl=async(t,e)=>fe.get(URLS.externalPlayer.vod.hboMax(t),e),getTitle=async(t,e,s)=>{var i,r,o,a,l,c,d,u,h,f,g,p,m;const n=await fe.get(vod$2.title(t,e),s);if(n){(i=n.preview)!=null&&i.ageRating&&(n.preview.ageRating=n.preview.ageRating.replace(/\D/g,"")+"+");let v=!1;return(o=(r=n.preview)==null?void 0:r.brandingMethods)!=null&&o.find(S=>S.name===HBO_MAX_BRANDING_METHOD)&&(v=!0),{preview:n.preview,details:{actors:((a=n.details)==null?void 0:a.actors)||[],backgrounds:((l=n.details)==null?void 0:l.backgrounds)||[],brandingMethods:((c=n.details)==null?void 0:c.brandingMethods)||[],description:((d=n.details)==null?void 0:d.description)||"",directors:((u=n.details)==null?void 0:u.directors)||[],episodes:[],isHboMaxBrandingMethod:v,logoTitles:((h=n.details)==null?void 0:h.logoTitles)||[],mediaItems:((f=n.details)==null?void 0:f.mediaItems)||[],screenshots:((g=n.details)==null?void 0:g.screenshots)||[],seasons:((m=(p=n.details)==null?void 0:p.seasons)==null?void 0:m.sort((S,y)=>S.number-y.number))||[]},pauses:[],loading:!1,loaded:!0}}else return},getAllEpisodes=async(t,e,s)=>{const n=await fe.get(vod$2.allEpisodes(t,e),s);return Array.isArray(n==null?void 0:n.episodes)?n==null?void 0:n.episodes:[]},getSeason=async(t,e,s,n)=>fe.get(vod$2.season(t,e,s),n),getSeasonEpisodes=async(t,e,s,n)=>fe.get(vod$2.seasonEpisodes(t,e,s),n),loadTitleSeasonsAndEpisodes=async(t,e,s,n=[],i="{without_season}")=>{let r=[],o=n;if(n.length){const c=n.filter(u=>u.id!=="0").map(u=>getSeasonEpisodes(t,e,u.id,s).catch(h=>log$N.error(h))),d=await Promise.all(c);d==null||d.forEach((u,h)=>{var f;(f=u==null?void 0:u.episodes)==null||f.forEach(g=>{var p;r.push({details:void 0,preview:{seasonId:(p=o[h])==null?void 0:p.id,...g}})})}),log$N.info("Episodes for seasons have finished loading")}const a=await getAllEpisodes(t,e,s),l=await Promise.all(a);if(l.length&&(o.push({id:"0",number:0,title:i}),l.forEach(c=>{r==null||r.push({details:void 0,preview:{seasonId:"0",...c}})}),log$N.info("Episodes without season have finished loading")),t==="archive"){const c=r.map(u=>{var h;return getTitle(t,((h=u.preview)==null?void 0:h.id)||"",s).catch(f=>{log$N.error(f)})}),d=await Promise.all(c);r=r.map(u=>{var h;return{...u,details:(h=d.find(f=>{var g,p;return((g=f==null?void 0:f.preview)==null?void 0:g.id)===((p=u.preview)==null?void 0:p.id)}))==null?void 0:h.details}}),log$N.info("Episodes' data for Archive have finished loading")}if(n.length){const c=n.filter(u=>u.id!=="0").map(u=>getSeason(t,e,u.id,s).catch(h=>log$N.error(h))),d=await Promise.all(c);d!=null&&d.length&&(o=o.map(u=>{var h;return{...u,description:((h=d.find(f=>f.id===u.id))==null?void 0:h.description)||""}}),log$N.info("Seasons' data was successfully updated"))}return{titleEpisodes:r,titleSeasons:o}},getVodSourceCollections=async(t,e="")=>
4fe.get(URLS.vod.collections(e),t),getVodHomeCollections=async(t,e=!1,s="")=>fe.get(e?URLS.home.vodCollectionsV3(s):URLS.home.vodCollectionsV2(s),t),getCollectionTitles=async(t,e=void 0,s,n,i=0,r=DEFAULT_TILES_AMOUNT)=>{const o={limit:r,offset:i};return fe.get(vod$2.collectionTitles(s,n),{params:o,languageCode:t,ctx:e})},getSimilarCollections=async(t,e="",s,n,i)=>{var o;let r=[];try{r=((o=await getSimilarities(n,i,s,{languageCode:e,ctx:t}))==null?void 0:o.similarTitlesCollections)||[],r=(r==null?void 0:r.filter(a=>{var l;return((l=a.titlesList)==null?void 0:l.length)>=5}))||[],r.length=r.length>3?3:r.length,r=r.map(a=>{var l;return{caption:a.caption,id:a.id,titlesList:(l=a.titlesList)==null?void 0:l.filter((c,d)=>d<12)}})}catch(a){log$N.error(a)}return r||[]},getVodPlayback=async(t,e)=>fe.get(vod$2.playback(t),e),postVodPlaybackUpdate=async(t,e,s)=>fe.post(vod$2.playbackUpdate(t,e),s),getIviPlayback=async(t,e)=>fe.get(vod$2.ivi.playback(t),e),getAmediaPlayback=async(t,e)=>fe.get(vod$2.amedia.playback(t),e),getMegogoPlayback=async(t,e)=>fe.get(vod$2.megogo.playback(t),e),getPlaybackLsHlsVideo=async(t,e)=>fe.get(URLS.vod.playbackLsHls(e),t),postBegin=t=>fe.post(URLS.unsubscriptionRetention.begin,t),postEnd=t=>fe.post(URLS.unsubscriptionRetention.end,t),getSubscriptionOptions=t=>fe.get(URLS.unsubscriptionRetention.subscriptionOptions,t),postSearchHistoryStarted=async(t,e)=>fe.post(URLS.searchHistory.start,{...t,data:e,jsonData:!0}),postSearchHistoryFinished=async(t,e)=>fe.post(URLS.searchHistory.finish,{...t,data:e,jsonData:!0}),postSearchHistoryUseTvChannel=async(t,e)=>fe.post(URLS.searchHistory.useTvChannel,{...t,data:e,jsonData:!0}),postSearchHistoryV2UseTvChannel=async(t,e)=>fe.post(URLS.searchHistory.useTvChannelV2,{...t,data:e,jsonData:!0}),postSearchHistoryUseVodTitle=async(t,e)=>fe.post(URLS.searchHistory.useVodTitle,{...t,data:e,jsonData:!0}),postSearchHistoryV2UseVodTitle=async(t,e)=>fe.post(URLS.searchHistory.useVodTitleV2,{...t,data:e,jsonData:!0}),getSearchHistory=async t=>fe.get(URLS.searchHistory.getHistory,t),getSearchV2=async t=>fe.get(URLS.searchHistory.searchV2,t),postReportSearch=async(t,e)=>fe.post(URLS.searchHistory.report,{...t,data:e,jsonData:!0}),getRegions=t=>fe.get(URLS.regions,t),getProviders=t=>fe.get(URLS.providers,t),getContactsVerificationCaptchaData=t=>fe.get(URLS.contactsVerification.captchaData,{...t,jsonData:!0}),getContactsVerificationCaptchaImage=async(t,e)=>{const s=new URLSearchParams(getAppVersionParamsFlattened(e.ctx)).toString(),n=await fe.get(`${URLS.contactsVerification.captchaImage(t)}?${s}`,{...e,responseType:"blob",withCredentials:!0});return URL.createObjectURL(n)},getCaptchaImage=async(t,e,s,n)=>{const i=new URLSearchParams(getAppVersionParamsFlattened(n.ctx)).toString(),r=`t=${t}&${i}`,o=e?"reload=$true":"",a=s?`${getEnvVars().beBaseUrl}/contacts-verification/v1/captcha?${r}`:`${getEnvVars().beBaseUrl}/captcha?${o}&${r}`,l=await axios.request({url:a,method:"get",responseType:"blob",withCredentials:!0});return{url:URL.createObjectURL(l.data),cookieHeaders:l.headers["cookie-custom"]?JSON.parse(l.headers["cookie-custom"]).reduce((c,d)=>`${c}${d.name}=${d.value};`,""):""}},sendUnifiedEvents=t=>fe.post(URLS.clientAnalytics,t);var SubscriptionStatus=(t=>(t.ACTIVE="ACTIVE",t.CANCELED_BY_USER="CANCELED_BY_USER",t.CANCELED_BY_PAYMENT="CANCELED_BY_PAYMENT",t.CANCELED_BY_REMOVING_PAYMENT_METHOD="CANCELED_BY_REMOVING_PAYMENT_METHOD",t.IN_RETRY="IN_RETRY",t.UNRECOGNIZED="UNRECOGNIZED",t))(SubscriptionStatus||{}),PaymentSystem=(t=>(t.Yakassa="Yakassa",t.Apple="Apple",t.Android="Android",t.Smartpay="Smartpay",t.Uztelecom="Uztelecom",t.Megafon="Megafon",t.UNRECOGNIZED="UNRECOGNIZED",t))(PaymentSystem||{});const setCurrentStep=(t,e)=>{t.adultOnboarding.currentStep=e},setNextStep=(t,e)=>{t.adultOnboarding.nextStep=e},resetStepsHistory=t=>{t.adultOnboarding.stepsHistory.length=0,t.adultOnboarding.stepsHistory=[]},addToStepsHistory=(t,e)=>{t.adultOnboarding.stepsHistory.push(e)},removeFromStepsHistory=t=>{t.adultOnboarding.stepsHistory.pop()},setPinAction=(t,e)=>{t.adultOnboarding.pinAction=e},adultOnboarding=Object.freeze(Object.defineProperty({__proto__:null,addToStepsHistory,removeFromStepsHistory,resetStepsHistory,setCurrentStep,setNextStep,setPinAction},Symbol.toStringTag,{value:"Module"}
4)),archiveTitlePlaybackMethodSelector=t=>{var i,r,o,a;const e=playingTitleSelector(t);if(!e)return;let s=[];if((i=e.preview)!=null&&i.hasSeries){const l=playingTitlePauseSelector(t),c=playingEpisodeIdSelector(t)||(l==null?void 0:l.episodeId);if(!c)return null;const d=(r=e==null?void 0:e.details)==null?void 0:r.episodes,u=d==null?void 0:d.find(f=>{var g;return((g=f.preview)==null?void 0:g.id)===c});if(!(u&&((o=u.details)!=null&&o.mediaItems)))return null;const h=playingMediaItemSelector(t,u.details.mediaItems);s=sortBy(h==null?void 0:h.playbackMethods,"priority")}else{if(!(e&&((a=e.details)!=null&&a.mediaItems)))return null;const l=playingMediaItemSelector(t,e.details.mediaItems);s=sortBy(l==null?void 0:l.playbackMethods,"priority")}const n=Object.values(PLAYBACK_METHODS);return s.find(l=>n.includes(l.name))},archiveTitlePlaybackMethodParamsSelector=t=>{const e=archiveTitlePlaybackMethodSelector(t);return e?e.params.reduce((s,n)=>(s[n.key]=n.value,s),{}):null},archiveTitleStartTimeSelector=t=>{const e=archiveTitlePlaybackMethodSelector(t),s=archiveTitlePlaybackMethodParamsSelector(t);return e&&s&&e.name===PLAYBACK_METHODS.smotreshkaPlaybackInfo?parseInt(s.start):0},archiveTitleDurationSelector=t=>{const e=archiveTitlePlaybackMethodSelector(t),s=archiveTitlePlaybackMethodParamsSelector(t);if(!(e&&s))return 0;switch(e.name){case PLAYBACK_METHODS.smotreshkaPlaybackInfo:return parseInt(s.end)-parseInt(s.start);default:return 0}},archiveTimelineDurationSelector=t=>archiveTitleDurationSelector(t)+archiveTitleDurationSelector(t)*ARCHIVE_PLAYER_TICK_OFFSET*2,archiveTickDurationSelector=t=>ARCHIVE_PLAYER_TICK_OFFSET*archiveTimelineDurationSelector(t),archiveTimelineStartsSelector=t=>archiveTitleStartTimeSelector(t)-archiveTickDurationSelector(t),sourcesSelector=t=>t.vod.sources,sourceSelector=(t,e)=>sourcesSelector(t)[e],sourcesWithoutArchiveSelector=t=>t.vod.sources?Object.values(t.vod.sources).filter(e=>e.id!=="archive").reduce((e,s)=>({...e,[s.id]:s}),{}):{},listOfSourceIdsWithoutArchiveSelector=t=>t.vod.sources?Object.values(t.vod.sources).filter(s=>s.isUsed).map(s=>s.id):[],listOfAllSourceIdsSelector=t=>t.vod.sources?Object.values(t.vod.sources).map(e=>e.id):[],sourcesLoadedSelector=t=>t.vod.states.sourcesLoaded,sourcesLoadingSelector=t=>t.vod.states.sourcesLoading,favoritesSelector=t=>t.vod.favorites||[],favoritesFilteredSelector=t=>favoritesSelector(t).filter(e=>e.source&&e.titleId&&listOfAllSourceIdsSelector(t).includes(e.source)),isInFavoritesSelector$1=(t,e)=>!!favoritesSelector(t).find(s=>s.id===e||s.titleId===e),favoritesLoadedSelector=t=>t.vod.states.favoritesLoaded,favoritesLoadingSelector=t=>t.vod.states.favoritesLoading,sourceCategoriesSelector=(t,e)=>{var s;return((s=sourceSelector(t,e))==null?void 0:s.categories)||{}},sourceCategoriesSortedSelector=(t,e)=>{var n;const s=sourceCategoriesSelector(t,e);return s?(n=Object.values(s))==null?void 0:n.sort((i,r)=>i.priority-r.priority):[]},sourceCategoriesLoadedSelector=(t,e)=>{var s,n;return(n=(s=t.vod.sources)==null?void 0:s[e])==null?void 0:n.categoriesLoaded},sourceCategoriesLoadingSelector=(t,e)=>{var s,n;return(n=(s=t.vod.sources)==null?void 0:s[e])==null?void 0:n.categoriesLoading},currentCategoryIdSelector=(t,e)=>{var s,n,i;return((i=(n=(s=t.vod)==null?void 0:s.sources)==null?void 0:n[e])==null?void 0:i.currentCategoryId)||""},currentCategorySelector=(t,e)=>{var n,i,r,o;const s=currentCategoryIdSelector(t,e);return s?(o=(r=(i=(n=t.vod)==null?void 0:n.sources)==null?void 0:i[e])==null?void 0:r.categories)==null?void 0:o[s]:void 0},categoryIdFromTitleSelector=(t,e,s)=>{var r,o,a;const n=(r=e==null?void 0:e.preview)==null?void 0:r.categories,i=sourceCategoriesSelector(t,s);return!n||!i?"":(o=n[0])!=null&&o.id?n[0].id:((a=Object.values(i||{}).find(l=>{var c;return l.title===((c=n[0])==null?void 0:c.title)}))==null?void 0:a.id)||""},isAnyHomeCollectionLoadingSelector=t=>t.vod.states.isAnyHomeCollectionLoading,isAnyHomeCollectionLoadedSelector=t=>t.vod.states.isAnyHomeCollectionLoaded,isSourceCollectionLoadingSelector=t=>t.vod.states.isSourceCollectionLoading,isSourceCollectionLoadedSelector=t=>t.vod.states.isSourceCollectionLoaded,sourceCollectionSelector=(t,e)=>t.vod.sourceCollections.find(s=>s.id===e),hasMoreTitlesToLoadSelector=(t,e)=>{var s;return(s=sourceCollectionSelector(t,e))==null?void 0:s.hasMoreTitlesToLoad},isAnyVodHomeCollectionVisibleSelector=t=>{var e,s,n,i;return((s=(e=t.homeScreenConfig)==null?void 0:e.options)==null?void 0:s.showVodCollections)!==void 0?(i=(n=t.homeScreenConfig)==null?void 0:n.options)==null?void 0:i.showVodCollections:!0},homeCollectionsSelector=t=>t.vod.homeCollections||[],sourceCollectionsSelector=t=>t.vod.sourceCollections||[],homeCollectionsFilteredByPlacementBlocksSelector=(t,e)=>{var s;return(s=homeCollectionsSelector(t))==null?void 0:s.filter(({placementBlocks:n})=>n==null?void 0:n.find(({blockId:i})=>e==null?void 0:e.includes(i)))},collectionSelector=(t,e)=>sourceCollectionsSelector(t).find(s=>s.id===e)||homeCollectionsSelector(t).find(s=>s.id===e||s.vodCollectionId===e),megaCollectionsSelector=t=>{var e;return((e=t.siteConfig)==null?void 0:e.vodMegaCollections)||[]},megaCollectionsAvailableSelector=t=>megaCollectionsSelector(t).filter(e=>e.slug&&collectionsFromMegaCollectionSelector(t,e).length),megaCollectionsInSlidersSelector=t=>megaCollectionsAvailableSelector(t).filter(e=>e.showOnMain),collectionsFromMegaCollectionSelector=(t,e)=>{var s;return(s=t.vod.homeCollections)==null?void 0:s.filter(({placementBlocks:n})=>n==null?void 0:n.find(({blockId:i})=>{var r;return(r=e.placementBlocksString)==null?void 0:r.includes(i)}))},currentMegaCollectionSelector=(t,e)=>megaCollectionsSelector(t).find(s=>s.slug&&s.slug===e),sortingSelector=t=>t.vod.sorting,sortingsSelector=t=>t.vod.sortings,archivePosterWidthProportionSelector=t=>{var e,s,n;return((n=(s=(e=t.siteConfig)==null?void 0:e.archiveCatalog)==null?void 0:s.posterProportions)==null?void 0:n.width)||16},archivePosterHeightProportionSelector=t=>{var e,s,n;return((n=(s=(e=t.siteConfig)==null?void 0:e.archiveCatalog)==null?void 0:s.posterProportions)==null?void 0:n.height)||9},posterWidthProportionSelector=(t,e)=>{var s,n,i,r,o;return e==="archive"?((i=(n=(s=t.siteConfig)==null?void 0:s.archiveCatalog)==null?void 0:n.posterProportions)==null?void 0:i.width)||16:((o=(r=t.vod.sources[e])==null?void 0:r.posterProportions)==null?void 0:o.width)||2},posterHeightProportionSelector=(t,e)=>{var s,n,i,r,o;return e==="archive"?((i=(n=(s=t.siteConfig)==null?void 0:s.archiveCatalog)==null?void 0:n.posterProportions)==null?void 0:i.height)||9:((o=(r=t.vod.sources[e])==null?void 0:r.posterProportions)==null?void 0:o.height)||3},sourceLogoUrlSelector=(t,e,s)=>{var r,o;const n=s||t.theme,i=getByLanguage(n==="light"?(r=t.vod.sources[e])==null?void 0:r.logoTilePoster:(o=t.vod.sources[e])==null?void 0:o.logoTilePosterDark,t.languageCode,t.defaultLanguageCode);return(i==null?void 0:i.url)||""},titleLogoSelector=(t,e,s)=>{const n=e.availableOnTvChannels,i=n&&n.length?n[0].channelId:"",r=c
4hannelByIdSelector(t,i);return r?getChannelLogo(r):s.logo},titleEnhancedSelector=(t,e,s)=>{var n,i;return(i=(n=t.vod.sources[e])==null?void 0:n.titlesEnhanced)==null?void 0:i[s]},titleEnhancedLoadedSelector=(t,e,s)=>{var n;return(n=titleEnhancedSelector(t,e,s))==null?void 0:n.loaded},titleEnhancedLoadingSelector=(t,e,s)=>{var n;return(n=titleEnhancedSelector(t,e,s))==null?void 0:n.loading},audioTrackIndexSelector=t=>t.vod.audioTrackIndex,playingSourceSelector=t=>{var e;return(e=t.vod.sources)==null?void 0:e[playingSourceIdSelector(t)]},playingTitleSelector=t=>{var e,s;return(s=(e=playingSourceSelector(t))==null?void 0:e.titlesEnhanced)==null?void 0:s[playingTitleIdSelector(t)]},playingTitlePauseSelector=t=>{var r,o,a;const e=playingTitleSelector(t),s=playingEpisodeIdSelector(t),n=playingMediaItemIdSelector(t);let i;return n?i=(r=e==null?void 0:e.pauses)==null?void 0:r.find(l=>l.mediaItemId===n):s?i=(o=e==null?void 0:e.pauses)==null?void 0:o.find(({episodeId:l})=>l===s):i=(a=e==null?void 0:e.pauses)==null?void 0:a[0],i},episodeTitleSelector=(t,e)=>{var a,l;const s=playingTitleSeasonsSelector(t).find(c=>{var d;return c.id===((d=e==null?void 0:e.preview)==null?void 0:d.seasonId)}),n=hasSeasonsInPlayingTitleSelector(t)&&(s!=null&&s.number)?`${translationSelector(t,"season")} ${s.number}. `:"",i=(a=e==null?void 0:e.preview)==null?void 0:a.episodeNumber,o=((l=e==null?void 0:e.preview)==null?void 0:l.title)||(i?`${translationSelector(t,"episode")} ${i}`:"");return n+o},playingTitleEpisodesSelector=t=>{var e,s;return((s=(e=playingTitleSelector(t))==null?void 0:e.details)==null?void 0:s.episodes)||[]},playingEpisodeTitleSelector=t=>{const e=playingEpisodeSelector(t);return episodeTitleSelector(t,e)},nextEpisodeTitleSelector=t=>{const e=nextEpisodeSelector(t);return episodeTitleSelector(t,e)},playingEpisodeIndexSelector=t=>playingTitleEpisodesSelector(t).findIndex(s=>{var n;return((n=s.preview)==null?void 0:n.id)===playingEpisodeIdSelector(t)}),playingEpisodeSelector=t=>{const e=playingTitleEpisodesSelector(t),s=playingEpisodeIndexSelector(t);return e[s]},prevEpisodeSelector=t=>{const e=playingTitleEpisodesSelector(t),s=playingEpisodeIndexSelector(t);return e[s-1]},nextEpisodeSelector=t=>{const e=playingTitleEpisodesSelector(t),s=playingEpisodeIndexSelector(t);return e[s+1]},titleEpisodesSelector=(t,e,s)=>{var n,i;return((i=(n=titleEnhancedSelector(t,e,s))==null?void 0:n.details)==null?void 0:i.episodes)||[]},titleSeasonsSelector=(t,e,s)=>{var n,i;return((i=(n=titleEnhancedSelector(t,e,s))==null?void 0:n.details)==null?void 0:i.seasons)||[]},playingTitleSeasonsSelector=t=>{var e,s;return((s=(e=playingTitleSelector(t))==null?void 0:e.details)==null?void 0:s.seasons)||[]},hasSeasonsInPlayingTitleSelector=t=>{var e;return((e=playingTitleSeasonsSelector(t))==null?void 0:e.length)>0},selectedSeasonIndexSelector=(t,e,s,n,i=-1)=>{if(i>=0)return i;const r=playingEpisodeSelector(t),o=titleSeasonsSelector(t,e,s).findIndex(a=>{var l;return a.id===((l=r==null?void 0:r.preview)==null?void 0:l.seasonId)||a.number===n});return Math.max(o,0)},titleH1Selector=(t,e,s=-1)=>{var i,r,o,a;if(!((i=e==null?void 0:e.preview)!=null&&i.title))return"";let n="";switch(s){case-1:break;case 0:n=` (${(r=getByLanguage(t.translations.without_season,languageCodeSelector(t),t.defaultLanguageCode))==null?void 0:r.toLowerCase()})`;break;default:n=` (${(o=getByLanguage(t.translations.season,languageCodeSelector(t),t.defaultLanguageCode))==null?void 0:o.toLowerCase()} ${s})`;break}return`${(a=e==null?void 0:e.preview)==null?void 0:a.title}${n}`},metaTitleSelector=(t,e,s,n)=>{var m,v,S,y;const i=n&&n>0,r=(v=(m=t.vod)==null?void 0:m.sources)==null?void 0:v[e],o=r==null?void 0:r.titlesEnhanced[s],a=o==null?void 0:o.preview,l=(S=a==null?void 0:a.categories)==null?void 0:S[0],c=!i&&(l!=null&&l.title)?translationSelector(t,`category_${transliterate(l.title)}_singular`):"",h=`${e==="archive"?"archive":"vod"}_meta_title${i?"_with_season":""}`,f=i?`${getByLanguage(t.translations.series,languageCodeSelector(t),t.defaultLanguageCode)} ${titleH1Selector(t,o,n)}`:(a==null?void 0:a.title)||"";if(!f)return translationSelector(t,"title_unavailable");const g=i?"":(y=a==null?void 0:a.years)==null?void 0:y[0],p=r!=null&&r.customTitleId?translationSelector(t,r.customTitleId):"";return translationSelector(t,h).replace(/%titleName%/g,f).replace(/%titleType%/g,c).replace(/%year%/g,g?`${g}`:"").replace(/%vodName%/g,p)},vod$1=Object.freeze(Object.defineProperty({__proto__:null,archivePosterHeightProportionSelector,archivePosterWidthProportionSelector,archiveTickDurationSelector,archiveTimelineDurationSelector,archiveTimelineStartsSelector,archiveTitleDurationSelector,archiveTitlePlaybackMethodParamsSelector,archiveTitlePlaybackMethodSelector,archiveTitleStartTimeSelector,audioTrackIndexSelector,categoryIdFromTitleSelector,collectionSelector,collectionsFromMegaCollectionSelector,currentCategoryIdSelector,currentCategorySelector,currentMegaCollectionSelector,favoritesFilteredSelector,favoritesLoadedSelector,favoritesLoadingSelector,favoritesSelector,hasMoreTitlesToLoadSelector,hasSeasonsInPlayingTitleSelector,homeCollectionsFilteredByPlacementBlocksSelector,homeCollectionsSelector,isAnyHomeCollectionLoadedSelector,isAnyHomeCollectionLoadingSelector,isAnyVodHomeCollectionVisibleSelector,isInFavoritesSelector:isInFavoritesSelector$1,isSourceCollectionLoadedSelector,isSourceCollectionLoadingSelector,listOfAllSourceIdsSelector,listOfSourceIdsWithoutArchiveSelector,megaCollectionsAvailableSelector,megaCollectionsInSlidersSelector,megaCollectionsSelector,metaTitleSelector,nextEpisodeSelector,nextEpisodeTitleSelector,playingEpisodeIndexSelector,playingEpisodeSelector,playingEpisodeTitleSelector,playingSourceSelector,playingTitleEpisodesSelector,playingTitlePauseSelector,playingTitleSeasonsSelector,playingTitleSelector,posterHeightProportionSelector,posterWidthProportionSelector,prevEpisodeSelector,selectedSeasonIndexSelector,sortingSelector,sortingsSelector,sourceCategoriesLoadedSelector,sourceCategoriesLoadingSelector,sourceCategoriesSelector,sourceCategoriesSortedSelector,sourceCollectionSelector,sourceCollectionsSelector,sourceLogoUrlSelector,sourceSelector,sourcesLoadedSelector,sourcesLoadingSelector,sourcesSelector,sourcesWithoutArchiveSelector,titleEnhancedLoadedSelector,titleEnhancedLoadingSelector,titleEnhancedSelector,titleEpisodesSelector,titleH1Selector,titleLogoSelector,titleSeasonsSelector},Symbol.toStringTag,{value:"Module"})),isSourceIdValid=t=>typeof t=="string"&&!/[^a-z0-9.\-_]+/i.test(t),isTitleIdValid=t=>typeof t=="string"&&!/[^a-z0-9.\-+_\s;\\:%=]+/i.test(t),isSeasonNumValid=t=>typeof t=="string"&&!/[^0-9]+/.test(t),isVodMegaCollectionSlugValid=t=>typeof t=="string"&&!/[^a-z0-9.\-_]+/i.test(t),isVodCollectionIdValid=t=>typeof t=="string"&&!/[^a-z0-9.\-_]+/i.test(t),getTitlePosterUrl=t=>(t==null?void 0:t.path)||"",getTitlePosterType=t=>(t==null?void 0:t.type)||"",getMegogoPlaybackUrl=(t,e)=>/\/a\/\d+/.test(t)?t.replace(/\/a\/\d+/,`/a/${e.index}`):t.replace(/(\/o\/\d+\/)/,`/a/${e.index}$1`),log$M=logger$1("player-selectors"),typeSelector=t=>t.player.type,isTvSelector=t=>typeSelector(t)==="tv",isVodSelector=t=>typeSelector(t)==="vod",isArchiveSelector=t=>typeSelector(t)==="archive",isDateTimeVisibleSelector=t=>t.player.isDateTimeVisible,isPrerollVisibleSelector=t=>t.player.isPrerollVisible,isLiveSelector=t=>t.player.isLive,isLoadingSelector=t=>t.player.loading,isLoadedSelector=t=>t.player.loaded,alertSelector=t=>t.player.alert,dvrWarningOverlaySelector=t=>t.player.dvrWarningOverlay,errorSelector=t=>{const e=t.player.error;return e&&!e.message&&(e.code=PLAYER_ERROR_CODES.COMMON,e.message=translationSelector(t,"error_empty_response")),e},errorCodeSelector=t=>{var e;return(e=errorSelector(t))==null?void 0:e.code},hasErrorSelector=t=>!!errorSelector(t),isEpgInfoVisibleSelector=t=>t.player.isEpgVisible,isFullscreenMenuVisibleSelector=t=>isFullscreenSelector(t)&&t.player.isFullscreenMenuVisible,isSettingsMenuVisibleSelector=t=>t.player.isSettingsMenuVisible,isVolumeSliderVisibleSelector=t=>t.player.volumeSlider.visible,isRewindingSelector=t=>t.player.rewinding,isFastForwardingSelector=t=>t.player.fastForwarding,isBalloonVisibleSelector=t=>t.player.timeline.isBalloonVisible,overlayVisibleSelector=t=>t.player.overlay.visible,overlayFrozenSelector=t=>t.player.overlay.frozen,isOverlayVisibleSelector=t=>(!isPlayingSelector(t)||overlayVisibleSelector(t)||hasErrorSelector(t)||isOverlayFrozenSelector(t)||isMinimizedSelector(t)||isLoadingSelector(t))&&isLoadedSelector(t),isOverlayFrozenSelector=t=>hasErrorSelector(t)||!t.player.video.isPlaying||t.player.overlay.frozen||t.player.isFullscreenMenuVisible||t.player.isEpgVisible||t.player.isSettingsMenuVisible||t.player.volumeSlider.visible||t.player.rewinding||t.player.fastForwarding||t.modals.visibility.dvrWarning||t.modals.visibility.playerHelp,isTimelineBalloonFollowingMouseSelector=t=>t.player.timeline.isBalloonFollowingMouse,isMinimizedSelector=t=>t.player.minimized,isVisibleSelector=t=>t.player.visible,isScrollLockedSelector=t=>t.player.isScrollLocked,isPlayerControlDisabledSelector=t=>isLoadingSelector(t)||!isLoadedSelector(t)||isOfflineSelector(t)||hasErrorSelector(t),isRewind
4ButtonDisabledSelector=t=>{if(isPlayerControlDisabledSelector(t))return!0;if(isTvSelector(t)){const e=playingChannelSelector(t);return isDvrRestricted(e)||isDvrDisabled(e)}return isVodSelector(t)?playingTimeSelector(t)<THRESHOLDS.tv.shortJumpSeconds:!1},isFastForwardButtonDisabledSelector=t=>{if(isPlayerControlDisabledSelector(t))return!0;if(isTvSelector(t)){const e=playingChannelSelector(t);return isLiveSelector(t)||isDvrRestricted(e)||isDvrDisabled(e)}return isVodSelector(t)?videoDurationSelector(t)-playingTimeSelector(t)<THRESHOLDS.tv.shortJumpSeconds:!1},wasPlayingBeforeOfflineSelector=t=>t.player.video.wasPlayingBeforeOffline,isPlayingSelector=t=>t.player.video.isPlaying,isFullscreenSelector=t=>t.player.video.isFullscreen,videoPosterSelector=t=>t.player.video.poster,subtitleDisplaySelector=t=>t.player.video.subtitleDisplay,fps50Selector=t=>t.player.video.fps50,hasSubtitlesSelector=t=>t.player.video.hasSubtitles,isVideoScaledSelector=t=>t.player.video.scaled,isVideoMutedSelector=t=>t.player.video.muted,videoVolumeSelector=t=>t.player.video.volume,videoDurationSelector=t=>t.player.video.duration||1,playingTimeSelector=t=>t.player.video.playingTime||0,playingChannelIdSelector=t=>t.player.playing.channelId||"",playingChannelSelector=t=>t.tvChannels.list[playingChannelIdSelector(t)],playingSourceIdSelector=t=>t.player.playing.sourceId||"",playingTitleIdSelector=t=>t.player.playing.titleId||"",playingEpisodeIdSelector=t=>t.player.playing.episodeId||"",playingMediaItemIdSelector=t=>t.player.playing.mediaItemId||"",playingMediaItemSelector=(t,e)=>{var i,r,o,a;const s=(o=(r=(i=playingTitleSelector(t))==null?void 0:i.details)==null?void 0:r.episodes
4)==null?void 0:o.find(l=>{var c;return((c=l==null?void 0:l.preview)==null?void 0:c.id)===playingEpisodeIdSelector(t)});if(e=e||((a=s==null?void 0:s.details)==null?void 0:a.mediaItems),!(e!=null&&e.length))return;const n=playingMediaItemIdSelector(t);return n&&e.find(l=>l.id===n)||e[0]},playingSeasonIdSelector=t=>{var e;return((e=playingTitleSeasonsSelector(t).find(s=>{var n,i;return s.id===((i=(n=playingEpisodeSelector(t))==null?void 0:n.preview)==null?void 0:i.seasonId)}))==null?void 0:e.id)||""},archivePlayingUrlSelector=t=>{let e="";const s=selectors.playerPlayingChannel.renditionSelector(t);e=s==null?void 0:s.url;const n=Math.max(0,serverTimeSelector(t)-archiveTimelineStartsSelector(t));if(e){e=matchUrlProtocolWithLocationProtocol(e,t.common.isHttps);const i=n|0;i>CHUNK_LENGTH&&(e+=`&delay=${i-playingTimeSelector(t)}`)}else log$M.error("There is no URL in current rendition",s);return e},tvPlayingUrlSelector=t=>{let e="";const s=selectors.player.playingChannelSelector(t),n=selectors.player.playbackInfoSmotreshkaSelector(t),i=selectors.player.isLiveSelector(t),r=selectors.player.playingTimeSelector(t),o=selectors.appInfo.serverTimeSelector(t);let a=s&&hasDvr(s)?o-r:0;if(a=Math.max(0,a),!n)return e;const l=selectors.playerPlayingChannel.renditionSelector(t);return e=l==null?void 0:l.url,e?(e=matchUrlProtocolWithLocationProtocol(e,t.common.isHttps),!i&&a>CHUNK_LENGTH&&(e+=`&delay=${a}`)):log$M.error("There is no URL in current rendition",l),e},playingUrlSelector=(t,e)=>{var r,o,a,l;const s=getUserAgent(),n=getDrmSystem(s),i=playbackInfoAmediaSelector(t);if(typeSelector(t)==="tv")return tvPlayingUrlSelector(t);if(typeSelector(t)==="archive")return archivePlayingUrlSelector(t);switch(playbackMethodSelector(t)){case PLAYBACK_METHODS.amedia2V1:return i?getAmediaDrmStreamUrl(i,n):"";case PLAYBACK_METHODS.iviWithIntegrationParams:case PLAYBACK_METHODS.iviTwoSteps:return((a=(o=(r=playbackInfoIviSelector(t))==null?void 0:r.files)==null?void 0:o[0])==null?void 0:a.url)||"";case PLAYBACK_METHODS.megogoV1:{let c="";const d=playbackInfoMegogoSelector(t),u=(d==null?void 0:d.src)||"",h=(d==null?void 0:d.audio_tracks)||[];if(h.length>0){const f=audioTrackIndexSelector(t),g=h[f];g.index>=0?c=getMegogoPlaybackUrl(u,g):(c=u,log$M.error('Unable to get "index" field from audioTrack:',g,`by array element index = ${f} in`,h))}else c=u;return matchUrlProtocolWithLocationProtocol(c,t.common.isHttps)||""}default:return matchUrlProtocolWithLocationProtocol(((l=playbackInfoSmotreshkaVodV2Selector(t))==null?void 0:l.url)||"",t.common.isHttps)||""}},playbackMethodSelector=t=>t.player.playbackMethod,playbackInfoSelector=t=>t.player.playbackInfo,playbackInfoAmediaSelector=t=>playbackInfoSelector(t).amedia2V1,playbackInfoIviSelector=t=>playbackInfoSelector(t).ivi,playbackInfoMegogoSelector=t=>playbackInfoSelector(t).megogoV1,playbackInfoSmotreshkaSelector=t=>playbackInfoSelector(t).smotreshkaPlaybackInfo,playbackInfoSmotreshkaVodV2Selector=t=>playbackInfoSelector(t).smotreshkaVodV2,audioTracksSelector=t=>{var e,s;return playbackMethodSelector(t)===PLAYBACK_METHODS.megogoV1?(((e=playbackInfoMegogoSelector(t))==null?void 0:e.audio_tracks)||[]).map(i=>({caption:i.display_name||translationSelector(t,i.lang),id:i.id.toString(),index:i.index})):playbackMethodSelector(t)===PLAYBACK_METHODS.amedia2V1?(((s=playbackInfoAmediaSelector(t))==null?void 0:s.audioTracks)||[]).map(i=>({caption:translationSelector(t,i),id:i})):[]},player$1=Object.freeze(Object.defineProperty({__proto__:null,alertSelector,audioTracksSelector,dvrWarningOverlaySelector,errorCodeSelector,errorSelector,fps50Selector,hasErrorSelector,hasSubtitlesSelector,isArchiveSelector,isBalloonVisibleSelector,isDateTimeVisibleSelector,isEpgInfoVisibleSelector,isFastForwardButtonDisabledSelector,isFastForwardingSelector,isFullscreenMenuVisibleSelector,isFullscreenSelector,isLiveSelector,isLoadedSelector,isLoadingSelector,isMinimizedSelector,isOverlayFrozenSelector,isOverlayVisibleSelector,isPlayerControlDisabledSelector,isPlayingSelector,isPrerollVisibleSelector,isRewindButtonDisabledSelector,isRewindingSelector,isScrollLockedSelector,isSettingsMenuVisibleSelector,isTimelineBalloonFollowingMouseSelector,isTvSelector,isVideoMutedSelector,isVideoScaledSelector,isVisibleSelector,isVodSelector,isVolumeSliderVisibleSelector,overlayFrozenSelector,overlayVisibleSelector,playbackInfoAmediaSelector,playbackInfoIviSelector,playbackInfoMegogoSelector,playbackInfoSelector,playbackInfoSmotreshkaSelector,playbackInfoSmotreshkaVodV2Selector,playbackMethodSelector,playingChannelIdSelector,playingChannelSelector,playingEpisodeIdSelector,playingMediaItemIdSelector,playingMediaItemSelector,playingSeasonIdSelector,playingSourceIdSelector,playingTimeSelector,playingTitleIdSelector,playingUrlSelector,subtitleDisplaySelector,typeSelector,videoDurationSelector,videoPosterSelector,videoVolumeSelector,wasPlayingBeforeOfflineSelector},Symbol.toStringTag,{value:"Module"})),isFullscreenAvailable=()=>document.fullscreenEnabled||document.webkitFullscreenEnabled||document.webkitEnterFullscreen,getIsFullscreen=()=>!!document.fullscreenElement||!!document.webkitFullscreenElement,requestFullscreen=t=>{getIsFullscreen()||(t.requestFullscreen?t.requestFullscreen():t.webkitRequestFullscreen?t.webkitRequestFullscreen():t.webkitEnterFullscreen&&t.webkitEnterFullscreen())},exitFullscreen$1=()=>{getIsFullscreen()&&(document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen())},isIframe=t=>t!==null&&t.tagName==="IFRAME",log$L=logger$1("metrics"),sentGaEvents={},initialData={acquiring_type:null,action:null,banner_id:null,button_text:null,category:null,category_filtering:null,channel_name:null,collection_name:null,content_category:null,control_type:null,error_text:null,fullscreen:null,genre_filtering:null,link_text:null,offer_category:null,offer_category_id:null,offer_id:null,offer_location:null,offer_title:null,offers_count:null,page_path:null,player_type:null,profile:null,provider_id:null,query:null,
4season_num:null,sorting:null,strip_name:null,title_id:null,trial_available:null,user_id:null,vod_name:null},gaEvent=(t,e)=>{if(typeof window>"u"||!(t!=null&&t.action))return;const s=location.pathname;if(userIdSelector(e)&&(t.user_id=userIdSelector(e)),providerIdSelector(e)&&(t.provider_id=providerIdSelector(e)),window.location.hostname==="localhost")return log$L.info("log instead of sending to GA",{...t,event:"event-to-ga",page_path:s});const n={acquiring_type:null,action:null,banner_id:null,button_text:null,category:null,category_filtering:null,channel_name:null,collection_name:null,content_category:null,control_type:null,error_text:null,fullscreen:null,genre_filtering:null,link_text:null,offer_category:null,offer_category_id:null,offer_id:null,offer_location:null,offer_title:null,offers_count:null,page_path:null,player_type:null,profile:null,provider_id:null,query:null,season_num:null,sorting:null,strip_name:null,title_id:null,trial_available:null,user_id:null,vod_name:null,...t,event:"event-to-ga",page_path:s},i=document.getElementById("iframe-with-external-js");isIframe(i)&&i.contentWindow&&i.contentWindow.postMessage(JSON.stringify({type:"gtm-data-layer-push",dataLayerItem:n}),"*");const r={...initialData,...t,page_path:s},o=t.category||"unknown";typeof window.gtag=="function"&&window.gtag("event",o,r)},gaEventOnce=(t,e)=>{const s=JSON.stringify(t);sentGaEvents[s]||(gaEvent(t,e),sentGaEvents[s]=!0)},yaMetrikaGoal=t=>{var s;const e=`yaCounter${window.ymCounter}`;try{(s=window[e])==null||s.reachGoal(t)}catch(n){log$L.info("metrika","instead of sending to Yandex.Metrika",n)}},KIBIBYTE=1024;function bytesToBits(t){return t*8}const bytesToKiloBytes=t=>(t/KIBIBYTE).toFixed(2)+" KB";function msToS(t){return t/1e3}function bitsPerSToMbitPerS(t){return t/1e6}function formatToFixed2(t){return t.toFixed(2)}const isOkNumber=t=>typeof t=="number"&&!isNaN(t),checkNumberWithDefault=(t,e)=>isOkNumber(t)?t:e,boundMinMax=(t,e,s)=>e<t?t:e>s?s:e,setModalParams=(t,e)=>{t.modals.params=e},setModalScrollPosition=(t,e)=>{t.modals.scrollPosition=e},resetModalScrollPosition=t=>{t.modals.scrollPosition=0},setModalTitle=(t,e)=>{t.modals.title=e},resetModalTitle=t=>{t.modals.title=""},showModal=(t,e)=>{var s;modalsVisibilitySelector(t)[e]||(t.returnMetaTitle=((s=document.querySelector("title"))==null?void 0:s.innerText)||"",t.modals.visibility[e]=!0)},hideModal=(t,e)=>{t.modals.visibility[e]=!1,resetModalTitle(t)},hideAllModals=t=>{Object.keys(modalsVisibilitySelector(t)).forEach(e=>{t.modals.visibility[e]=!1}),resetModalTitle(t)},showAdultOnboarding=t=>{showModal(t,MODALS.adultOnboarding)},hideAdultOnboarding=t=>{hideModal(t,MODALS.adultOnboarding)},showByRoute=t=>{t.modals.visibility.byRoute=!0},hideByRoute=t=>{t.modals.visibility.byRoute=!1},showDvrError=t=>{t.modals.visibility.dvrError=!0},hideDvrError=t=>{t.modals.visibility.dvrError=!1},showDvrWarning=t=>{t.modals.visibility.dvrWarning=!0},hideDvrWarning=t=>{t.modals.visibility.dvrWarning=!1},showFeSettings=t=>{t.modals.visibility.feSettings=!0},hideFeSettings=t=>{t.modals.visibility.feSettings=!1},showMobileApps=t=>{t.modals.visibility.mobileApps=!0},hideMobileApps=t=>{t.modals.visibility.mobileApps=!1},showOfferDetails=t=>{t.modals.visibility.offerDetails=!0},hideOfferDetails=t=>{t.modals.visibility.offerDetails=!1},showOfferGift=t=>{t.modals.visibility.offerGift=!0},hideOfferGift=t=>{t.modals.visibility.offerGift=!1},showOfferExitConfirmation=t=>{t.modals.visibility.offerExitConfirmation=!0},hideOfferExitConfirmation=t=>{t.modals.visibility.offerExitConfirmation=!1},showPersonalData=t=>{t.modals.visibility.personalData=!0},hidePersonalData=t=>{t.modals.visibility.personalData=!1},showPhoneVerification=t=>{showModal(t,MODALS.phoneVerification)},hidePhoneVerification=t=>{hideModal(t,MODALS.phoneVerification)},showPlayerHelp=t=>{var e;gaEvent({category:"player_controls",action:"Открытие туториала",channel_name:(e=playingChannelSelector(t))==null?void 0:e.name},t),t.modals.visibility.playerHelp=!0},hidePlayerHelp=(t,e)=>{var n;const s={category:"player_controls",action:"Закрытие туториала",channel_name:(n=playingChannelSelector(t))==null?void 0:n.name};e&&(s.control_type=e),gaEvent(s,t),t.modals.visibility.playerHelp=!1},showPopupNoticeModal=t=>{t.modals.visibility.popupNotice=!0},hidePopupNoticeModal=t=>{t.modals.visibility.popupNotice=!1},showProfileAction=t=>{t.modals.visibility.profileAction=!0}
4,hideProfileAction=t=>{t.modals.visibility.profileAction=!1},showProfileProtected=t=>{t.modals.visibility.profileProtected=!0},hideProfileProtected=t=>{t.modals.visibility.profileProtected=!1},showQs=t=>{t.modals.visibility.qs=!0},hideQs=t=>{t.modals.visibility.qs=!1},showQsQr=t=>{t.modals.visibility.qsQr=!0},showSkipPromoOffers=t=>{t.modals.visibility.skipPromoOffers=!0},hideSkipPromoOffers=t=>{t.modals.visibility.skipPromoOffers=!1},showSubscriptionConfirmation=t=>{t.modals.visibility.subscriptionConfirmation=!0},hideSubscriptionConfirmation=t=>{t.modals.visibility.subscriptionConfirmation=!1},showSubscriptionShop=t=>{showModal(t,MODALS.subscriptionShop)},hideSubscriptionShop=t=>{hideModal(t,MODALS.subscriptionShop)},showSubscriptionV2=t=>{t.modals.visibility.subscriptionV2=!0},hideSubscriptionV2=t=>{t.modals.visibility.subscriptionV2=!1},showTrialGift=t=>{showModal(t,MODALS.trialGift)},hideTrialGift=t=>{hideModal(t,MODALS.trialGift)},showUnsubscriptionRetentionOfferDetails=t=>{t.modals.visibility.unsubscriptionRetentionOfferDetails=!0},hideUnsubscriptionRetentionOfferDetails=t=>{t.modals.visibility.unsubscriptionRetentionOfferDetails=!1},showVerificationSubscription=t=>{showModal(t,MODALS.verificationSubscription)},hideVerificationSubscription=t=>{hideModal(t,MODALS.verificationSubscription)},showWelcomeScreen=t=>{var e,s;(s=(e=t.siteConfig)==null?void 0:e.welcomeScreen)!=null&&s.enabled&&(t.modals.visibility.welcomeScreen=!0)},hideWelcomeScreen=t=>{t.modals.visibility.welcomeScreen=!1},modals=Object.freeze(Object.defineProperty({__proto__:null,hideAdultOnboarding,hideAllModals,hideByRoute,hideDvrError,hideDvrWarning,hideFeSettings,hideMobileApps,hideModal,hideOfferDetails,hideOfferExitConfirmation,hideOfferGift,hidePersonalData,hidePhoneVerification,hidePlayerHelp,hidePopupNoticeModal,hideProfileAction,hideProfileProtected,hideQs,hideSkipPromoOffers,hideSubscriptionConfirmation,hideSubscriptionShop,hideSubscriptionV2,hideTrialGift,hideUnsubscriptionRetentionOfferDetails,hideVerificationSubscription,hideWelcomeScreen,resetModalScrollPosition,setModalParams,setModalScrollPosition,setModalTitle,showAdultOnboarding,showByRoute,showDvrError,showDvrWarning,showFeSettings,showMobileApps,showModal,showOfferDetails,showOfferExitConfirmation,showOfferGift,showPersonalData,showPhoneVerification,showPlayerHelp,showPopupNoticeModal,showProfileAction,showProfileProtected,showQs,showQsQr,showSkipPromoOffers,showSubscriptionConfirmation,showSubscriptionShop,showSubscriptionV2,showTrialGift,showUnsubscriptionRetentionOfferDetails,showVerificationSubscription,showWelcomeScreen},Symbol.toStringTag,{value:"Module"})),addNotificationToStack=(t,e,s,n,i=!1,r=NOTIFICATION_SIMPLE_HIDE_TIMEOUT_5S,o)=>{s==="loginSuccess"&&localStore.set("showLoginSuccessNotification",!0);const a=i?setTimeout(()=>{t.notifications.simple.shift(),s==="loginSuccess"&&localStore.set("showLoginSuccessNotification",!1)},r):null;if(t.notifications.simple.length>=3){const l=t.notifications.simple[0];l.timeout&&clearTimeout(l.timeout),t.notifications.simple.shift()}t.notifications.simple.push({text:e,icon:n,type:s,timeout:a,iconColorClass:o})},showErrorNotification=(t,e)=>{addNotificationToStack(t,e,"error","error-circle")},hideErrorNotification=t=>{const e=t.notifications.simple.findIndex(s=>s.type==="error");t.notifications.simple.splice(e,1)},showDiagnosticsStatusNotification=(t,e,s)=>{addNotificationToStack(t,s,"diagnosticsStatus",e?"error-circle":"done-circle")},hideDiagnosticsStatusNotification=t=>{const e=t.notifications.simple.findIndex(s=>s.type==="diagnosticsStatus");t.notifications.simple.splice(e,1)},showFavoriteNotification=async(t,e="tv",s=!0,n)=>{const i=e==="tv",r=i?"channel":"title",o=i?/%channelName%/g:/%titleName%/g;let a,l="favorite-on";s?a=`${r}_added_to_fav`:(a=`${r}_removed_from_fav`,l="favorite-off");const c=`<span>${translationSelector(t,a).replace(o,`«${n}»`)}</span>`;addNotificationToStack(t,c,"favorite",l,!0)},showLoginSuccessNotification=t=>{const e=translationSelector(t,"you_are_logged_in")||"";addNotificationToStack(t,e,"loginSuccess","done-circle",!0,NOTIFICATION_SIMPLE_HIDE_TIMEOUT_10S)},showPauseRemovedNotification=(t,e)=>{const n=`<span>${translationSelector(t,"title_deleted_from_watch_history").replace(/%titleName%/g,`«${e}»`)}</span>`;addNotificationToStack(t,n,"pauseRemoved","delete",!0)},showProfileNotification=(t,e,s="done-circle")=>{addNotificationToStack(t,e,"profile",s,!0)},showQsNotification=(t,e)=>{addNotificationToStack(t,e,"qs",void 0,!0,NOTIFICATION_SIMPLE_HIDE_TIMEOUT_10S)},showAutoRenewNotification=(t,e,s)=>{addNotificationToStack(t,e,"autoRenew","renew",!0,NOTIFICATION_SIMPLE_HIDE_TIMEOUT_10S,s==="enable"?COLOR_CLASS.success:COLOR_CLASS.error)},hideAllComplexNotifications=t=>{const e=notificationsSelector(t).complex;Object.keys(e).forEach(s=>{e[s].isVisible=!1})},addNotificationToQueueByName=(t,e)=>{queueSelector(t).indexOf(e)===-1&&queueSelector(t).push(e)},removeNotificationFromQueueByName=(t,e)=>{const s=queueSelector(t),n=s.indexOf(e);n>-1&&s.splice(n,1)},showAdultOnboardingNotification=(t,e,s,n)=>{t.notifications.complex.adultOnboarding.isVisible=!0,t.notifications.complex.adultOnboarding.title=e,t.notifications.complex.adultOnboarding.message=s,t.notifications.complex.adultOnboarding.withButton=n,addNotificationToQueueByName(t,"adultOnboarding")},hideAdultOnboardingNotification=t=>{t.notifications.complex.adultOnboarding.isVisible=!1,t.notifications.complex.adultOnboarding.title="",t.notifications.complex.adultOnboarding.message="",t.notifications.complex.adultOnboarding.withButton=!1,removeNotificationFromQueueByName(t,"adultOnboarding")},showAuthAndRegNotification=(t,e="")=>{hideAuthAndRegNotification(t),setTimeout(()=>{t.notifications.complex.authAndReg.isVisible=!0,t.notifications.complex.authAndReg.returnUrl=e,addNotificationToQueueByName(t,"authAndReg")},0)},hideAuthAndRegNotification=(t,e=!0)=>{t.notifications.complex.authAndReg.isVisible=!1,e&&(t.notifications.complex.authAndReg.returnUrl=""),removeNotificationFromQueueByName(t,"authAndReg")},showAutologinMegafonNotification=t=>{t.notifications.complex.autologinMegafon.isVisible=!0,addNotificationToQueueByName(t,"autologinMegafon")},hideAutologinMegafonNotification=t=>{t.notifications.complex.autologinMegafon.isVisible=!1,removeNotificationFromQueueByName(t,"autologinMegafon")},showDvrRestrictionNotification=t=>{t.notifications.complex.dvrRestriction.isVisible=!0,addNotificationToQueueByName(t,"dvrRestriction")},hideDvrRestrictionNotification=t=>{t.notifications.complex.dvrRestriction.isVisible=!1,removeNotificationFromQueueByName(t,"dvrRestriction")},showDvrRestrictionWithButtonVisibleSelector=t=>{t.notifications.complex.dvrRestrictionWithButton.isVisible=!0,addNotificationToQueueByName(t,"dvrRestrictionWithButton")},hideDvrRestrictionWithButtonVisibleSelector=t=>{t.notifications.complex.dvrRestrictionWithButton.isVisible=!1,removeNotificationFromQueueByName(t,"dvrRestrictionWithButton")},showPlayerErrorNotification=t=>{t.notifications.complex.playerError.isVisible=!0,addNotificationToQueueByName(t,"playerError")},hidePlayerErrorNotification=t=>{t.notifications.complex.playerError.isVisible=!1,removeNotificationFromQueueByName(t,"playerError")},showProviderInfoNotification=t=>{t.notifications.complex.providerContactInfo.isVisible=!0,addNotificationToQueueByName(t,"providerContactInfo")},hideProviderInfoNotification=t=>{t.notifications.complex.providerContactInfo.isVisible=!1,removeNotificationFromQueueByName(t,"providerContactInfo")},showPaymentErrorRetry=t=>{t.notifications.complex.retry.isVisible=!0,addNotificationToQueueByName(t,"retry")},hidePaymentErrorRetry=t=>{t.notifications.complex.retry.isVisible=!1,removeNotificationFromQueueByName(t,"retry")},showReviewNotification=t=>{t.notifications.complex.review.isVisible=!0,addNotificationToQueueByName(t,"review")},hideReviewNotification=t=>{t.notifications.complex.review.isVisible=!1,removeNotificationFromQueueByName(t,"review")},showSubscriptionPaymentErrorNotification=t=>{t.notifications.complex.subscriptionPaymentError.isVisible=!0,addNotificationToQueueByName(t,"subscriptionPaymentError")},hideSubscriptionPaymentErrorNotification=t=>{t.notifications.complex.subscriptionPaymentError.isVisible=!1,removeNotificationFromQueueByName(t,"subscriptionPaymentError")},showSubscriptionProlongationErrorNotification=(t,e)=>{t.notifications.complex.subscriptionProlongationError.message=e,t.notifications.complex.subscriptionProlongationError.isVisible=!0,addNotificationToQueueByName(t,"subscriptionProlongationError")},hideSubscriptionProlongationErrorNotification=t=>{t.notifications.complex.subscriptionProlongationError.message="",t.notifications.complex.subscriptionProlongationError.isVisible=!1,removeNotificationFromQueueByName(t,"subscriptionProlongationError")},showUnavailableContentNotification=(t,e,s,n,i)=>{hideUnavailableContentNotification(t),setTimeout(()=>{hideReviewNotification(t),t.notifications.complex.unavailableContent.isVisible=!0,t.notifications.complex.unavailableContent.image=i,t.notifications.complex.unavailableContent.sourceId=e,t.notifications.complex.unavailableContent.titleId=s,t.notifications.complex.unavailableContent.titleText=n,addNotificationToQueueByName(t,"unavailableContent")},0)},hideUnavailableContentNotification=t=>{t.notifications.complex.unavailableContent.isVisible=!1,t.notifications.complex.unavailableContent.sourceId="",t.notifications.complex.unavailableContent.titleId="",t.notifications.complex.unavailableContent.titleText="",t.notifications.complex.unavailableContent.image=null,removeNotificationFromQueueByName(t,"unavailableContent")},notifications=Object.freeze(Object.defineProperty({__proto__:null,addNotificationToQueueByName,addNotificationToStack,hideAdultOnboardingNotification,hideAllComplexNotifications,hideAuthAndRegNotification,hideAutologinMegafonNotification,hideDiagnosticsStatusNotification,hideDvrRestrictionNotification,hideDvrRestrictionWithButtonVisibleSelector,hideErrorNotification,hidePaymentErrorRetry,hidePlayerErrorNotification,hideProviderInfoNotification,hideReviewNotification,hideSubscriptionPaymentErrorNotification,hideSubscriptionProlongationErrorNotification,hideUnavailableContentNotification,removeNotificationFromQueueByName,showAdultOnboardingNotification,showAuthAndRegNotification,showAutoRenewNotification,showAutologinMegafonNotification,showDiagnosticsStatusNotification,showDvrRestrictionNotification,showDvrRestrictionWithButtonVisibleSelector,showErrorNotification,show
4FavoriteNotification,showLoginSuccessNotification,showPauseRemovedNotification,showPaymentErrorRetry,showPlayerErrorNotification,showProfileNotification,showProviderInfoNotification,showQsNotification,showReviewNotification,showSubscriptionPaymentErrorNotification,showSubscriptionProlongationErrorNotification,showUnavailableContentNotification},Symbol.toStringTag,{value:"Module"})),log$K=logger$1("player"),setPlayerType=(t,e="")=>{t.player.type=e},startLoading$1=t=>{t.player.loading||(log$K.info("startLoading"),t.player.loading=!0)},stopLoading$1=t=>{t.player.loading&&(log$K.info("stopLoading"),t.player.loading=!1)},setReady=(t,e)=>{log$K.info("setReady",e),t.player.ready=e},setLoaded=(t,e)=>{e!==t.player.loaded&&(log$K.info("setLoaded",e),t.player.loaded=e)},minimizePlayer=t=>{t.player.minimized=!0},expandPlayer=t=>{t.player.minimized=!1},showPlayer=t=>{t.player.visible=!0},hidePlayer=t=>{t.player.visible=!1},lockScroll=t=>{t.player.isScrollLocked=!0},unlockScroll=t=>{t.player.isScrollLocked=!1},reset$1=t=>{clearError(t),stopLoading$1(t),setLoaded(t,!1),setIsPlaying(t,!1),setHasSubtitles(t,!1),setOverlayVisibility(t,!1),setReady(t,!1),releaseOverlay(t),hidePlayer(t),resetVideoData(t)},resetVideoData=t=>{t.player.playbackSessionContext=void 0,setPlayingTime(t,0),setDuration(t,0),resetPlayingData(t),resetPlaybackInfo(t),t.player.playbackMethod=""},setIsPrerollVisible=(t,e)=>{t.player.isPrerollVisible=e},exitFullscreenOnAndroid=(t,e,s)=>{if(typeof window>"u"||typeof document>"u"){log$K.error("exitFullscreenOnAndroid is to be used on client-side only");return}const n=getUserAgent();window.innerHeight<window.innerWidth&&getDeviceFlags(n).isAndroid&&s&&exitFullscreen(t)},setError=(t,e,s="",n,i={})=>{var r;log$K.error("setError",e,s,n),stopLoading$1(t),t.player.error={code:e,message:s,options:i,status:n},isMinimizedSelector(t)||((r=document.documentElement)==null?void 0:r.clientWidth)<=MOBILE_WINDOW_WIDTH_MAX?showPlayerErrorNotification(t):lockScroll(t),isFullscreenSelector(t)&&exitFullscreen(t)},clearError=t=>{t.player.error!==null&&(log$K.info("clearError"),t.player.error=null)},setAlert=(t,e)=>{log$K.info("setAlert",e),t.player.alert=e},clearAlert=t=>{t.player.alert=""},showEpgInfo=t=>{t.player.isEpgVisible=!0},hideEpgInfo=t=>{t.player.isEpgVisible=!1,releaseOverlay(t)},toggleEpgInfo=t=>{t.player.isEpgVisible?hideEpgInfo(t):showEpgInfo(t)},showFullscreenMenu=t=>{hideDvrWarning(t),t.player.isFullscreenMenuVisible=!0},hideFullscreenMenu=t=>{t.player.isFullscreenMenuVisible=!1},showSettingsMenu=t=>{t.player.isSettingsMenuVisible=!0},hideSettingsMenu=t=>{t.player.isSettingsMenuVisible=!1},setOverlayVisibility=(t,e)=>{e!==t.player.overlay.visible&&(log$K.info(`${e?"show":"hide"} overlay`),t.player.overlay.visible=e)},freezeOverlay=t=>{t.player.overlay.frozen=!0},releaseOverlay=t=>{t.player.overlay.frozen=!1},doShowOverlay=t=>{if(t.player.overlay.hideTimeoutId&&(clearTimeout(t.player.overlay.hideTimeoutId),t.player.overlay.hideTimeoutId=null),overlayVisibleSelector(t)||setOverlayVisibility(t,!0),t.player.video.isPlaying&&t.player.loading){setTimeout(()=>showOverlay(t),1e3);return}!isRewindingSelector(t)&&!isFastForwardingSelector(t)&&(t.player.overlay.hideTimeoutId=setTimeout(()=>hideOverlay(t),THRESHOLDS.tv.hideOverlayAfterMilliseconds))},showOverlay=throttle(doShowOverlay,TV_PLAYER_HIDE_OVERLAY_TIMEOUT),hideOverlay=t=>{if(!isOverlayFrozenSelector(t)){if(t.player.alert){t.player.overlay.hideTimeoutId=setTimeout(()=>{setOverlayVisibility(t,!1)},HIDE_PLAYER_ALERT_DELAY);return}setOverlayVisibility(t,!1),t.player.touchedTimes=0}},updatePlayingTime=(t,e)=>{let s=e;if(isTvSelector(t)){const n=serverTimeSelector(t),i=playingChannelSelector(t),r=i?dvrLeftBoundSelector(t,i):0;s=n?boundMinMax(r,e,n):0,(isDvrDisabled(i)||isDvrRestricted(i))&&(s=n),n===s&&setIsLive(t,!0)}setPlayingTime(t,s)},setHasSubtitles=(t,e)=>{t.player.video.hasSubtitles=e},toggleFullscreen=t=>{t.player.video.isFullscreen=!t.player.video.isFullscreen},goFullscreen=t=>{t.player.video.isFullscreen=!0},exitFullscreen=t=>{exitFullscreen$1(),hideFullscreenMenu(t),t.player.video.isFullscreen=!1},resetPoster=t=>{log$K.info("resetPoster"),t.player.video.poster=""},setPoster=(t,e)=>{log$K.info("setPoster",e),t.player.video.poster=e},setWasPlayingBeforeOffline=(t,e)=>t.player.video.wasPlayingBeforeOffline=e,setIsPlaying=(t,e)=>{e!==t.player.video.isPlaying&&(log$K.info("setIsPlaying",e),t.player.video.isPlaying=e)},setDuration=(t,e)=>{t.player.video.duration=e},setPlayingTime=(t,e)=>{t.player.video.playingTime=e},clearHideVolumeSliderTimeout=t=>{t.player.volumeSlider.hideTimeoutId&&clearTimeout(t.player.volumeSlider.hideTimeoutId)},showVolumeSlider=t=>{clearHideVolumeSliderTimeout(t),t.player.volumeSlider.visible=!0},hideVolumeSlider=t=>{clearHideVolumeSliderTimeout(t),t.player.volumeSlider.hideTimeoutId=setTimeout(()=>t.player.volumeSlider.visible=!1,1e3)},changeVolume=(t,e)=>{const s=e>1?1:e<0?0:e;t.player.video.volume!==s&&(log$K.info("changeVolume",t.player.video.volume,"->",s),t.player.video.volume=s)},resetMute=t=>{storage.get(STORE_KEYS.player.mute)&&toggleMute(t)},volumeUp=t=>{log$K.info("volumeUp"),showOverlay(t),resetMute(t),t.player.video.volume<.96&&(t.player.video.volume=Math.min(1,t.player.video.volume+.05)),storage.set(STORE_KEYS.player.volume,t.player.video.volume)},volumeDown=t=>{log$K.info("volumeDown"),showOverlay(t),resetMute(t),t.player.video.volume>.05?t.player.video.volume=Math.max(0,t.player.video.volume-.05):t.player.video.volume<=.05&&(t.player.video.volume=0,toggleMute(t)),storage.set(STORE_KEYS.player.volume,t.player.video.volume)},changeMute=(t,e)=>{t.player.video.muted=e,storage.set(STORE_KEYS.player.mute,e)},toggleMute=t=>{log$K.info("toggleMute"),t.player.video.muted=!t.player.video.muted,storage.set(STORE_KEYS.player.mute,t.player.video.muted),gaEvent({category:"player_controls",action:`${t.player.video.muted?"Выключить":"Включить"} звук`},t)},mute=t=>{log$K.info("mute"),t.player.video.muted=!0}
4,unmute=t=>{log$K.info("unmute"),t.player.video.muted=!1},resetPlayingData=t=>{setPlayingSourceId(t,""),setPlayingChannelId(t,""),setPlayingTitleId(t,""),setPlayingEpisodeId(t,""),setPlayingMediaItemId(t,"")},setPlayingChannelId=(t,e)=>{t.player.playing.channelId=e},setPlayingSourceId=(t,e)=>{t.player.playing.sourceId=e},setPlayingTitleId=(t,e)=>{t.player.playing.titleId=e},setPlayingEpisodeId=(t,e)=>{t.player.playing.episodeId=e},setPlayingMediaItemId=(t,e)=>{t.player.playing.mediaItemId=e},resetPlaybackInfo=t=>{setPlaybackInfoAmedia(t,void 0),setPlaybackInfoIvi(t,void 0),setPlaybackInfoMegogo(t,void 0),setPlaybackInfoSmotreshka(t,void 0),setPlaybackInfoSmotreshkaVodV2(t,void 0)},setPlaybackInfoAmedia=(t,e)=>{t.player.playbackInfo.amedia2V1=e},setPlaybackInfoIvi=(t,e)=>{t.player.playbackInfo.ivi=e},setPlaybackInfoMegogo=(t,e)=>{t.player.playbackInfo.megogoV1=e},setPlaybackInfoSmotreshka=(t,e)=>{t.player.playbackInfo.smotreshkaPlaybackInfo=e},setPlaybackInfoSmotreshkaVodV2=(t,e)=>{t.player.playbackInfo.smotreshkaVodV2=e},setDvrWarningOverlayData=(t,e,s)=>{t.player.dvrWarningOverlay.channelId=e,t.player.dvrWarningOverlay.message=s,showDvrWarning(t)},setTimelineBalloonFollowingMouse=(t,e)=>{t.player.timeline.isBalloonFollowingMouse=e},setIsLive=(t,e)=>{t.player.isLive=e},player=Object.freeze(Object.defineProperty({__proto__:null,changeMute,changeVolume,clearAlert,clearError,exitFullscreen,exitFullscreenOnAndroid,expandPlayer,freezeOverlay,goFullscreen,hideEpgInfo,hideFullscreenMenu,hideOverlay,hidePlayer,hideSettingsMenu,hideVolumeSlider,lockScroll,minimizePlayer,mute,releaseOverlay,reset:reset$1,resetPlaybackInfo,resetPlayingData,resetPoster,resetVideoData,setAlert,setDuration,setDvrWarningOverlayData,setError,setHasSubtitles,setIsLive,setIsPlaying,setIsPrerollVisible,setLoaded,setOverlayVisibility,setPlaybackInfoAmedia,setPlaybackInfoIvi,setPlaybackInfoMegogo,setPlaybackInfoSmotreshka,setPlaybackInfoSmotreshkaVodV2,setPlayerType,setPlayingChannelId,setPlayingEpisodeId,setPlayingMediaItemId,setPlayingSourceId,setPlayingTime,setPlayingTitleId,setPoster,setReady,setTimelineBalloonFollowingMouse,setWasPlayingBeforeOffline,showEpgInfo,showFullscreenMenu,showOverlay,showPlayer,showSettingsMenu,showVolumeSlider,startLoading:startLoading$1,stopLoading:stopLoading$1,toggleEpgInfo,toggleFullscreen,toggleMute,unlockScroll,unmute,updatePlayingTime,volumeDown,volumeUp},Symbol.toStringTag,{value:"Module"})),dvrRestrictionMessageSelector=t=>{var e,s;return((s=(e=playbackInfoSmotreshkaSelector(t))==null?void 0:e.dvrAvailability)==null?void 0:s.msg)||""},isInFavoritesSelector=t=>{const e=playingChannelIdSelector(t);return e?!!favoritesSelector$1(t)[e]:!1},thumbnailsServerSelector=t=>{var s;const e=((s=playbackInfoSmotreshkaSelector(t))==null?void 0:s.thumbnailServerUrl)||"";return e&&matchUrlProtocolWithLocationProtocol(e,t.common.isHttps)},prevChannelIdSelector=t=>{var i;const e=playingChannelIdSelector(t),s=Object.values(filteredChannelsSelector(t)),n=s.findIndex(r=>
4r.id===e);return((i=s[n-1])==null?void 0:i.id)||""},nextChannelIdSelector=t=>{var i;const e=playingChannelIdSelector(t),s=Object.values(filteredChannelsSelector(t)),n=s.findIndex(r=>r.id===e);return((i=s[n+1])==null?void 0:i.id)||""},availableLanguagesSelector=t=>languagesSelector(t).filter(({unavailable:e})=>e!==!0),anyAvailableLanguageIndexSelector=t=>languagesSelector(t).findIndex(({unavailable:e})=>e!==!0),isLanguageAvailableSelector=(t,e)=>{var s;return((s=languagesSelector(t)[e])==null?void 0:s.unavailable)!==!0},languagesSelector=t=>{var e;return((e=playbackInfoSmotreshkaSelector(t))==null?void 0:e.languages)||[]},languageIndexSelector=t=>{const e=playbackInfoSmotreshkaSelector(t),s=defaultLanguageIndexSelector(t);return e&&Number.isInteger(e.languageIndex)?e.languageIndex:s},languageSelector=t=>{const e=languagesSelector(t),s=languageIndexSelector(t);return e[s]},defaultLanguageIndexSelector=t=>{const s=languagesSelector(t).findIndex(n=>n.default);return Math.max(s,0)},renditionsSelector=t=>{var e;return((e=languageSelector(t))==null?void 0:e.renditions)||[]},renditionIndexSelector=t=>{const e=playbackInfoSmotreshkaSelector(t),s=defaultRenditionIndexSelector(t);return e&&Number.isInteger(e.renditionIndex)?e.renditionIndex:s},renditionSelector=t=>{const e=renditionsSelector(t),s=renditionIndexSelector(t);return e[s]},defaultRenditionIndexSelector=t=>{const s=renditionsSelector(t).findIndex(n=>n.default);return Math.max(s,0)},hasVitrinaSelector=t=>{const e=playingChannelIdSelector(t)||"",s=channelVitrinaSelector(t,e);return!!s&&!!(s!=null&&s.iframeUrl)},vitrinaSelector=t=>{const e=playingChannelIdSelector(t)||"";return channelVitrinaSelector(t,e)},vitrinaUrlSelector=t=>{var e;return(e=vitrinaSelector(t))==null?void 0:e.iframeUrl},playerPlayingChannel$1=Object.freeze(Object.defineProperty({__proto__:null,anyAvailableLanguageIndexSelector,availableLanguagesSelector,defaultLanguageIndexSelector,defaultRenditionIndexSelector,dvrRestrictionMessageSelector,hasVitrinaSelector,isInFavoritesSelector,isLanguageAvailableSelector,languageIndexSelector,languageSelector,languagesSelector,nextChannelIdSelector,prevChannelIdSelector,renditionIndexSelector,renditionSelector,renditionsSelector,thumbnailsServerSelector,vitrinaSelector,vitrinaUrlSelector},Symbol.toStringTag,{value:"Module"})),initialState$p={title:"",meta:[],breadcrumbs:[],breadcrumbTelevisionChannel:null,breadcrumbProduct:null},LOCALE={ru:"ru_Ru"},reset=t=>{t.seo=initialState$p},setMetaTitle=(t,e="")=>{t.seo.title=e||translationSelector(t,"default_meta_title")||"",typeof document<"u"&&(document.title=e)},setMeta=(t,e)=>{t.seo.meta=e},addMeta=(t,e)=>t.seo.meta.push(e),addBreadcrumbs=(t,e)=>t.seo.breadcrumbs=e,addBreadcrumbTelevisionChannel=(t,e)=>t.seo.breadcrumbTelevisionChannel=e,addBreadcrumbProduct=(t,e)=>t.seo.breadcrumbProduct=e,initMeta=(t,{title:e,meta:s})=>{var a;const{languageCode:n}=t;e&&setMetaTitle(t,e),s.find(l=>l.name==="description")||s.push({name:"description",content:translationSelector(t,(a=t.siteConfig)==null?void 0:a.common.description)});const r=[{name:"og:type",content:"website"},{name:"og:site_name",content:getByLanguage(t.translations.smotreshka,n,t.defaultLanguageCode)||""},{name:"og:locale",content:LOCALE[n]},{name:"twitter:card",content:"summary_large_image"}],o=s.find(l=>l.property==="og:image");o&&s.push({property:"twitter:image",content:o.content}),setMeta(t,[...s,...r])},seo$1=Object.freeze(Object.defineProperty({__proto__:null,addBreadcrumbProduct,addBreadcrumbTelevisionChannel,addBreadcrumbs,addMeta,initMeta,reset,setMeta,setMetaTitle},Symbol.toStringTag,{value:"Module"})),globalSearchUsefulLinksSelector=t=>{var e,s;return((s=(e=t.siteConfig)==null?void 0:e.globalSearch)==null?void 0:s.usefulLinks)||[]},globalSearchPopularQueriesSelector=t=>{var e,s;return((s=(e=t.siteConfig)==null?void 0:e.globalSearch)==null?void 0:s.popularQueries)||[]},popupNoticesDisplayInCenterSelector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.popupNotices)==null?void 0:s.displayInCenter},popupNoticesIntervalSelector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.popupNotices)==null?void 0:s.interval},popupNoticesEnabledSelector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.popupNotices)==null?void 0:s.enabled},isCropSupportedSelector=t=>{var s,n;const e=(n=(s=t.siteConfig)==null?void 0:s.imageServer)==null?void 0:n.isCropSupported;return e||typeof e>"u"},myPageEnabledSelector=t=>{var s,n;const e=(n=(s=t.siteConfig)==null?void 0:s.myPage)==null?void 0:n.enabled;return e||typeof e>"u"},hasVodHomeCollectionsV3Selector=t=>{var s,n;const e=(n=(s=t.siteConfig)==null?void 0:s.vodCollections)==null?void 0:n.hasVodHomeCollectionsV3;return e||typeof e>"u"},searchPlacementBlocksSelector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.globalSearch)==null?void 0:s.placementBlocks},subscriptionShopEnabledSelector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.subscriptionShop)==null?void 0:s.enabled},hasTokensV2Selector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.tokens)==null?void 0:s.hasTokensV2},isEvictedSessionEnabled=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.evictedSession)==null?void 0:s.enabled}
4,isClientAnalyticsEnabled=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.clientAnalytics)==null?void 0:s.enabled},siteConfig=Object.freeze(Object.defineProperty({__proto__:null,globalSearchPopularQueriesSelector,globalSearchUsefulLinksSelector,hasTokensV2Selector,hasVodHomeCollectionsV3Selector,isClientAnalyticsEnabled,isCropSupportedSelector,isEvictedSessionEnabled,myPageEnabledSelector,popupNoticesDisplayInCenterSelector,popupNoticesEnabledSelector,popupNoticesIntervalSelector,searchPlacementBlocksSelector,subscriptionShopEnabledSelector},Symbol.toStringTag,{value:"Module"})),analyticsTokenV1Selector=t=>t.tokensV1.analyticsToken,audienceTokenV1Selector=t=>t.tokensV1.audienceToken,tvAssetTokenV1Selector=t=>t.tokensV1.tvAssetToken,expiresAtTokenV1Selector=t=>t.tokensV1.expiresAt,tokensV1$1=Object.freeze(Object.defineProperty({__proto__:null,analyticsTokenV1Selector,audienceTokenV1Selector,expiresAtTokenV1Selector,tvAssetTokenV1Selector},Symbol.toStringTag,{value:"Module"})),analyticsTokenSelector=t=>hasTokensV2Selector(t)?analyticsTokenV2Selector(t):analyticsTokenV1Selector(t),audienceTokenSelector=t=>hasTokensV2Selector(t)?audienceTokenV2Selector(t):audienceTokenV1Selector(t),tvAssetTokenSelector=t=>hasTokensV2Selector(t)?tvAssetTokenV2Selector(t):tvAssetTokenV1Selector(t),audienceTokenV2Selector=t=>{var e;return((e=t.tokensV2.assetTokens)==null?void 0:e.audienceToken)||""},tvAssetTokenV2Selector=t=>{var e;return((e=t.tokensV2.assetTokens)==null?void 0:e.tvAssetToken)||""},analyticsTokenV2Selector=t=>{var e;return((e=t.tokensV2.assetTokens)==null?void 0:e.analyticsToken)||""},searchAssetTokenV2Selector=t=>{var e;return((e=t.tokensV2.assetTokens)==null?void 0:e.searchAssetToken)||""},contextTokenSelector$1=t=>t.tokensV2.contextToken,regularUpdateSelector=t=>t.tokensV2.regularUpdate,etagSelector=t=>{var e;return(e=t.tokensV2.regularUpdate)==null?void 0:e.etag},intervalSecSelector=t=>{var e;return(e=t.tokensV2.regularUpdate)==null?void 0:e.intervalSec},loadedSelector=t=>t.tokensV2.loaded,loadingSelector$1=t=>t.tokensV2.loading,timeoutSelector=t=>t.tokensV2.timeout,tokensV2$1=Object.freeze(Object.defineProperty({__proto__:null,analyticsTokenSelector,analyticsTokenV2Selector,audienceTokenSelector,audienceTokenV2Selector,contextTokenSelector:contextTokenSelector$1,etagSelector,intervalSecSelector,loadedSelector,loadingSelector:loadingSelector$1,regularUpdateSelector,searchAssetTokenV2Selector,timeoutSelector,tvAssetTokenSelector,tvAssetTokenV2Selector},Symbol.toStringTag,{value:"Module"})),log$J=logger$1("tokens-v1-actions"),loadAssetTokensV1=async(t,e)=>{if(t.tokensV1.loaded)return log$J.info("Asset Tokens v1 were already loaded"),null;if(t.tokensV1.loading)return log$J.info("Asset Tokens v1 are already loading right now"),null;t.tokensV1.loading=!0;let s;try{s=await getAssetTokensV1(e),t.tokensV1.loaded=!0}catch{s=null,t.tokensV1.loaded=!1}finally{t.tokensV1.loading=!1}s!==null&&(Object.entries(s).forEach(([n,i])=>{["analyticsToken","audienceToken","tvAssetToken"].includes(n)&&s!==null&&cookieStore.set(COOKIE_NAMES[n],i,{expires:new Date(s.expiresAt)})}),t.tokensV1.analyticsToken=s.analyticsToken,t.tokensV1.audienceToken=s.audienceToken,t.tokensV1.tvAssetToken=s.tvAssetToken,t.tokensV1.expiresAt=s.expiresAt,log$J.info("Asset Tokens v1 were successfully loaded"))},tokensV1=Object.freeze(Object.defineProperty({__proto__:null,loadAssetTokensV1},Symbol.toStringTag,{value:"Module"})),urlSelector=t=>{var e;return((e=t.providerInfo)==null?void 0:e.url)||""},salesPhoneSelector=t=>{var e;return((e=t.providerInfo)==null?void 0:e.sales_phone)||null},supportEmailSelector=t=>{var e;return(e=t.providerInfo)==null?void 0:e.support_email},supportEmailV2Selector=t=>{var e;return(e=t.providerInfoV2)==null?void 0:e.supportInfo.supportEmail},supportURLSelector=t=>{var e;return(e=t.providerInfo)==null?void 0:e.support_url_short},supportURLV2Selector=t=>{var e;return(e=t.providerInfoV2)==null?void 0:e.supportInfo.supportUrl.originalValue},salesPhoneFormattedSelector=t=>{const e=salesPhoneSelector(t);return e&&(e.country_code||e.region_code||e.number)?`${e.country_code} (${e.region_code}) ${e.number}`:""},providerInfo$1=Object.freeze(Object.defineProperty({__proto__:null,salesPhoneFormattedSelector,salesPhoneSelector,supportEmailSelector,supportEmailV2Selector,supportURLSelector,supportURLV2Selector,urlSelector},Symbol.toStringTag,{value:"Module"})),loadProviderInfo=async(t,e)=>{var s,n,i,r,o,a;t.providerInfoV2=await fe.get(URLS.providerInfoV2,{languageCode:t.languageCode,ctx:e,params:{providerId:(i=(n=(s=t.account)==null?void 0:s.provider)==null?void 0:n.provider)==null?void 0:i.id}}).catch(()=>null),t.providerInfo||(t.providerInfo=await fe.get(URLS.providerInfo(((a=(o=(r=t.account)==null?void 0:r.provider)==null?void 0:o.provider)==null?void 0:a.id)||"default"),{ctx:e,languageCode:languageCodeSelector(t)}).catch(()=>null))},providerInfo=Object.freeze(Object.defineProperty({__proto__:null,loadProviderInfo},Symbol.toStringTag,{value:"Module"})),pausesVodLoadedSelector=t=>t.pauses.vod.loaded,pausesVodLoadingSelector=t=>t.pauses.vod.loading,pausesVodHasMorePausesToLoadSelector=t=>t.pauses.vod.hasMorePausesToLoad,pausesVodItemsSelector=t=>t.pauses.vod.items,pausesVodItemsFilteredSelector=t=>pausesVodItemsSelector(t).filter(e=>filterPausesVod(t,e)).map(e=>preparePauseVodWithPoster(t,e)),pauses$1=Object.freeze(Object.defineProperty({__proto__:null,pausesVodHasMorePausesToLoadSelector,pausesVodItemsFilteredSelector,pausesVodItemsSelector,pausesVodLoadedSelector,pausesVodLoadingSelector},Symbol.toStringTag,{value:"Module"})),initialState$o={tv:{items:[]},vod:{hasMorePausesToLoad:!1,loading:!1,loaded:!1,items:[]}},log$I=logger$1("pauses"),loadVodPauses=async(t,e,s=!1,n=DEFAULT_TILES_AMOUNT)=>{if(isAnonymousSelector(t))return;if(pausesVodLoadingSelector(t)){log$I.info("VOD Pauses are already loading...");return}const i=s?0:pausesVodItemsSelector(t).length;try{t.pauses.vod.loading=!0;const r=await getVodPauses({languageCode:t.languageCode,ctx:e,params:{limit:n,offset:i}});s&&(t.pauses.vod.items.length=0),t.pauses.vod.items=[...t.pauses.vod.items,...r],t.pauses.vod.hasMorePausesToLoad=r.length===n,t.pauses.vod.loaded=!0}catch(r){log$I.error(r)}finally{log$I.info("VOD pauses have been loaded, count:",t.pauses.vod.items.length),t.pauses.vod.loading=!1}},resetPauses=t=>{t.pauses=initialState$o,t.pauses.vod.items.length=0},filterPausesVod=(t,{sourceId:e})=>listOfAllSourceIdsSelector(t).includes(e),preparePauseVodWithPoster=(t,e)=>{var o;const s=preparePosterImage(e),n=e.sourceId==="archive"?getTitlePath("archive",e.titleId,e.episodeId,e.mediaItemId):getTitlePath(e.sourceId,e.titleId,e.episodeId);let i="",r=0;return e.totalDurationMsec&&(i=secondsToHMSelector(t,convertToSeconds(e.totalDurationMsec,"millisecond")),e.msecFromStart&&(r=Math.max(e.msecFromStart/e.totalDurationMsec,0))),{id:e.id,title:((o=e.shortData)==null?void 0:o.title)||"",link:n,image:s,duration:i,timelinePosition:r,sourceId:e.sourceId,titleId:e.titleId,episodeId:e.episodeId,mediaItemId:e.mediaItemId,msecFromStart:e.msecFromStart}},preparePosterImage=t=>{var d;let e="",r=0,o=0,a="",l="portrait";const c=(d=t.shortData)==null?void 0:d.image;if(!c)return{src:e,width:r,height:o,type:a,orientation:l};if(t.sourceId==="archive"&&(l="landscape",c!=null&&c.aspectRatio)){const u=c.aspectRatio.split(":").map(f=>parseInt(f,10)),h=calculateSizeByAspectRatio(180,132,u[0],u[1]);r=h.width,o=h.height}return c&&(e=c.path,a=c.type,!r&&!o&&(l==="portrait"?(r=Math.round(132*.7),o=132):(r=180,o=132))),{src:e,width:r,height:o,type:a,orientation:l}},deleteVodPause=async(t,e,s,n)=>{var i;try{await deleteVodPause$1(s,n,{languageCode:t.languageCode,ctx:e});const r=t.pauses.vod.items.findIndex(a=>a.titleId===n),o=t.pauses.vod.items[r];t.pauses.vod.items.splice(r,1),showPauseRemovedNotification(t,((i=o.shortData)==null?void 0:i.title)||"")}catch(r){log$I.error("deleteVodPause",r);const o="error_during_vod_pause_delete",a=translationSelector(t,o)||`{${o}}`;showErrorNotification(t,a),setTimeout(()=>{hideErrorNotification(t)},3e3)}},pauses=Object.freeze(Object.defineProperty({__proto__:null,deleteVodPause,filterPausesVod,loadVodPauses,preparePauseVodWithPoster,resetPauses},Symbol.toStringTag,{value:"Module"}
4)),log$H=logger$1("vod-actions"),loadPlaybackInfoDetailsForArchive=async(t,e)=>{const s=playingTitleSelector(t),n=archiveTitlePlaybackMethodParamsSelector(t),i=(n==null?void 0:n.channel_id)||"",r=(n==null?void 0:n.region)||"";try{if(!s){log$H.error("Unable to load playbackInfo details: there is no active playing title",s);return}log$H.info("loading playbackInfo details for channel",i);const o={};r&&(o.region=r);const a=await getPlaybackInfo({ctx:e,languageCode:languageCodeSelector(t),enable50fps:fps50Selector(t),languageIndex:defaultLanguageIndexSelector(t),renditionIndex:defaultRenditionIndexSelector(t),params:o,channelId:i}).catch(l=>{log$H.error(l);let c=PLAYER_ERROR_CODES.COMMON;return l.resStatus===HTTP_CODES.FORBIDDEN&&(c=PLAYER_ERROR_CODES.PROVIDER_ERROR),setError(t,c,l.message||translationSelector(t,"error_empty_response"),l.resStatus),null});return a?(clearError(t),setPlaybackInfoSmotreshka(t,a),log$H.info("playbackInfo have been loaded",a),((a==null?void 0:a.languages)||[]).length||log$H.warn("Invalid playbackInfo: languages were not found")):log$H.warn("playbackInfo details have not been loaded",a),stopLoading$1(t),!0}catch(o){log$H.error(o);let a=PLAYER_ERROR_CODES.COMMON;o.resStatus===HTTP_CODES.FORBIDDEN&&(a=PLAYER_ERROR_CODES.PROVIDER_ERROR);const l=o.message||translationSelector(t,"channel_is_not_available");return setError(t,a,l,o.resStatus),!1}},loadSources=async(t,e)=>{var i;if(sourcesLoadedSelector(t)||sourcesLoadingSelector(t))return;log$H.info("Do you need to load VOD-sources?",!sourcesLoadedSelector(t)&&!sourcesLoadingSelector(t)),t.vod.states.sourcesLoading=!0;let s=!1;try{t.vod.sourcesFe=((i=await getSources({languageCode:languageCodeSelector(t),ctx:e}))==null?void 0:i.sources)||[],log$H.info("VOD FE sources have been loaded & set to store")}catch(r){log$H.error("api.vod.getSources ->",r),s=!0,t.vod.sourcesFe={sources:[]}}finally{t.vod.states.sourcesLoading=!1}if(!t.vod.sourcesFe.length){t.vod.states.sourcesLoaded=!s;return}const n={};t.vod.sourcesFe.filter(r=>{var o;return r.id==="archive"||((o=t.vod.sourcesBe.find(a=>a.id===r.id))==null?void 0:o.isUsed)||wlDetector().isSanta}).sort((r,o)=>(r==null?void 0:r.priority)-(o==null?void 0:o.priority)).forEach(r=>{var l,c,d,u,h,f,g,p,m,v;r.titlesEnhanced={};let o;const a=t.vod.sourcesBe.findIndex(S=>S.id===r.id);r.id!=="archive"?o={...r,color:((l=t.vod.sourcesBe[a])==null?void 0:l.color)||"",customTitleId:((c=t.vod.sourcesBe[a])==null?void 0:c.customTitleId)||"",imageTileVod:((d=t.vod.sourcesBe[a])==null?void 0:d.imageTileVod)||"",isUsed:((u=t.vod.sourcesBe[a])==null?void 0:u.isUsed)||wlDetector().isSanta,logo:((h=t.vod.sourcesBe[a])==null?void 0:h.logo)||"",logoId:((f=t.vod.sourcesBe[a])==null?void 0:f.logoId)||"",logoTilePoster:((g=t.vod.sourcesBe[a])==null?void 0:g.logoTilePoster)||"",logoTilePosterDark:((p=t.vod.sourcesBe[a])==null?void 0:p.logoTilePosterDark)||"",posterProportions:{height:((m=t.vod.sourcesBe[a])==null?void 0:m.posterProportions.height)||3,width:((v=t.vod.sourcesBe[a])==null?void 0:v.posterProportions.width)||2}}:o={...r},n[r.id]=o}),t.vod.sources=n,t.vod.states.sourcesLoaded=!s,log$H.info("VOD BE + FE sources have been set to store")},resetSources=t=>{t.vod.sources={},t.vod.sourcesFe={},t.vod.states.sourcesLoaded=!1},getSourceCategories=async(t,e,s)=>{var o;const[n]=await Promise.all([getCategories(e,s)]),i=new Set;e==="archive"&&((o=n==null?void 0:n.categories)==null||o.push({id:"-1",description:"",title:translationSelector(t,"vod_filter_all_categories"),priority:-1,genres:[],slug:""}));const r=((n==null?void 0:n.categories)||[]).map(a=>{const l={...a,genres:a.genres||[],titles:[],titlesEnhanced:{}};l.genres.unshift({id:"-1",title:translationSelector(t,"vod_filter_all_genres"),priority:1000001,slug:""});const c=new Set;return l.genres=l.genres.filter(d=>{if(!(d!=null&&d.id))return!1;const u=JSON.stringify(d);return e==="archive"&&d.id!=="-1"&&i.add(u),i.add(u),c.has(u)?!1:(c.add(u),!0)}).sort((d,u)=>{const h=u.priority-d.priority;return h!==0?h:compareStrings(d.title,u.title)}),l}).reduce((a,l)=>(a[l.id]=l,a),{});
4if(e==="archive"){const a=[...new Set([...i].map(l=>JSON.parse(l)))];r[-1]&&(r[-1].genres=a)}return{categories:r}},loadSourceCategories=async(t,e,s)=>{if(sourceCategoriesLoadedSelector(t,s)||sourceCategoriesLoadingSelector(t,s)||!t.vod.sources[s])return;t.vod.sources[s].categoriesLoading=!0;const{categories:n}=await getSourceCategories(t,s,{languageCode:languageCodeSelector(t),ctx:e}).catch(i=>(log$H.error(i),{categories:{}}));(!n||Object.keys(n).length===0&&isOkObject(n))&&log$H.error(`Categories for sourceId = ${s} are absent.`),t.vod.sources[s].categories=n,t.vod.sources[s].categoriesLoaded=!0,t.vod.sources[s].categoriesLoading=!1,log$H.info(`Categories data has loaded for sourceId = ${s}`)},resetCurrentCategoryId=t=>{for(const e of listOfSourceIdsWithoutArchiveSelector(t))t.vod.sources[e]&&(t.vod.sources[e].currentCategoryId=DEFAULT_VOD_CATEGORIES[e])},setCurrentCategoryId=(t,e,s="")=>{t.vod.sources[e]&&(t.vod.sources[e].currentCategoryId=s)},loadFavorites=async(t,e)=>{var n;if(isAnonymousSelector(t)||!myPageEnabledSelector(t))return;if(favoritesLoadingSelector(t)){log$H.info("VOD Favorites are already being loaded right now");return}if(favoritesLoadedSelector(t)&&favoritesSelector(t).length){log$H.info("VOD Favorites have already been loaded before");return}t.vod.states.favoritesLoading=!0;const s=((n=await getFavorites({languageCode:languageCodeSelector(t),ctx:e}).catch(i=>{log$H.error("getFavorites:",i),t.vod.states.favoritesLoading=!1,t.vod.states.favoritesLoaded=!0}))==null?void 0:n.shortData)||[];s.length?(t.vod.favorites=s,log$H.info("VOD Favorites have been successfully loaded")):log$H.info("VOD Favorites are empty"),t.vod.states.favoritesLoading=!1,t.vod.states.favoritesLoaded=!0},resetFavorites=t=>{t.vod.states.favoritesLoaded=!1,t.vod.states.favoritesLoading=!1,t.vod.favorites=[]},toggleTitleFavorite=async(t,e,s,n,i,r)=>{const o=isInFavoritesSelector$1(t,n);if(o){await removeFromFavorites(n,s,{languageCode:t.languageCode,ctx:e});const a=t.vod.favorites.findIndex(l=>l.titleId===n);t.vod.favorites.splice(a,1),await showFavoriteNotification(t,"vod",!o,i)}else await addToFavorites(n,s,{languageCode:t.languageCode,ctx:e}).then(()=>{t.vod.states.favoritesLoaded=!1,loadFavorites(t,e),showFavoriteNotification(t,"vod",!o,i)}).catch(a=>{var h,f,g;log$H.error("addToFavorites",a);const d=(((f=(h=a.response)==null?void 0:h.data)==null?void 0:f.message)||((g=a.response)==null?void 0:g.data)).includes("excess")?"vod_favorites_limit_was_reached":"unknown_error",u=translationSelector(t,d)||`{${d}}`;showErrorNotification(t,u),setTimeout(()=>{hideErrorNotification(t)},3e3)});gaEvent({...gaParamsSelector(t),action:o?"Удалить из избранного":"Добавить в избранное",title_id:n,control_type:"mouse",category:"vod",vod_name:s},t)},setSorting=(t,e)=>{t.vod.sorting=e},setSortings=(t,e)=>{t.vod.sortings=e},resetSorting=t=>{t.vod.sorting=""},savePause=async(t,e,s)=>{s==="archive"?await saveArchivePause(t,e):await saveVodPause(t,e)},saveVodPause=async(t,e)=>{const s=playingSourceIdSelector(t);playingTitleIdSelector(t)?(await saveVodPause$1({ctx:e,languageCode:languageCodeSelector(t)},s,playingTitleIdSelector(t),playingMediaItemIdSelector(t)||playingEpisodeIdSelector(t)||playingTitleIdSelector(t),Math.floor(convertToMilliseconds(Math.max(playingTimeSelector(t),1),"second")),Math.floor(convertToMilliseconds(videoDurationSelector(t),"second")),playingEpisodeIdSelector(t),playingSeasonIdSelector(t),0),await loadTitleVodPause(t,e,s,playingTitleIdSelector(t)),await loadVodPauses(t,e,!0)):log$H.warn("Could not save pause. Title's ID was not provided")},saveArchivePause=async(t,e)=>{var u,h,f,g,p;const s=archiveTimelineDurationSelector(t),n=s*ARCHIVE_PLAYER_TICK_OFFSET,i=playingTitleSelector(t),r=hasSeasonsInPlayingTitleSelector(t),o=(u=i==null?void 0:i.preview)==null?void 0:u.hasSeries,a=n+1,l=Math.max(playingTimeSelector(t),a);let c;o&&(c=(f=(h=i==null?void 0:i.details)==null?void 0:h.episodes)==null?void 0:f.find(m=>{var v;return((v=m==null?void 0:m.preview)==null?void 0:v.id)===playingEpisodeIdSelector(t)}));const d=playingMediaItemSelector(t,o?(g=c==null?void 0:c.details)==null?void 0:g.mediaItems:(p=i==null?void 0:i.details)==null?void 0:p.mediaItems);l>n&&l<s-n&&(playingTitleIdSelector(t)?(await saveVodPause$1({ctx:e,languageCode:languageCodeSelector(t)},"archive",playingTitleIdSelector(t),playingMediaItemIdSelector(t)||(d==null?void 0:d.id),Math.floor(convertToMilliseconds(l-archiveTickDurationSelector(t),"second")),Math.floor(convertToMilliseconds(archiveTitleDurationSelector(t),"second")),playingEpisodeIdSelector(t),r?playingSeasonIdSelector(t):"",d==null?void 0:d.expiresAt),await loadTitleVodPause(t,e,"archive",playingTitleIdSelector(t)),await loadVodPauses(t,e,!0)):log$H.warn("Could not save pause. Title's ID was not provided"))},setAudioTrackIndex=(t,e)=>{t.vod.audioTrackIndex=e},startLoadingTitle=(t,e,s)=>{var n;(n=t.vod.sources[e].titlesEnhanced)!=null&&n[s]&&(t.vod.sources[e].titlesEnhanced[s].loading=!0)},stopLoadingTitle=(t,e,s)=>{var n;(n=t.vod.sources[e].titlesEnhanced)!=null&&n[s]&&(t.vod.sources[e].titlesEnhanced[s].loading=!1)}
4,setLoadedTitle=(t,e,s)=>{t.vod.sources[e].titlesEnhanced[s].loaded=!0},resetLoadedTitle=(t,e,s)=>{t.vod.sources[e].titlesEnhanced[s].loaded=!1},flushTitles=(t,e,s)=>{var n,i;{const r=s?(i=(n=t.vod)==null?void 0:n.sources[e].categories)==null?void 0:i[s]:null;r?r.titles=[]:t.vod.sources[e].titles=[]}},loadTitles=async(t,e)=>{var l,c,d,u,h;const{sourceId:s}=e;let{categoryId:n}=e;if(!s)return log$H.error("sourceId was not passed"),[];if(!n)return log$H.error("categoryId was not passed"),[];const i=t.vod.sources[s].categories;i!=null&&i[n]||(log$H.error(`categoryId = ${n} does not exists in categories`,i),n=((l=i==null?void 0:i[Object.keys(i||{})[0]])==null?void 0:l.id)||"",n?(e.categoryId=n,setCurrentCategoryId(t,s,n),log$H.info(`using the 1st available categoryId = ${n} instead`)):log$H.error("Cannot set current category ID because categoryId = undefined"));const r=((c=i==null?void 0:i[n])==null?void 0:c.titles)||[];if(e.offset=e.offset||r.length,!sortingSelector(t)&&e.sourceId!=="archive"){const f=(d=await getTitlesMeta(s,{languageCode:languageCodeSelector(t),ctx:e.ctx}).catch(g=>log$H.error(g)))==null?void 0:d.sortings;if(f!=null&&f.length){setSortings(t,f);const g=((u=f==null?void 0:f[0])==null?void 0:u.name)||"";setSorting(t,g),e.sort=g}else log$H.info(`Sortings are not available for sourceID=${s}`)}const o=await getCategoryTitles(e),a=(h=t.vod.sources[s].categories)==null?void 0:h[n];return a&&t.vod.sources[s]&&i!=null&&i[n]&&(a.titles=r.concat(o),log$H.info(`Titles have been loaded & set to store for categoryId = ${n}`)),o},searchTitles=async(t,e,s)=>{const{limit:n,offset:i,searchQuery:r,sourceId:o}=s;if(!o)throw new Error("searchTitles action: sourceId was not passed");if(!r)throw new Error("searchTitles action: VOD searchQuery was not passed");let a=null;try{a=await getSearchTitles(o,{languageCode:t.languageCode,ctx:e,params:{query:r,limit:n,offset:i||0}})}catch(l){log$H.error(l)}t.vod.sources[o].titles=(a==null?void 0:a.titles)||[]},loadTitleVod=async(t,e,s,n,i)=>{var r,o,a,l;if(!s){log$H.error("sourceId was not passed to loadTitleVod");return}if(!n){log$H.error("titleId was not passed to loadTitleVod");return}if(!t.vod.sources[s]){log$H.warn(`current sourceid=[${s}] is absent from sources=[${[Object.keys(t.vod.sources)].join(", ")}]`);return}if(titleEnhancedLoadedSelector(t,s,n)){log$H.debug(`Title ${n} has already been loaded`);return}if(titleEnhancedLoadingSelector(t,s,n)){log$H.debug(`Title ${n} is already loading`);return}t.vod.sources[s].titlesEnhanced[n]={...VOD_TITLE_ENHANCED_TEMPLATE};try{startLoadingTitle(t,s,n),log$H.debug(`Title ${n} is loading...`);const c=t.vod.sources[s].titlesEnhanced[n],d=await getTitle(s,n,{languageCode:languageCodeSelector(t),ctx:e});if(d){if(log$H.info(`Title ${n} has been loaded!`),(r=d==null?void 0:d.preview)!=null&&r.hasSeries){const{titleSeasons:u,titleEpisodes:h}=await loadTitleSeasonsAndEpisodes(s,n,{ctx:e,languageCode:languageCodeSelector(t)},(o=d.details)==null?void 0:o.seasons,translationSelector(t,"without_season"));d.details&&(d.details.seasons=u,d.details.episodes=h)}if(t.vod.sources[s]){const u=((l=(a=t.siteConfig)==null?void 0:a.seoExperiment)==null?void 0:l.titles)||[],h=i==null?void 0:i.name,f=h==="vod-title"||h==="archive-title",g=h==="vod-title-season"||h==="archive-title-season",p=f||g;u.forEach(m=>{var E;const v=m.variationId==="var_1_entire_card",S=m.variationId==="var_2_seasons_only",y=m.variationId==="var_3_main_page_only",C=!v&&(S&&!g||y&&g);p&&m.experimentId&&m.experimentId!=="type2_hide_google"&&d.details&&m.titleId===((E=d.preview)==null?void 0:E.id)&&!C&&(d.details.description="")}),t.vod.sources[s].titlesEnhanced[n]={...c,...d}}}}catch(c){log$H.error(c)}finally{stopLoadingTitle(t,s,n),setLoadedTitle(t,s,n)}await loadTitleVodPause(t,e,s,n)},loadTitleVodPause=async(t,e,s,n)=>{var i,r;if(!isAnonymousSelector(t))if((r=(i=t.vod.sources[s])==null?void 0:i.titlesEnhanced)!=null&&r[n]){const o=await getVodTitlePauses(s,n,{ctx:e,languageCode:languageCodeSelector(t)});t.vod.sources[s].titlesEnhanced[n].pauses=o,log$H.info(`VOD pauses have been loaded for title = ${n}`,o)}else log$H.warn(`Unable to load pauses for title = ${n}, title should be loaded first`)},loadSimilarities=async(t,e,s,n)=>{t.vod.similarities=await getSimilarCollections(e,languageCodeSelector(t),audienceTokenSelector(t),s,n)},loadTitleVideoData=async(t,e,s,n,i)=>{var g,p,m,v;if(!s)throw new Error("Source ID was not passed");startLoading$1(t);const r=i||n,o=titleEnhancedSelector(t,s,n);let a=(p=(g=o==null?void 0:o.details)==null?void 0:g.mediaItems)==null?void 0:p[0];if(i){const S=await getTitle(s,i,{languageCode:languageCodeSelector(t),ctx:e}).catch(y=>
4(setError(t,y.code,y.message,y.resStatus),null));a=(v=(m=S==null?void 0:S.details)==null?void 0:m.mediaItems)==null?void 0:v[0]}if(!a)throw new Error(`No media items, titleId=${n}, episodeId=${i}`);const l=sortBy(a==null?void 0:a.playbackMethods,"priority"),c=Object.values(PLAYBACK_METHODS),d=l.find(S=>c.includes(S.name));if(!d)throw log$H.error("proper playback method was not found",{episodeOrTitle:o,playbackMethods:l}),new Error("Proper playback method was not found");t.player.playbackMethod=d.name,log$H.info(`playbackMethod ${d.name} has been loaded`),log$H.info("Video data has been loaded");const u=S=>S.params.reduce((y,C)=>(y[C.key]=C.value,y),{});let h=u(d);log$H.info("Playback method:",d.name);const f=getUserAgent();try{if(d.name===PLAYBACK_METHODS.iviTwoSteps){const S=await getIviPlayback(r,{languageCode:t.languageCode,ctx:e,params:h});S&&(h=u(S))}if(d.name===PLAYBACK_METHODS.iviTwoSteps||d.name===PLAYBACK_METHODS.iviWithIntegrationParams){const S=await getContentInfo(h,{languageCode:t.languageCode,ctx:e});for(const C of S.files)C.url=matchUrlProtocolWithLocationProtocol(C.url,t.common.isHttps);setPlaybackInfoIvi(t,S);const y=S==null?void 0:S.files[0].url;y?log$H.debug("Playback URL for IVI is ready",y):log$H.error("Playback URL for IVI was not provided, iviContentInfo:",S)}else if(d.name===PLAYBACK_METHODS.megogoV1){const S=await getMegogoPlayback(r,{languageCode:t.languageCode,ctx:e,params:h}).catch(C=>{throw log$H.error(C),C}),y=S==null?void 0:S.data;if(y){setPlaybackInfoMegogo(t,{...y});const C=(y==null?void 0:y.audio_tracks)||[];if(C.length>0){const T=storage.get(STORE_KEYS.player.audioTrackMegogo);let b=C.findIndex(I=>I.id.toString()===T);b=b>=0?b:0,C[b].index>=0&&(t.vod.audioTrackIndex=b)}const E=getDrmSystem(f);y.src?log$H.debug(`Playback URL & data from ${d.name} are ready, drmSystem:`,E):log$H.error(`Playback URL from ${d.name} was not provided:`,y)}else log$H.error(`Unable to get data from /playback/vod/megogo/v1/${r}`)}else if(d.name===PLAYBACK_METHODS.amedia2V1){const S=await getAmediaPlayback(r,{languageCode:t.languageCode,ctx:e,params:h}).catch(b=>{throw log$H.error(b),b});let y,C;S&&(y=S.response.video,C=S.playbackSession),setPlaybackInfoAmedia(t,{...y});const E=getDrmSystem(f),L=playbackInfoAmediaSelector(t);let T="";L?(T=getAmediaDrmStreamUrl(L,E),T?log$H.info(`Playback URL & data from ${d.name} have been set to store.player.playbackInfo.amedia2V1, drmSystem:`,E):log$H.error(`Playback URL from ${d.name} was not provided:`,y)):log$H.error("amedia2Playback is empty:",y),C&&(t.player.playbackSessionContext=C)}else if(d.name===PLAYBACK_METHODS.smotreshkaVodV2){const S=await getVodPlayback(r,{languageCode:t.languageCode,ctx:e,params:h}).catch(E=>{throw log$H.error(E),E});let y="",C;if(S&&(setPlaybackInfoSmotreshkaVodV2(t,S),y=S.url,C=S.playbackSession),!y){log$H.error("Playback video URL is absent");return}C&&(t.player.playbackSessionContext=preparePlaybackSessionContext(C)),log$H.info("Playback URL is ready",y)}else{log$H.error("Title:",o,"PLAYBACK METHOD:",d),log$H.error(`UNKNOWN PLAYBACK METHOD: '${d.name}'`);return}}catch(S){throw resetPlaybackInfo(t),S}hidePlayerErrorNotification(t),stopLoading$1(t)},preparePlaybackSessionContext=t=>{const e={...t};return Object.keys(e).forEach(s=>{var n;if(Object.getOwnPropertyDescriptor(VALIDATE_RULES,s)){const i=parseInt(((n=e==null?void 0:e[s])==null?void 0:n.toString())||"");if(!VALIDATE_RULES[s].check(i)){const{min:o,max:a}=VALIDATE_RULES[s];e[s]=i<o?o:a}}}),e},VALIDATE_RULES={updateInSec:{min:.1,max:600,check(t){return t>=this.min&&t<=this.max}},expireInSec:{min:.1,max:86400,check(t){return t>=this.min&&t<=this.max}}},checkForProviderWithCountryCode=async(t,e,s)=>{await loadProviderInfo(t,e),s.phone=salesPhoneFormattedSelector(t),s.url=urlSelector(t),isAnonymousSelector(t)?gaEvent({category:"blocked_content_click",action:"Появление ошибки - Вы не авторизованы"},t):s.phone||s.url?gaEvent({category:"blocked_content_click",action:"Нет подписки с контактами провайдера"},t):gaEvent({category:"blocked_content_click",action:"Нет подписки без контактов провайдера"},t)},resetCollections=t=>{t.vod.states.isAnyHomeCollectionLoaded=!1,t.vod.states.isAnyHomeCollectionLoading=!1,t.vod.states.isSourceCollectionLoaded=!1,t.vod.states.isSourceCollectionLoading=!1,t.vod.homeCollections=[],t.vod.sourceCollections=[]},loadHomeCollections=async(t,e)=>{var i;const s=Object.keys(sourcesSelector(t));let n=[];if(!sourcesLoadedSelector(t)){log$H.warn("VOD-sources were not loaded yet");return}if(!listOfAllSourceIdsSelector(t).length){log$H.warn("There are 0 VOD-sources. Skip loading Home VOD-collections");return}if(isAnyHomeCollectionLoadingSelector(t)){log$H.info("Home VOD-collections have already started loading");return}if(!((i=t.vod.homeCollections)!=null&&i.length&&isAnyHomeCollectionLoadedSelector(t))){t.vod.states.isAnyHomeCollectionLoading=!0,audienceTokenSelector(t)||await loadAssetTokens(t,e);try{const r=await getVodHomeCollections({languageCode:t.languageCode,ctx:e},hasVodHomeCollectionsV3Selector(t),audienceTokenSelector(t));if(r&&(n=r.vodCollections),!(n!=null&&n.length)){t.vod.states.isAnyHomeCollectionLoaded=!0,t.vod.states.isAnyHomeCollectionLoading=!1;return}n=n.filter(o=>{var a;return((a=o.titlesList)==null?void 0:a.length)&&(o.vodSource==="archive"||s.includes(o.vodSource))}),n=sortBy(mapHomeCollections(t,n),"priority"),await setHomeCollections(t,n),log$H.info("Home VOD-collections have been loaded"),t.vod.states.isAnyHomeCollectionLoaded=!0}catch(r){log$H.error("Home VOD-collections did not load:",r)}finally{t.vod.states.isAnyHomeCollectionLoading=!1}}},mapHomeCollections=(t,e)=>e.length?e.map(s=>({caption:s.caption,logo:s.vodSource!=="archive"?sourceLogoUrlSelector(t,s.vodSource):void 0,titlesList:s.titlesList,vodSource:s.vodSource,vodCollectionId:s.vodCollectionId,id:s.id,priority:s.priority,brandingMethods:[],placementBlocks:s.placementBlocks})):[],setHomeCollections=async(t,e)=>{let s=[];s=e.flatMap(n=>listOfAllSourceIdsSelector(t).includes(n.vodSource)?prepareCollection(t,n):[]),t.vod.homeCollections=s},prepareTitlesForCollection=(t,e,s)=>s.map(n=>({...n,widthProportion:posterWidthProportionSelector(t,e),heightProportion:posterHeightProportionSelector(t,e),link:getTitlePath(e,n.id)})),prepareCollection=(t,e)=>({...e,titlesList:prepareTitlesForCollection(t,e.vodSource,e.titlesList)}),loadTitlesForSourceCollection=async(t,e,s,n)=>{var l,c,d,u;if(!s){log$H.info("sourceId was not provided");return}if(!n){log$H.info("collectionId was not provided");return}t.vod.states.isSourceCollectionLoading=!0;const i=t.vod.sourceCollections.find(h=>h.id===n),r=((l=i==null?void 0:i.titlesList)==null?void 0:l.length)||0,o=(c=await getCollectionTitles(languageCodeSelector(t),e,s,n,r).catch(h=>{log$H.error(h),t.vod.states.isSourceCollectionLoading=!1}))==null?void 0:c.titles;if(o!=null&&o.length){const h=((d=await getVodSourceCollections({ctx:e,languageCode:languageCodeSelector(t)},s).catch(g=>{log$H.error(g)}))==null?void 0:d.collections)||[];let f="";h!=null&&h.length&&(f=((u=h==null?void 0:h.find(g=>g.id===n))==null?void 0:u.title)||""),addTitlesToSourceCollection(t,s,n,o,f)}t.vod.states.isSourceCollectionLoading=!1;const a=t.vod.sourceCollections.findIndex(h=>h.id===n);a>=0&&(t.vod.sourceCollections[a].hasMoreTitlesToLoad=(o==null?void 0:o.length)===DEFAULT_TILES_AMOUNT)},addTitlesToSourceCollection=(t,e,s,n,i)=>{var r;if(i=i||((r=t.vod.homeCollections.find(o=>(o==null?void 0:o.vodCollectionId)===s||(o==null?void 0:o.id)===s))==null?void 0:r.caption)||"",!t.vod.sourceCollections.find(o=>o.id===s))t.vod.sourceCollections.push({brandingMethods:[],caption:i,id:s,logo:e!=="archive"?sourceLogoUrlSelector(t,e):void 0,placementBlocks:[],priority:0,titlesList:prepareTitlesForCollection(t,e,n),vodCollectionId:"",vodSource:e});else{const o=t.vod.sourceCollections.findIndex(l=>l.id===s),a=t.vod.sourceCollections[o].titlesList;a.push(...prepareTitlesForCollection(t,e,n)),t.vod.sourceCollections[o].titlesList=a}},vod=Object.freeze(Object.defineProperty({__proto__:null,addTitlesToSourceCollection,checkForProviderWithCountryCode,flushTitles,loadFavorites,loadHomeCollections,loadPlaybackInfoDetail
4sForArchive,loadSimilarities,loadSourceCategories,loadSources,loadTitleVideoData,loadTitleVod,loadTitleVodPause,loadTitles,loadTitlesForSourceCollection,preparePlaybackSessionContext,resetCollections,resetCurrentCategoryId,resetFavorites,resetLoadedTitle,resetSorting,resetSources,savePause,searchTitles,setAudioTrackIndex,setCurrentCategoryId,setLoadedTitle,setSorting,setSortings,startLoadingTitle,stopLoadingTitle,toggleTitleFavorite},Symbol.toStringTag,{value:"Module"})),log$G=logger$1("payment-actions"),loadPaymentMethod=async(t,e,s,n=!1)=>{if(!t.payment.method||n){const i={languageCode:t.languageCode,ctx:e};s&&(i.params={token:s}),t.payment.method=await paymentMethod(i)}},removePaymentMethod=async(t,e)=>{await removePaymentMethod$1({languageCode:t.languageCode,ctx:e}),t.payment.method=null},loadYakassaSubscriptions=async(t,e,s)=>{const n={languageCode:t.languageCode,ctx:e};s&&(n.params={token:s}),t.payment.yakassaSubscriptions=await yakassaSubscriptions(n)||[]},loadCurrentSubscriptions=async(t,e)=>{var s,n,i,r,o,a;try{const l=await currentSubscriptions({languageCode:t.languageCode,ctx:e});if(!(l!=null&&l.subscriptions))return;const c=[];for(const d of l.subscriptions){let u={},h=[];try{u=JSON.parse(((s=d.mainOffer)==null?void 0:s.renderingDataJson)||"{}");const g=d.mainOffer||((n=d.temporaryOffer)==null?void 0:n.offer);if(g){const p=await getOfferAllChannels(g.offerId,{ctx:e,languageCode:t.languageCode});h=((i=p==null?void 0:p.channels)==null?void 0:i.filter(m=>t.tvChannels.list[m.channelId]))||[]}}catch(g){log$G.error(g)}const f={...d,showcaseChannels:h,renderingData:u,managementMethods:sortByPriority((r=d.managementMethods)==null?void 0:r.filter(g=>SUPPORTED_MANAGEMENT_METHODS.includes(g.name)))};d.mainOffer&&(f.mainOffer={...d.mainOffer,renderingMethods:(a=(o=d.mainOffer)==null?void 0:o.renderingMethods)==null?void 0:a.filter(g=>availableTemplates[g.name]||g.name===BILLING_RENDERING_METHOD_NAME)}),c.push(f)}c!=null&&c.length&&(t.payment.currentSubscriptions=c,c.some(d=>{var u;return(u=d.managementMethods)==null?void 0:u.find(h=>h.name===MANAGEMENT_METHOD_NAMES.YAKASSA)})&&await actions.payment.loadYakassaSubscriptions(t,e))}catch(l){log$G.warn("loadCurrentSubscriptions failed",l)}},payment$1=Object.freeze(Object.defineProperty({__proto__:null,loadCurrentSubscriptions,loadPaymentMethod,loadYakassaSubscriptions,removePaymentMethod},Symbol.toStringTag,{value:"Module"})),utmLabelsSelector=t=>{var e;return(e=t.utmLabels)==null?void 0:e.reduce((s,n)=>({...s,[`utm_${n.name}`]:n.value}),{})},utmLabels$1=Object.freeze(Object.defineProperty({__proto__:null,utmLabelsSelector},Symbol.toStringTag,{value:"Module"})),log$F=logger$1("qs"),handleModalStepBack=t=>{goToPrevStep(t),t.qs.toPrevStep=!0},isOnForbidden=(t,e)=>{t.resStatus===HTTP_CODES.FORBIDDEN&&showQsNotification(e,t.message)},handleForTv=async(t,e,s)=>{if(t.qs.currentSourceId=s.id||"",!(isAnonymousSelector(t)||hasVitrinaSelector(t)||!getChannelIsLocked(s)||wlDetector().isSanta||t.secretSanta)){try{await getTvV3SubscriptionOptions(t,e,s.id)}catch(n){if(isOnForbidden(n,t),[void 0,HTTP_CODES.NOT_FOUND].includes(n.resStatus))try{await getTvSubscriptionOptions(t,e,s.id)}catch(i){isOnForbidden(i,t),[void 0,HTTP_CODES.NOT_FOUND].includes(i.resStatus)||setError(t,PLAYER_ERROR_CODES.COMMON,i.message,i.resStatus)}}await loadPaymentMethodAndShowModal(t,e,QS_SOURCE_TYPES.CHANNEL,!0,s)}},handleForVod=async(t,e,s,n,i)=>{if(!(t.secretSanta||wlDetector().isSanta)){t.qs.currentSourceId=s;try{await getVodV3SubscriptionOptions(t,e,{params:{sourceId:s}})}catch(r){if(isOnForbidden(r,t),[void 0,HTTP_CODES.NOT_FOUND].includes(r.resStatus))try{await getVodSubscriptionOptions(t,e,{params:{sourceId:s}})}catch(o){isOnForbidden(o,t)}}await loadPaymentMethodAndShowModal(t,e,QS_SOURCE_TYPES.VOD,!1,null,s,n,i)}},handleOffersSet=async(t,e,s)=>{if(t.secretSanta||wlDetector().isSanta)return;if(isAnonymousSelector(t)){actions.notifications.showAuthAndRegNotification(t);return}const n=`offer-set-${s}`;t.qs.currentSourceId=n;try{await getOffersSetSubscriptionOptions(t,e,s,n)}catch{}await loadPaymentMethodAndShowModal(t,e,"promo",!1,null),actions.utmLabels.resetUtmLabels(t)},loadPaymentMethodAndShowModal=async(t,e,s,n,i,r,o,a)=>{var l,c;
4if(currentTemplateComponentSelector(t)){const d=prioritySubscriptionSelector(t);try{await loadPaymentMethod(t,e)}catch(h){log$F.error("onLoadPaymentMethod",h)}t.qs.sourceType=s,n?t.qs.channel=i:r&&o&&a&&(t.qs.vod={name:((l=o==null?void 0:o.preview)==null?void 0:l.title)||"",sourceId:r,episodeId:a}),showQs(t);const u={...gaParamsSelector(t),category:"acquiring",action:"Показ диалога оплаты",trial_available:`${d==null?void 0:d.trialAvailable}`,acquiring_type:"qs"};n?u.channel_name=(i==null?void 0:i.title)||"":(u.vod_name=r||"",u.title_name=((c=o==null?void 0:o.preview)==null?void 0:c.title)||""),gaEvent(u,t)}},setCurrentStepByIndex=(t,e)=>{var s,n;t.qs.currentSourceId&&((n=(s=t.qs)==null?void 0:s.subscriptionsBySource[t.qs.currentSourceId])!=null&&n.steps[e])&&(t.qs.currentStepIndex=e)},goToNextOrPreviousStep=(t,e=!0)=>{const s=currentStepSelector(t);if(s){const n=e?"next":"prev",i=s[n]?getStepIndexByName(t,s[n]||""):t.qs.currentStepIndex+(e?1:-1);setCurrentStepByIndex(t,i||0)}},goToStepByName=(t,e)=>{if(e)return setCurrentStepByIndex(t,getStepIndexByName(t,e)||0)},goToNextStep=t=>goToNextOrPreviousStep(t,!0),goToPrevStep=t=>goToNextOrPreviousStep(t,!1),getParamsWithTransactionId=(t,e={})=>(t.qs.qsTransactionId&&(e.qs_transaction_id=t.qs.qsTransactionId),e),createYakassaSubscription=async(t,e)=>(removeAssetTokens(t),e.params=getParamsWithTransactionId(t,e.params),await createYakassaSubscription$1(e)),createYakassaSubscriptionV2=async(t,e)=>(removeAssetTokens(t),e.params=getParamsWithTransactionId(t,e.params),await createYakassaSubscriptionV2$1(e)),createSubscription$1=async(t,e)=>(removeAssetTokens(t),e.params=getParamsWithTransactionId(t,e.params),await createSubscription$2(e)),createSubscriptionWithVerifiedPhone=async(t,e)=>(removeAssetTokens(t),e.params=getParamsWithTransactionId(t,e.params),await createSubscriptionWithVerifiedPhone$1(e)),createSubscriptionUpsale=async(t,e)=>(removeAssetTokens(t),e.params=getParamsWithTransactionId(t,e.params),await createSubscriptionUpsale$1(e)),createSubscriptionUpsaleV2=async(t,e)=>(removeAssetTokens(t),e.params=getParamsWithTransactionId(t,e.params),await createSubscriptionUpsaleV2$1(e)),addChannelsToOffer=async(t,e,s,n=!1)=>{if(s.offerId)try{const i=await getOfferShowcaseChannels(s.offerId,{ctx:e,languageCode:languageCodeSelector(t)});if(!i)return;const{channels:r}=i,o=intersectionWith(Object.values(t.tvChannels.list),r,(a,l)=>a.id===(l==null?void 0:l.channelId));s.channels=sortBy(o,"strNumber"),s.channelsIds=(r==null?void 0:r.map(a=>a.channelId))||[],s.trialAvailable&&s.trial&&!n&&await addChannelsToOffer(t,e,s.trial,!0)}catch(i){log$F.error(i)}},prepareQsData=async(t,e,s,n)=>{var i,r,o,a;if(!s){log$F.warn("data was not provided, data:",s);return}return t.qs.paymentRetry=((r=(i=s.existingSubscriptions)==null?void 0:i[0])==null?void 0:r.subscriptionStatus)===SubscriptionStatus.IN_RETRY.toLowerCase()||((a=(o=s.existingSubscriptions)==null?void 0:o[0])==null?void 0:a.paymentSystemType)===PaymentSystem.Uztelecom,prepareQuickSubscribeData(t,e,s,n)},prepareShopSubscriptionOptions=(t=[],e,s)=>{var i;const n=[];for(const r of t){let o={},a={};try{o=JSON.parse(r.renderingDataJson||"{}"),r.trialAvailable&&r.trial&&(a=JSON.parse(r.trial.renderingDataJson))}catch(c){log$F.error(c)}const l={...r,showcaseChannels:e[r.offerId],renderingData:o};r.trial&&(l.trial={...r.trial,renderingData:a}),((i=l.shopSettings)==null?void 0:i.section)==="additional"&&s&&(l.shopSettings.categories=l.shopSettings.categories||[],l.shopSettings.categories.unshift({id:ADDITIONAL_SUBSCRIPTIONS_DEFAULT_CATEGORY_ID,name:"Все"})),l.renderingMethods=sortByPriority(l.renderingMethods),l.renderingMethod=l.renderingMethods[0],n.push(l)}return n.filter(r=>r.renderingMethods.find(o=>o.name===RENDERING_METHOD_NAMES.SUBSCRIPTION_SHOP||o.name===RENDERING_METHOD_NAMES.SUBSCRIPTION_SHOP_ADJUSTED))},getVodSubscriptionOptions=async(t,e,s)=>{const n=s.params.sourceId;if(t.qs.subscriptionsBySource[n])return;s.params={...s.params,...utmLabelsSelector(t)};const i=await vod$3({...s,languageCode:t.languageCode,ctx:e});
4i&&(t.qs.subscriptionsBySource[n]=await prepareQsData(t,e,i))},getOffersSetSubscriptionOptions=async(t,e,s,n)=>{t.qs.subscriptionsBySource[n]||(t.qs.subscriptionsBySource[n]=await prepareQsData(t,e,await offersSet(s,{ctx:e,languageCode:t.languageCode,params:{sourceId:n,...utmLabelsSelector(t)}})||void 0))},getVodV3SubscriptionOptions=async(t,e,s)=>{const n=s.params.sourceId;t.qs.subscriptionsBySource[n]||(s.params={...s.params,...utmLabelsSelector(t)},t.qs.subscriptionsBySource[n]=await prepareQsData(t,e,await vodV3({...s,languageCode:t.languageCode,ctx:e})||void 0))},getTvSubscriptionOptions=async(t,e,s,n)=>{if(t.qs.subscriptionsBySource[s])return;const i={languageCode:t.languageCode,ctx:e};n&&(i.params={token:n}),i.params={...i.params,...utmLabelsSelector(t)},t.qs.subscriptionsBySource[s]=await prepareQsData(t,e,await tv(s,i)||void 0)},getTvV3SubscriptionOptions=async(t,e,s,n)=>{const i={languageCode:t.languageCode,ctx:e};n&&(i.params={token:n}),i.params={...i.params,...utmLabelsSelector(t)},t.qs.subscriptionsBySource[s]=await prepareQsData(t,e,await tvV3(s,i)||void 0)},getAllSubscriptionOptions=async(t,e)=>{var i;const s=await loadAllAvailableSubscriptionOptions$1(e);if(!s){log$F.warn("data was not provided, data:",s);return}s.subscriptionOptions=(i=s.subscriptionOptions)==null?void 0:i.filter(({type:r})=>r==="base");const n=await prepareQsData(t,e.ctx,s);t.qs.allSubscriptions=n},getPromoCodeSubscriptionOptions=async(t,e)=>{var i;const s=await loadAllAvailableSubscriptionOptions$1(e);if(!s)return log$F.warn("data was not provided, data:",s),[];s.subscriptionOptions=(i=s.subscriptionOptions)==null?void 0:i.filter(({renderingMethods:r})=>r.find(o=>o.name===SUBSCRIPTION_METHOD_NAMES.PROMO_OFFER));const n=await prepareQsData(t,e.ctx,s,{withPromoCode:!0});t.qs.promoCodeSubscriptions=n},getByLanguageWithReplace=(t,e,s,n)=>{var o,a;let i=getByLanguage(e,languageCodeSelector(t),t.defaultLanguageCode)||"";return i?([{name:"%trialPeriod%",replacement:n?Math.round(convertToDays(n,"second")):void 0},{name:"%sourceName%",replacement:t.qs.sourceType!=="vod"?(a=(o=t.qs)==null?void 0:o.channel)==null?void 0:a.name:""},{name:"%channelCount%",replacement:s}].forEach(l=>{l.replacement!==void 0&&(i=i.replace(l.name,l.replacement))}),i):void 0},loadSubscriptionOptionsChannels=async(t,e,s=[])=>{const n=s.map(o=>getOfferAllChannels(o.offerId,{ctx:e,languageCode:t.languageCode})),i=await Promise.all(n),r={};return s.forEach((o,a)=>{var c;const l=i[a];l&&(r[o.offerId]=(c=l.channels)==null?void 0:c.filter(d=>t.tvChannels.list[d.channelId]))}),r},loadShopSubscriptionOptions=async(t,e)=>{const s=await loadShopSubscriptionOptions$1(audienceTokenSelector(t),{languageCode:t.languageCode,ctx:e});if(!s){log$F.warn("loadShopSubscriptionOptions failed");return}const{subscriptionOptions:n}=s,i=await loadSubscriptionOptionsChannels(t,e,n);t.qs.shopSubscriptions=sortByPriority(prepareShopSubscriptionOptions(n,i,!1))},loadAvailableSubscriptionOptions=async(t,e)=>{const s=await loadAllAvailableSubscriptionOptions$1({languageCode:t.languageCode,ctx:e});if(!s){log$F.warn("loadAvailableSubscriptionsOptions failed");return}const{subscriptionOptions:n}=s,i=await loadSubscriptionOptionsChannels(t,e,n);t.qs.availableSubscriptions=sortByPriority(prepareShopSubscriptionOptions(n,i,!0))},loadAllAvailableSubscriptionOptions=async(t,e)=>{const s=await loadAllAvailableSubscriptionOptions$1({languageCode:t.languageCode,ctx:e});if(!s){log$F.warn("loadAllAvailableSubscriptionOptions failed");return}const{existingSubscriptions:n,subscriptionOptions:i}=s;t.qs.existingSubscriptions=n,t.qs.allAvailableSubscriptions=i},startLoading=t=>{t.qs.loading=!0},stopLoading=t=>{t.qs.loading=!1,t.qs.subscriptionShop.loadingId=""},setSubscriptionShopLoadingId=(t,e="")=>{t.qs.subscriptionShop.loadingId=e},setAdditionalActionsCurrentStepIndex=(t,e)=>{t.qs.additionalActions.currentStepIndex=e},additionalActionsGoToNextStep=t=>{t.qs.additionalActions.currentStepIndex++},additionalActionsGoToPreviousStep=t=>{t.qs.additionalActions.currentStepIndex--},additionalActionsGoToStepByName=(t,e)=>{setAdditionalActionsCurrentStepIndex(t,QS_ADDITIONAL_ACTIONS_STEP_INDEX_DICTIONARY[e])},qs$1=Object.freeze(Object.defineProperty({__proto__:null,addChannelsToOffer,additionalActionsGoToNextStep,additionalActionsGoToPreviousStep,additionalActionsGoToStepByName,createSubscription:createSubscription$1,createSubscriptionUpsale,createSubscriptionUpsaleV2,createSubscriptionWithVerifiedPhone,createYakassaSubscription,createYakassaSubscriptionV2,getAllSubscriptionOptions,getByLanguageWithReplace,getOffersSetSubscriptionOptions,getPromoCodeSubscriptionOptions,getTvSubscriptionOptions,getTvV3SubscriptionOptions,getVodSubscriptionOptions,getVodV3SubscriptionOptions,goToNextOrPreviousStep,goToNextStep,goToPrevStep,goToStepByName,handleForTv,handleForVod,handleModalStepBack,handleOffersSet,loadAllAvailableSubscriptionOptions,loadAvailableSubscriptionOptions,loadPaymentMethodAndShowModal,loadShopSubscriptionOptions,setAdditionalActionsCurrentStepIndex,setCurrentStepByIndex,setSubscriptionShopLoadingId,startLoading,stopLoading},Symbol.toStringTag,{value:"Module"})),elementsSelector=t=>t.popupNotices.elements.map(e=>e.id),contextTokenSelector=t=>t.popupNotices.contextToken,currentElementSelector=t=>t.popupNotices.currentElement,currentElementRenderingMethodSelector=t=>{var e,s,n;return(n=(s=(e=t.popupNotices.currentElement)==null?void 0:e.renderingMethods)==null?void 0:s[0])==null?void 0:n.method},currentElementActionMethodSelector=t=>{var e,s,n;return(n=(s=(e=t.popupNotices.currentElement)==null?void 0:e.actionMethods)==null?void 0:s[0])==null?void 0:n.method},isPopupNoticeRegularModalVisibleSelector=t=>!!currentElementSelector(t)&&currentElementRenderingMethodSelector(t)===POPUP_NOTICE_RENDERING_METHODS.defaultPopup&&!!popupNoticesDisplayInCenterSelector(t),isPopupNoticeImageModalVisible=t=>!!currentElementSelector(t)&&currentElementRenderingMethodSelector(t)===POPUP_NOTICE_RENDERING_METHODS.windowBgPopup,startTimeSelector=t=>t.popupNotices.showTimeMs,popupNotices$1=Object.freeze(Object.defineProperty({__proto__:null,contextTokenSelector,currentElementActionMethodSelector,currentElementRenderingMethodSelector,currentElementSelector,elementsSelector,isPopupNoticeImageModalVisible,isPopupNoticeRegularModalVisibleSelector,startTimeSelector},Symbol.toStringTag,{value:"Module"})),log$E=logger$1("promo-elements"),getUrlByInternalRef=t=>{var s,n,i,r,o,a,l,c,d;let e="";if(t.actionMethods&&(e=((s=sortBy(t.actionMethods,"priority").find(({method:u})=>SUPPORTED_PROMO_ELEMENTS_ACTION_METHODS.includes(u)))==null?void 0:s.method)||""),e||log$E.debug("Supported action methods were not found in:",t),(n=t.internalReference)!=null&&n.screenId)switch((i=t.internalReference)==null?void 0:i.screenId){case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodContentWall.i
4d:{const u=((r=t.internalReference.vodContent)==null?void 0:r.source)||"";if(u)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodContentWall.path(u);break}case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodCollectionPage.id:{const u=(o=t.internalReference.vodContent)==null?void 0:o.source,h=(a=t.internalReference.vodContent)==null?void 0:a.collectionId.trim();if(h&&u)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodCollectionPage.path(u,h);break}case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodTitlePage.id:if(t.internalReference.vodContent){const{source:u,contentId:h}=t.internalReference.vodContent;if(u&&h)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodTitlePage.path(u,h)}break;case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodStartPlayback.id:if(t.internalReference.vodContent){const{source:u,contentId:h,episodeId:f}=t.internalReference.vodContent;if(u&&h)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodStartPlayback.path(u,h,f)}break;case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.tvContentWall.id:if((l=t.internalReference.tvContent)!=null&&l.channelId)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.tvContentWall.path(t.internalReference.tvContent.channelId);break;case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.tvStartPlayback.id:if((c=t.internalReference.tvContent)!=null&&c.channelId)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.tvStartPlayback.path((d=t.internalReference.tvContent)==null?void 0:d.channelId);break;case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.appSections.id:if(t.internalReference.appSectionId)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.appSections.path(t.internalReference.appSectionId);break;case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.searchPage.id:if(t.internalReference.searchString)return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.searchPage.path(t.internalReference.searchString);break;case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.subscriptionShopSubscribe.id:return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.subscriptionShopSubscribe.path(t.internalReference.subscriptionShop);case PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.subscriptionShopManage.id:return PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.subscriptionShopManage.path;default:log$E.debug("Unsupported internal reference:",t.internalReference)}return""},enhanceWithInternalUrl=t=>t.map(e=>({...e,internalUrl:getUrlByInternalRef(e)})),log$D=logger$1("utm-labels-actions"),setUtmLabels=(t,e)=>{log$D.debug("utmLabels",e),t.utmLabels=e},resetUtmLabels=t=>{log$D.debug("resetUtmLabels"),t.utmLabels=null},utmLabels=Object.freeze(Object.defineProperty({__proto__:null,resetUtmLabels,setUtmLabels},Symbol.toStringTag,{value:"Module"})),log$C=logger$1("notices-actions"),loadPopupNotices=async(t,e)=>{if(popupNoticesEnabledSelector(t)===!1)return;let s=audienceTokenSelector(t);s||(await loadAssetTokens(t,e),s=audienceTokenSelector(t));const n=await getPopupNotices(s,{ctx:e,languageCode:t.languageCode});n&&(t.popupNotices.elements=n.map(i=>({...i,renderingMethods:sortByPriority(i.renderingMethods.filter(r=>SUPPORTED_POPUP_NOTICE_RENDERING_METHODS.includes(r.method))),actionMethods:sortByPriority(i.actionMethods.filter(r=>SUPPORTED_PROMO_ELEMENTS_ACTION_METHODS.includes(r.method)))})).filter(i=>i.renderingMethods.length&&!!i.placementBlocks.find(({blockId:r})=>r==="default")))},tryToShow=async(t,e)=>{if(popupNoticesEnabledSelector(t)===!1)return;const s=isAnyModalOpenSelector(t),n=isAnyComplexNotificationVisibleSelector(t),i=location.href.includes("/watch"),r=location.href.includes("/adult"),o=isMinimizedSelector(t),a=isReviewVisibleSelector(t),l=isVisibleSelector(t),c=!t.popupNotices.showTimeoutId&&!isAnonymousSelector(t)&&!s&&!n&&(!i||i&&o)&&(!l||l&&o)&&!r&&!t.popupNotices.currentElement&&!a;if(isAnonymousSelector(t)||(log$C.info("tryToShow",{readyToShow:c}),log$C.debug("tryToShow",{showTimeout:t.popupNotices.showTimeoutId,isAnyModalOpen:s,isAnyComplexNotificationVisible:n,isAnyNoticeOpen:!!t.popupNotices.currentElement,isWatch:i,isAdult:r,isPlayerVisible:l,isPlayerMinimized:o,isReviewVisible:a})),c)try{const{promoElement:d,contextToken:u}=await findPromoElementToShow(t,e);t.popupNotices.contextToken=u,d&&(t.popupNotices.currentElement=d,(isPopupNoticeRegularModalVisibleSelector(t)||isPopupNoticeImageModalVisible(t))&&showPopupNoticeModal(t),await reportAction(t,e,"show"),t.popupNotices.sendTimeoutStatId&&clearTimeout(t.popupNotices.sendTimeoutStatId),t.popupNotices.sendTimeoutStatId=setTimeout(async()=>{await reportAction(t,e,"timeout"),close(t),resetUtmLabels(t)},18e5))}catch(d){log$C.error(d)}},close=t=>{var e,s;t.popupNotices.currentElement=null,hidePopupNoticeModal(t),t.popupNotices.sendTimeoutStatId&&clearTimeout(t.popupNotices.sendTimeoutStatId),startShowTimeout(t),(s=(e=t.siteConfig)==null?void 0:e.popupNotices)!=null&&s.interval?log$C.info(`close, next show will be in ${t.siteConfig.popupNotices.interval} minutes`):log$C.warn("the time period for blocking Popup Notices was not set in admin")},findPromoElementToShow=async(t,e)=>{if(t.popupNotices.elements.length||await loadPopupNotices(t,e).catch(()=>{}),log$C.debug("Total popup notices:",t.popupNotices.elements.length),t.popupNotices.elements.length){const s=elementsSelector(t),n=await whatToShow({ctx:e,languageCode:t.languageCode,data:{id:s,contextToken:contextTokenSelector(t)}});if(log$C.debug("Filtered popup notices:",s.length,"to show:",n),n&&!n.noNoticesToShow){const i=t.popupNotices.elements.find(r=>r.id===(n==null?void 0:n.promoElementId));if(i)return i.renderingData=JSON.parse(i.renderingDataJson),i.renderingData.footerTextMd&&(i.renderingData.footerText=parseMd(i.renderingData.footerTextMd)),{promoElement:i,
4contextToken:n.contextToken}}}return{promoElement:null,contextToken:""}},reportAction=async(t,e,s)=>{t.popupNotices.currentElement&&await reportAction$1({ctx:e,languageCode:t.languageCode,data:{actionType:s,promoElementId:t.popupNotices.currentElement.id,onscreenTimeMs:Date.now()-t.popupNotices.showTimeMs,contextToken:t.popupNotices.contextToken}})},reportExitAction=(t,e)=>{t.popupNotices.currentElement&&reportExitAction$1({ctx:e,languageCode:t.languageCode,data:{actionType:"exit",promoElementId:t.popupNotices.currentElement.id,onscreenTimeMs:Date.now()-t.popupNotices.showTimeMs,contextToken:t.popupNotices.contextToken}})},startShowTimeout=t=>{var e,s;t.popupNotices.showTimeoutId=setTimeout(()=>{t.popupNotices.showTimeoutId=null,log$C.info("Popup Notices are unlocked")},convertToMilliseconds((s=(e=t.siteConfig)==null?void 0:e.popupNotices)==null?void 0:s.interval,"minute"))},setShowTimeMs=(t,e)=>{t.popupNotices.showTimeMs=e},handleInternalRef=async(t,e,s,n,i)=>{var a;const r=isAnonymousSelector(t),o=getUrlByInternalRef(i);if(o&&((a=i.internalReference)!=null&&a.screenId)){const c=[PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.tvStartPlayback.id,PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING.vodStartPlayback.id].includes(i.internalReference.screenId);r&&c?(t.notifications.complex.authAndReg.returnUrl=o||"",actions.notifications.showAuthAndRegNotification(t)):await s.push(o),c||resetUtmLabels(t)}},popupNotices=Object.freeze(Object.defineProperty({__proto__:null,close,findPromoElementToShow,handleInternalRef,loadPopupNotices,reportAction,reportExitAction,setShowTimeMs,startShowTimeout,tryToShow},Symbol.toStringTag,{value:"Module"})),log$B=logger$1("auth"),reloadDataAfterLogin=async(t,e,s)=>{resetAllData(t),await putAccountToStoreAndSetFeCookie(t,e,s),hideAuthAndRegNotification(t),await preloadDataFe(t,e),await loadHomeCollections(t,e),await loadCurrentSubscriptions(t,e)},setAdvCakeData=(t,e=!0)=>{if(!wlDetector().isSmotreshka)return;if(!t){log$B.warn("Could not set Adv.Cake data; userId is undefined");return}const s=e?"авторизация":"регистрация";window.advcake_data=window.advcake_data||[],window.advcake_data.push({pageType:6,user:{email:t,type:""},leadInfo:{id:cookieStore.get(COOKIE_NAMES.advCake),name:s,totalPrice:"0",coupon:""}})},putAccountToStoreAndSetFeCookie=async(t,e,s)=>{var n;setFeCookie(s),await getAccount(t,e),setAdvCakeData((n=t.account.user)==null?void 0:n.id),resetCollections(t),removeAssetTokens(t)},getAccount=async(t,e,s)=>{const n={languageCode:t.languageCode,ctx:e};
4s&&(n.params={token:s});const i=await getAccount$1(n);i&&(t.account=i)},recheckAuthState=async(t,e)=>{var r,o,a;const{languageCode:s}=t,n=await getAccount$1({languageCode:s,ctx:e}),i=n==null?void 0:n.id;i&&i!==((r=t.account)==null?void 0:r.id)?(log$B.warn(`accountId mismatch. FE: ${i}, store: ${(o=t.account)==null?void 0:o.id}. Store account has been synced with FE`),await logout(t,e)):!i&&t.account&&t.feSessionId&&(log$B.warn(`accountId mismatch. FE: undefined, store: ${(a=t.account)==null?void 0:a.id}. Logging out`),await logout(t,e))},login=async(t,e,s,n)=>{const{languageCode:i}=t,o=await login$1({ctx:e,languageCode:i,data:{email:s,password:n}});o&&await reloadDataAfterLogin(t,e,o)},qrLogin=async(t,e,s)=>{const{languageCode:n}=t;resetCollections(t),removeAssetTokens(t),await qrLogin$1({ctx:e,languageCode:n,data:{code:s}}),await loadAssetTokens(t,e)},logout=async(t,e)=>{hideAllComplexNotifications(t),close(t),reset$1(t),localStorage.removeItem("tab"),cookieStore.set(COOKIE_NAMES.profileConfirmed,"0"),cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,"0"),cookieStore.remove(COOKIE_NAMES.profileConfirmationPeriod),clearFeCookie(),t.account=ACCOUNT_ANONYMOUS;const{languageCode:s}=t;await logout$1({ctx:e,languageCode:s}),window.location.href=makePath(t,"/")},getAvailableLogins=async(t,e)=>{const{languageCode:s}=t;t.availableLogins=await availableLogins({ctx:e,languageCode:s,params:{"contacts-session-token":t.verificationResult.sessionToken}})},loginWithVerifiedContacts=async(t,e,s)=>{const{languageCode:n}=t,i=await loginWithVerifiedContacts$1({ctx:e,languageCode:n,params:{"contacts-session-token":t.verificationResult.sessionToken},data:{login:s},timeout:3e4});await loadProviderInfo(t,e),i&&await reloadDataAfterLogin(t,e,i)},sendPassword=async(t,e,s)=>{const{languageCode:n}=t;await sendPassword$1({ctx:e,languageCode:n,params:{"contacts-session-token":t.verificationResult.sessionToken},data:{login:s}})},uztelAuth=async(t,e)=>{const{languageCode:s}=t,n=await uztelAuth$1({languageCode:s,ctx:e});n&&await reloadDataAfterLogin(t,e,n)},getTranslationForAuthAndRegTrial=(t,e)=>{var i;if(!((i=t.authAndReg)!=null&&i.trial))return"";const s=t.authAndReg.trial[e];if(!s)return"";const n=s==null?void 0:s.translationDict;return getByLanguage(n,t.languageCode,t.defaultLanguageCode)||`{${e}}`},autoLoginMegafon=async(t,e,s,n)=>{const{languageCode:i}=t,r={data:{token:n},ctx:e,languageCode:i},o=s===AUTO_LOGIN_MEGAFON_ROUTES_NAMES.autoLogin18p?await megafonAuthBy18pToken(r):await megafonAuthByToken(r);o&&await reloadDataAfterLogin(t,e,o)},authAndReg=Object.freeze(Object.defineProperty({__proto__:null,autoLoginMegafon,getAccount,getAvailableLogins,getTranslationForAuthAndRegTrial,login,loginWithVerifiedContacts,logout,qrLogin,recheckAuthState,sendPassword,setAdvCakeData,uztelAuth},Symbol.toStringTag,{value:"Module"})),log$A=logger$1("tokens-v2-actions"),updateIntervalSec=t=>{var s;const e=intervalSecSelector(t);(s=t.tokensV2)!=null&&s.regularUpdate&&e&&(t.tokensV2.regularUpdate.intervalSec=e<=0?1:e)},clearTokensTimeout=t=>{t.tokensV2.timeout&&(clearTimeout(t.tokensV2.timeout),t.tokensV2.timeout=null)},setTokensTimeout=(t,e)=>{var i,r;if(updateIntervalSec(t),!((r=(i=t.tokensV2)==null?void 0:i.regularUpdate)!=null&&r.intervalSec)){log$A.warn("Cannot set timeout for Tokens v2: regularUpdate.intervalSec is not set");return}clearTokensTimeout(t);const s=intervalSecSelector(t)||1,n=Math.floor(Math.random()*(s*2-s)+s);t.tokensV2.timeout=setTimeout(async()=>{t.tokensV2.loaded=!1,t.tokensV2.loading=!1,await updateAssetTokensV2(t,e)},n*1e3),log$A.info("Asset Tokens will be updated in",n,"seconds")},removeAssetTokens=t=>{hasTokensV2Selector(t)?(clearTokensTimeout(t),t.tokensV2.contextToken="",t.tokensV2.assetTokens=void 0,t.tokensV2.loaded=!1,t.tokensV2.loading=!1):(t.tokensV1.expiresAt="",cookieStore.remove(COOKIE_NAMES.analyticsToken),t.tokensV1.analyticsToken="",cookieStore.remove(COOKIE_NAMES.audienceToken),t.tokensV1.audienceToken="",cookieStore.remove(COOKIE_NAMES.tvAssetToken),t.tokensV1.tvAssetToken="",t.tokensV1.loaded=!1,t.tokensV1.loading=!1)},loadAssetTokens=async(t,e)=>{const s={ctx:e,languageCode:t.languageCode};hasTokensV2Selector(t)?await loadAssetTokensV2(t,s):await loadAssetTokensV1(t,s)},loadAssetTokensV2=async(t,e)=>{var n;if(loadedSelector(t))return log$A.info("Asset Tokens v2 were already loaded"),null;if(loadingSelector$1(t))return log$A.info("Asset Tokens v2 are already loading right now"),null;t.tokensV2.loading=!0;let s;try{s=await getAssetTokensV2(e),t.tokensV2.loaded=!0}catch{s=null,t.tokensV2.loaded=!1}finally{t.tokensV2.loading=!1}s===null||!((n=s==null?void 0:s.regularUpdate)!=null&&n.intervalSec)||(t.tokensV2.assetTokens=s.assetTokens,t.tokensV2.contextToken=s.contextToken,t.tokensV2.regularUpdate=s.regularUpdate,log$A.info("Asset Tokens v2 were successfully loaded"),setTokensTimeout(t,e))},updateAssetTokensV2=async(t,e)=>{var i;if(!hasTokensV2Selector(t))return null;const s=contextTokenSelector$1(t);if(!s){await loadAssetTokensV2(t,e);return}t.tokensV2.loading=!0;let n;try{n=await postAssetTokensV2(s,e),t.tokensV2.loaded=!0}catch(r){if(n=null,t.tokensV2.loaded=!1,r.code===HTTP_CODES.BAD_REQUEST){t.tokensV2.loading=!1,t.tokensV2.contextToken="",clearTokensTimeout(t),await loadAssetTokensV2(t,e);return}}finally{t.tokensV2.loading=!1}if(n){const r=n==null?void 0:n.contextToken,o=(i=n==null?void 0:n.regularUpdate)==null?void 0:i.etag;if(r&&r!==s&&o&&o!==etagSelector(t)){if(resetAllData(t,!1),t.tokensV2.assetTokens=n.assetTokens,t.tokensV2.contextToken=n.
4contextToken,t.tokensV2.regularUpdate=n.regularUpdate,await getAccount(t,e.ctx),await preloadDataFe(t,e.ctx),await loadHomeCollections(t,e.ctx),!isAnonymousSelector(t)&&(await loadCurrentSubscriptions(t,e.ctx),selectors.siteConfig.subscriptionShopEnabledSelector(t)))try{await loadShopSubscriptionOptions(t,e.ctx),await loadAvailableSubscriptionOptions(t,e.ctx)}catch(a){log$A.error(a)}}else log$A.info("contextToken or etag did not change, no need to update tokens' data")}setTokensTimeout(t,e)},tokensV2=Object.freeze(Object.defineProperty({__proto__:null,clearTokensTimeout,loadAssetTokens,loadAssetTokensV2,removeAssetTokens,setTokensTimeout,updateAssetTokensV2,updateIntervalSec},Symbol.toStringTag,{value:"Module"})),log$z=logger$1("tv-channels"),specialGenresList=[{id:"",title:TV_SPECIAL_GENRES.all},{id:"",title:TV_SPECIAL_GENRES.available},{id:"",title:TV_SPECIAL_GENRES.favourite},{id:"",title:TV_SPECIAL_GENRES.recentlyWatched},{id:"",title:TV_SPECIAL_GENRES.recommended}],getChannelsNotForPurchase=async(t,e)=>{isAnonymousSelector(t)||(t.tvChannels.channelsNotForPurchase=await getChannelsNotForPurchase$1({languageCode:t.languageCode,ctx:e}))},setChannelsLoaded=(t,e)=>{t.tvChannels.loaded=e},setChannelsLoading=(t,e)=>{t.tvChannels.loading=e},setChannelsRecentAndFavLoaded=(t,e)=>{t.tvChannels.recentAndFavLoaded=e},setChannelsRecentAndFavLoading=(t,e)=>{t.tvChannels.recentAndFavLoading=e},loadTvData=async(t,e)=>{if(t.flags.tvDataState.loaded){log$z.info("TV data has already been loaded");return}if(t.flags.tvDataState.loading){log$z.warn("TV data is already loading right now...");return}const s=Date.now();t.flags.tvDataState.loading=!0,setChannelsLoading(t,!0),tvAssetTokenSelector(t)||await loadAssetTokens(t,e),await getChannelsNotForPurchase(t,e);const{genresResponse:n,channelsResponse:i,recommendedChannelsResponse:r}=await getTvData(t.languageCode,e,tvAssetTokenSelector(t));t.tvChannels.genres=[...specialGenresList,...n],t.tvChannels.list=i,t.tvChannels.recommended=r,t.flags.tvDataState.loading=!1,t.flags.tvDataState.loaded=!0,setChannelsLoading(t,!1),setChannelsLoaded(t,!0),await loadRecentAndFavChannels(t,e),log$z.info(`All TV data has been loaded - ${Date.now()-s}ms`)},loadChannelsAndGenres=async(t,e,s="")=>{if(channelsLoadedSelector(t)||channelsLoadingSelector(t))return;setChannelsLoading(t,!0),!tvAssetTokenSelector(t)&&wlDetector().isSmotreshka&&await loadAssetTokens(t,e);const n=await getChannels({languageCode:t.languageCode,ctx:e,params:{session:s},tvAssetToken:tvAssetTokenSelector(t)}).then(i=>(setChannelsLoaded(t,!0),i)).catch(i=>(log$z.error(i),{channels:{},genres:[]})).finally(()=>{setChannelsLoading(t,!1)});t.tvChannels.list=(n==null?void 0:n.channels)||[],log$z.info("TV channels have been loaded"),n!=null&&n.genres.length&&(t.tvChannels.genres=[...n.genres,...specialGenresList],log$z.info("TV genres have been loaded"))},resetChannels=t=>{t.tvChannels.list={}},loadRecentAndFavChannels=async(t,e)=>{if(channelsRecentAndFavLoadedSelector(t)||channelsRecentAndFavLoadingSelector(t))return;setChannelsRecentAndFavLoading(t,!0);const s=await getRecentAndFavChannels({languageCode:t.languageCode,ctx:e});t.tvChannels.favorites=(s==null?void 0:s.favouriteChannels)||{},t.tvChannels.recentlyWatched=(s==null?void 0:s.recentlyWatchedChannels)||{},setChannelsRecentAndFavLoading(t,!1),setChannelsRecentAndFavLoaded(t,!0),log$z.info("Recent and favorite channels were loaded")},resetRecentAndFavChannels=t=>{setChannelsRecentAndFavLoaded(t,!1),setChannelsRecentAndFavLoading(t,!1),t.tvChannels.favorites={},t.tvChannels.recentlyWatched={}},loadRecommendedChannels=async(t,e)=>{t.tvChannels.recommended=await getRecommendedChannels({languageCode:t.languageCode,ctx:e})},resetRecommendedChannels=t=>{t.tvChannels.recommended={}},updateRecentlyWatched=debounce((t,e)=>{const s=recentlyWatchedSelector(t);s[e]&&(deleteFromObject(e,s),t.tvChannels.recentlyWatched=s),t.tvChannels.recentlyWatched={[e]:getChannelById(allChannelsSelector(t),e),...s}},THRESHOLDS.tv.channelSwitchDelay,{leading:!1,trailing:!0}),loadPlaybackInfoDetails=async(t,e,s,n=!0)=>{var a,l,c,d,u;const i=s==null?void 0:s.id,r=(a=s==null?void 0:s.medias)==null?void 0:a[0].id;if(!((l=Object.keys(t.tvChannels.list))!=null&&l.length&&i&&r)){log$z.error(`Unable to load playbackInfo details: invali
4d channel #${i}`,s);return}log$z.info("loading playbackInfo details for channel",i),(d=(c=t.tvChannels)==null?void 0:c.list)!=null&&d[i]&&(t.tvChannels.list[i].playbackInfoLoaded=!1);const o=await getPlaybackInfoMedia({ctx:e,languageCode:t.languageCode,enable50fps:fps50Selector(t),languageIndex:defaultLanguageIndexSelector(t),renditionIndex:defaultRenditionIndexSelector(t),mediaId:r}).catch(h=>{throw h instanceof ApiError?h.resStatus===HTTP_CODES.FORBIDDEN?log$z.info(h.reqInfo):log$z.error(h.reqInfo):log$z.error(h),h});if(o&&(clearError(t),t.tvChannels.list[i].info={playbackInfo:o},log$z.info("playbackInfo have been loaded",o)),(!Array.isArray(o==null?void 0:o.languages)||!((u=o==null?void 0:o.languages)!=null&&u.length))&&log$z.error("Invalid playbackInfo: languages were not found"),!isDvrDisabled(s)&&isDvrRestricted(s)){log$z.warn("DVR is restricted for channel",i,"Loading dvrAvailability...");const h=await getDvrAvailability(i,{languageCode:t.languageCode,ctx:e});log$z.info("dvrAvailability has been loaded",h),o&&h&&(o.dvrAvailability=h),t.tvChannels.list[i].info.playbackInfo.dvrAvailability=h,i===playingChannelIdSelector(t)&&t.player.playbackInfo.smotreshkaPlaybackInfo&&h&&(t.player.playbackInfo.smotreshkaPlaybackInfo.dvrAvailability=h,n&&!isVisibleSelector(t)&&showDvrRestrictionNotification(t))}o&&setPlaybackInfoSmotreshka(t,o),restoreLanguageSettings(t,s),restoreChannelSettings(t,s),log$z.info("loadPlaybackInfoDetails – DVR status",{isDvrDisabled:isDvrDisabled(s),isDvrRestricted:isDvrRestricted(s)}),t.tvChannels.list[i].playbackInfoLoaded=!0},restoreLanguageSettings=(t,e=playingChannelSelector(t))=>{var i,r,o,a,l;const s=languagesSelector(t),n=storage.get(STORE_KEYS.player.audioTrackTv);if((i=e==null?void 0:e.info)!=null&&i.playbackInfo){let c=s.findIndex(u=>u.id===n);c<0&&(c=s.findIndex(u=>u.default));const d=(l=(a=(o=(r=t.tvChannels)==null?void 0:r.list)==null?void 0:o[e==null?void 0:e.id])==null?void 0:a.info)==null?void 0:l.playbackInfo;d&&(d.languageIndex=-1),t.player.playbackInfo.smotreshkaPlaybackInfo&&(e==null?void 0:e.id)===playingChannelIdSelector(t)&&(t.player.playbackInfo.smotreshkaPlaybackInfo.languageIndex=c),log$z.info("restoreLanguageSettings",n,"languageIndex",c)}},restoreChannelSettings=(t,e=playingChannelSelector(t))=>{var c,d,u,h;if(!(e!=null&&e.id)){log$z.warn("channel ID was not passed");return}const n=(storage.get(STORE_KEYS.player.channelsSettings)||{})[e.id]||{};if(!languagesSelector(t).length)return log$z.error("Languages have not been loaded. Has loadPlaybackInfoDetails been called?");const r=languageSelector(t);let o=defaultRenditionIndexSelector(t);const a=r==null?void 0:r.renditions;a&&n.renditionIndex&&a[n.renditionIndex]&&(o=n.renditionIndex);const l=(h=(u=(d=(c=t.tvChannels)==null?void 0:c.list)==null?void 0:d[e==null?void 0:e.id])==null?void 0:u.info)==null?void 0:h.playbackInfo;l&&(l.renditionIndex=-1),t.player.playbackInfo.smotreshkaPlaybackInfo&&(t.player.video.scaled=!!n.isVideoScaled,t.player.playbackInfo.smotreshkaPlaybackInfo.renditionIndex=o),log$z.info("restoreChannelSettings",{renditionIndex:o,expand:isVideoScaledSelector(t)})},selectGenre=(t,e)=>{t.tvChannels.currentGenre=e,log$z.info("selectGenre",e)},resetGenre=t=>{selectGenre(t,TV_SPECIAL_GENRES.recommended),localStore.set("genre",TV_SPECIAL_GENRES.recommended),log$z.info("resetGenre to DEFAULT = __RECOMMENDED__")},toggleChannelFavorite=async(t,e,s)=>{const n=!!favoritesSelector$1(t)[s];n?await removeFromFavorites$1(s,{languageCode:t.languageCode,ctx:e}):await addToFavorites$1(s,{languageCode:t.languageCode,ctx:e}),gaEvent({...gaParamsSelector(t),action:n?"Удалить из избранного":"Добавить в избранное",channel_name:s,control_type:"mouse"},t);const{favouriteChannels:i}=await getRecentAndFavChannels({languageCode:t.languageCode,ctx:e});t.tvChannels.favorites=i||[],await showFavoriteNotification(t,"tv",!n,getChannelTitle(channelByIdSelector(t,s||"")))},setChannelMetaTitle=(t,e,s=!0)=>{setMetaTitle(t,buildChannelMetaTitle(t,e,s))},buildChannelMetaTitle=(t,e,s=!0)=>{const n=`channel_${s?"about":"epg"}_meta_title`;return(getByLanguage(t.translations[n],t.languageCode,t.defaultLanguageCode)||n).replace(/%channelName%/g,getChannelTitle(channelByIdSelector(t,e))||"")},setChannelsCatalogMetaTitle=(t,e)=>{setMetaTitle(t,buildChannelsCatalogMetaTitle(t,e))},buildChannelsCatalogMetaTitle=(t,e)=>{const s=`tv_${e?"now":"list"}_meta_title`;return getByLanguage(t.translations[s],t.languageCode,t.defaultLanguageCode)||s},loadExternalPlayerSettings=async(t,e)=>{var i;audienceTokenSelector(t)||await loadAssetTokens(t,e);const s=audienceTokenSelector(t),n=tvAssetTokenSelector(t);try{const r=await getExternalPlayerSettings({languageCode:t.languageCode,ctx:e,params:{"audience-token":s,"tv-asset-token":n}});r&&(t.tvChannels.clientPlatform=r.clientPlatform,t.tvChannels.settings=((i=r.channels)==null?void 0:i.reduce((o,a)=>(o[a.channelId]=a.playerParams.reduce((l,c)=>(l[c.name]=c.value,l),{}),o),{}))||{})}catch(r){log$z.error(r)}},tvChannels=Object.freeze(Object.defineProperty({__proto__:null,buildChannelMetaTitle,buildChannelsCatalogMetaTitle,getChannelsNotForPurchase,loadChannelsAndGenres,loadExternalPlayerSettings,loadPlaybackInfoDetail
4s,loadRecentAndFavChannels,loadRecommendedChannels,loadTvData,resetChannels,resetGenre,resetRecentAndFavChannels,resetRecommendedChannels,restoreChannelSettings,restoreLanguageSettings,selectGenre,setChannelMetaTitle,setChannelsCatalogMetaTitle,setChannelsLoaded,setChannelsLoading,setChannelsRecentAndFavLoaded,setChannelsRecentAndFavLoading,toggleChannelFavorite,updateRecentlyWatched},Symbol.toStringTag,{value:"Module"})),log$y=logger$1("profile"),setCurrentAction=(t,e)=>{t.profiles.currentAction=e},setIdToDlete=(t,e)=>{t.profiles.profileIdToDelete=e},setIsProfileLoading=(t,e)=>{log$y.info("isProfileLoading",e),t.profiles.isProfileLoading=e},setIsProfileLoaded=(t,e)=>{log$y.info("isProfileLoaded",e),t.profiles.isProfileLoaded=e},setProfileSelected=(t,e)=>{t.profiles.profileSelected=e},reloadData=async(t,e)=>{if(t.qs.subscriptionShop.isLoading=!0,hideProfileAction(t),resetAllData(t),await preloadDataFe(t,e),await loadHomeCollections(t,e),!isAnonymousSelector(t)){if(await getAccount(t,e),await loadCurrentSubscriptions(t,e),selectors.siteConfig.subscriptionShopEnabledSelector(t))try{await loadShopSubscriptionOptions(t,e),await loadAvailableSubscriptionOptions(t,e)}catch(s){log$y.error(s)}await loadVodPauses(t,e)}await loadAssetTokens(t,e),t.qs.subscriptionShop.isLoading=!1},change=async(t,e,s)=>{setIsProfileLoading(t,!0),setIsProfileLoaded(t,!1);try{await change$1({languageCode:t.languageCode,ctx:e,...s}),await reloadData(t,e),t.account.profile=t.account.profiles.find(n=>n.id===(s==null?void 0:s.data.Id)),unlockBodyScroll(t)}finally{setIsProfileLoaded(t,!0),setIsProfileLoading(t,!1)}},update=async(t,e,s,n)=>{var i,r,o,a;setIsProfileLoaded(t,!1),setIsProfileLoading(t,!0),await update$1(s,{languageCode:t.languageCode,ctx:e,...n}),s===((r=(i=t.account)==null?void 0:i.profile)==null?void 0:r.id)&&
4((a=(o=t.account)==null?void 0:o.profile)==null?void 0:a.restriction)!==(n==null?void 0:n.data["Restriction.Id"])&&await reloadData(t,e),setIsProfileLoading(t,!1),setIsProfileLoaded(t,!0),unlockBodyScroll(t)},getProfileRestrictions=async(t,e)=>{t.profileRestrictions=await getProfileRestrictions$1({languageCode:t.languageCode,ctx:e})},changeProfileWithoutPin=async(t,e,s)=>{await change(t,e,{data:{Id:s.id,Pin:""}})},profiles$1=Object.freeze(Object.defineProperty({__proto__:null,change,changeProfileWithoutPin,getProfileRestrictions,setCurrentAction,setIdToDlete,setIsProfileLoaded,setIsProfileLoading,setProfileSelected,update},Symbol.toStringTag,{value:"Module"})),log$x=logger$1("promo-elements"),preparePromoElements=(t,e)=>{let s=e.filter(l=>!!l.renderingMethods.find(({method:c})=>BANNER_RENDERING_METHODS.includes(c)));s=s.map(l=>{const c=l.actionMethods.filter(d=>{var h,f,g;const u=(h=l.internalReference)==null?void 0:h.vodContent;return d.method===PROMO_ELEMENTS_ACTION_METHODS.internalRef&&u?listOfAllSourceIdsSelector(t).includes(u.source)&&((g=(f=l.internalReference)==null?void 0:f.screenId)==null?void 0:g.startsWith("vod-")):!0});return{...prepareImages(l),renderingMethods:sortByPriority(l.renderingMethods),actionMethods:sortByPriority(c),internalUrl:getUrlByInternalRef(l)}}),s=s.filter(l=>l.actionMethods.length);const n=l=>!!l.renderingDataJson&&l.renderingMethods.find(c=>Object.values(BANNER_VIDEO_RENDERING_METHODS_NAMES).includes(c.method)),i=l=>l.renderingMethods.find(c=>BANNER_RENDERING_METHODS_NAMES.plainImage===c.method),r=l=>{var d;const c=(d=l.renderingMethods.sort((u,h)=>u.priority-h.priority)[0])==null?void 0:d.method;return[BANNER_RENDERING_METHODS_NAMES.plainImage1x1,BANNER_RENDERING_METHODS_NAMES.plainImage16x9,BANNER_RENDERING_METHODS_NAMES.plainPoster].includes(c)},o=l=>l.renderingMethods.find(c=>BANNER_RENDERING_METHODS_NAMES.textButton===c.method);s=enhanceWithInternalUrl(s);const a=s.reduce((l,c)=>{let d=PROMO_ELEMENTS_PLACEMENT_BLOCKS.default;return c.placementBlocks?c.placementBlocks.forEach(({blockId:u,priority:h})=>{(n(c)||i(c)||r(c)||o(c))&&(d=u,c.priority=h,l[d]=l[d]||[],l[d].push(c))}):(l[d]=l[d]||[],l[d].push(c)),l},{});return Object.entries(a).reduce((l,[c,d])=>(l[c]=d.sort((u,h)=>(u.priority||0)-(h.priority||0)),l),{})},prepareImages=t=>{var s;const e={...t};return(s=t.images)==null||s.forEach(n=>{switch(n.imageType){case"plain-1x1":e.plainImage1x1=n.imageURL;break;case"plain-16x9":e.plainImage16x9=n.imageURL;break;case"plain-16x4":e.plainImage16x4=n.imageURL;break;case"background-16x9":e.background16x9=n.imageURL;break;case"poster-7x10":e.plainPoster=n.imageURL;break;case"title-logo-15x4":e.titleLogo15x4=n.imageURL;break;case"source-icon-3x2":e.sourceIcon3x2=n.imageURL;break}}),e},loadPromoElements=async(t,e)=>{audienceTokenSelector(t)||await loadAssetTokens(t,e);const s=audienceTokenSelector(t),n=await getPromoElements(s,{languageCode:t.languageCode,ctx:e}),i=n.length;if(!i){log$x.info("Promo elements loaded: 0"),t.promoElements.isBannersDataLoaded=!0;return}t.promoElements.items=preparePromoElements(t,n),t.promoElements.isBannersDataLoaded=!0,log$x.info("Promo elements loaded:",i)},log$w=logger$1("home-actions"),loadBanners=async(t,e)=>{if(isBannersDataLoadingSelector(t)){log$w.info("Banners are already loading...");return}if(isBannersDataLoadedSelector(t)){log$w.debug("Banners have already been loaded");return}t.promoElements.isBannersDataLoading=!0,await loadPromoElements(t,e),t.promoElements.isBannersDataLoading=!1},home=Object.freeze(Object.defineProperty({__proto__:null,loadBanners},Symbol.toStringTag,{value:"Module"})),log$v=logger$1("server-utils"),empty=t=>!(t&&t.length),prepareContentBlock=(t,e)=>empty(t)?{}:e==null?void 0:e[t],prepareTranslation=(t,e)=>empty(t)?{}:e[t];function prepareComponents(t,e,s){var i,r;const n={};for(const o of t){const{type:a,componentName:l}=o;if(!a||!l){log$v.error("Cannot proceed preparing the component. Invalid (empty) type or componentName",o);continue}const c=cloneDeep(o.content);if(a===COMPONENT_TYPES.Advantages)c.contentBlock=prepareContentBlock(c.contentBlockId,s),Array.isArray(c.advantages)?c.advantages.forEac
4h(d=>{d.contentBlock=prepareContentBlock(d.contentBlockId,s),d.image=prepareFileRecord$1(d.imageId,e)}):log$v.error("advantage is not an array. advantage:",c.advantage);else if(a===COMPONENT_TYPES.BackgroundWithText)c.contentBlock=prepareContentBlock(c.contentBlockId,s),c.image=prepareFileRecord$1(c.imageId,e);else if(a===COMPONENT_TYPES.ButtonFileDownload)c.file=prepareFileRecord$1(c.fileId,e);else if(a===COMPONENT_TYPES.Device)c.image=prepareFileRecord$1(c.imageId,e),c.contentBlock=prepareContentBlock(c.contentBlockId,s);else if(a===COMPONENT_TYPES.Accordion)for(const d of c.items)d.contentBlock=prepareContentBlock(d.contentBlockId,s);else if(a===COMPONENT_TYPES.HowToWatch)Array.isArray(c.steps)?c.steps.forEach(d=>{d.contentBlock=prepareContentBlock(d.contentBlockId,s),d.image=prepareFileRecord$1(d.imageId,e)}):log$v.error(`Component HowToWatch#${l} steps is not an array. steps:`+c.steps);else if(a===COMPONENT_TYPES.ImageSlider)for(const d of c.images)d.image=prepareFileRecord$1(d.imageId,e);else if(a===COMPONENT_TYPES.ImageTextButton)c.image=prepareFileRecord$1(c.imageId,e),c.contentBlock=prepareContentBlock(c.contentBlockId,s);else if(a===COMPONENT_TYPES.TextOnly)c.contentBlock=prepareContentBlock(c.contentBlockId,s);else if(a===COMPONENT_TYPES.TvWizard)c.imageLight=prepareFileRecord$1((i=c.imageLight)==null?void 0:i.imageId,e),c.imageDark=prepareFileRecord$1((r=c.imageDark)==null?void 0:r.imageId,e),c.SamsungInstructions=prepareContentBlock(c.SamsungInstructions,s),c.LGInstructions=prepareContentBlock(c.LGInstructions,s),c.AndroidInstructions=prepareContentBlock(c.AndroidInstructions,s),c.UnavailableInstructions=prepareContentBlock(c.UnavailableInstructions,s);else if(a===COMPONENT_TYPES.AboutPage){c.backgroundLight=prepareFileRecord$1(c.backgroundLight,e),c.backgroundDark=prepareFileRecord$1(c.backgroundDark,e);for(const d of c.banners){const u=t.find(h=>h.componentName===d.bannerName);u?d.content=u.content:d.content=null}}else a===COMPONENT_TYPES.Banner&&(c.iconTop=prepareFileRecord$1(c.iconTop,e),c.iconBottom=prepareFileRecord$1(c.iconBottom,e));n[o.componentName]={...o,content:c}}return n}const getPageMeta=(t,e,s,n,i,r)=>{const o=n.common,a=n.socialMeta,l=(t==null?void 0:t.meta)||{},c=(t==null?void 0:t.socialMeta)||{},d=E=>E?getByLanguage(prepareTranslation(E,r),e,s):"",u=E=>{var L;return E&&((L=getByLanguage(prepareFileRecord$1(E,i),e,s))==null?void 0:L.url)||null},h=d(l.titleTrKey)||d(t.title)||d(o.title)||t.title||"Sequoia",f=d(l.descriptionTrKey||o.description),g=d(l.keywordsTrKey||o.keywords),p=d(c.titleTrKey||a.title),m=d(c.descriptionTrKey||a.description),v=u(c.ogFileKey||a.og),S=u(c.vkFileKey||a.vk),y=[`<title>${h}</title>`],C={ogFileKey:v||"",vkFileKey:S||""};return f&&y.push(`<meta name="description" content="${f}">`),g&&y.push(`<meta name="keywords" content="${g}">`),p&&y.push(`<meta property="og:title" content="${p}"/>`),m&&y.push(`<meta property="og:description" content="${m}"/>`),v&&y.push(`<meta property="og:image" content="${v}"/>`),S&&y.push(`<meta property="vk:image" content="${v}"/>`),{title:h,head:y.join(`
5`),metaImages:C}};function generateCmsPagesForRouter(t,e,s,n,i,r){return t.map(o=>{const{_id:a,content:l,...c}=o;return{path:o.path,component:{name:`page__${a}`,exact:o.path==="/",template:l},dataObject:{appContainer:null,page:c,...getPageMeta(o,e,s,n,i,r)}}})}const processSiteConfig=async(t,e)=>{var s,n,i,r,o,a;if(!t)return t;if(t.loader){t.loader=prepareFileRecord$1(t.loader,e);const l=[];for(const u in t.loader)Object.getOwnPropertyDescriptor(t,u)&&l.push(fetchLoaderData(t.loader[u].url).catch(h=>{log$v.error("fetchLoaderData ->",h)}));const c=await Promise.all(l).catch(()=>"");let d=0;for(const u in t.loader)Object.getOwnPropertyDescriptor(t,u)&&(t.loader[u].data=c[d],d++)}return t.appStores||(t.appStores={links:{android:"",ios:"",default:""},patha:"",scheme:""}),(s=t.smartAppBanner)!=null&&s.icon&&(t.smartAppBanner.icon=prepareFileRecord$1(t.smartAppBanner.icon,e)),(n=t.genreIconDefault)!=null&&n.imageId&&(t.genreIconDefault=prepareFileRecord$1(t.genreIconDefault.imageId,e)),(i=t.genreIcons)==null||i.forEac
5h((l,c)=>{t.genreIcons[c].image=prepareFileRecord$1(l.imageId,e)}),(r=t.logo)!=null&&r.light&&(t.logo.light=prepareFileRecord$1(t.logo.light,e)),(o=t.logo)!=null&&o.dark&&(t.logo.dark=prepareFileRecord$1(t.logo.dark,e)),(a=t.vodMegaCollections)!=null&&a.length&&t.vodMegaCollections.forEach(l=>{l.smallBanner=prepareFileRecord$1(l.smallBannerId,e),l.bigBanner=prepareFileRecord$1(l.bigBannerId,e)}),t},log$u=logger$1("app-sections"),loadAppSections=async(t,e)=>{var n;const s=audienceTokenSelector(t);try{const i=await getAppSections(s,{languageCode:t.languageCode,ctx:e}).catch(()=>null);t.appSections.sections=((n=i==null?void 0:i.customSections)==null?void 0:n.filter(r=>r.renderingMethods.includes(SUPPORTED_SECTION_RENDERING_METHODS.verticalBlockV1)).map(r=>{var o;return{...r,blocks:(o=r==null?void 0:r.blocks)==null?void 0:o.map(a=>({...a,blockSettings:JSON.parse(a.blockSettingsJson)})),sectionSettings:JSON.parse(r.sectionSettingsJson)}}))||[]}catch(i){log$u.error(i)}},appSections=Object.freeze(Object.defineProperty({__proto__:null,loadAppSections},Symbol.toStringTag,{value:"Module"})),loadFiles=async t=>{t.fileRecords={items:await getAllFiles()}},log$t=logger$1("common-actions"),actualizeLocalTime=t=>{t.common.localTime=Date.now()},setNeedServerTimeSync=(t,e)=>{t.common.needServerTimeSync=e},setIsOffline=(t,e)=>{t.common.isOffline=e},setHeaderAboveContent=(t,e)=>{t.common.isHeaderAboveContent=e},makeHeaderTransparent=t=>{t.common.isHeaderTransparent=!0},makeHeaderOpaque=t=>{t.common.isHeaderTransparent=!1},loadTranslations=async t=>{t.translations=await getAllTranslations()},loadSiteConfig=async t=>{const e=await getSiteConfig();t.siteConfig=await processSiteConfig(e,t.fileRecords.items)},loadPages=async(t,e)=>{if(!t.siteConfig){log$t.error("empty siteConfig");return}const s=await getAllPages(),n={};if(s!=null&&s.pages){for(const i of e)n[i.code]=generateCmsPagesForRouter(s==null?void 0:s.pages,i.code,t.defaultLanguageCode,t.siteConfig,t.fileRecords.items,t.translations);t.cmsPages=n[t.languageCode]||[]}},loadComponents=async(t,e)=>{const s=await getAllComponents();t.components=s?prepareComponents(s,t.fileRecords.items,e):{}},loadSeoRules=async t=>{const e=await getSeoRules();t.seoRules=e||{}},preloadData=async(t,e,s="")=>{var c,d,u,h,f;if((e==null?void 0:e.baseUrl)==="/provider"||s==="/provider")return;const n=Date.now(),[i,r]=await preloadDataBefore(t,e);await preloadDataMain(t,e,s,i),await preloadDataAfter(t,e,r);const o=t.appSections.sections.find(g=>g.sectionId==="home_screen"),a=!!((d=(c=t.homeScreenConfig)==null?void 0:c.config_list)!=null&&d.find(({key:g})=>g===PROMO_ELEMENTS_PLACEMENT_BLOCKS.homeCarouselV2))&&!!((u=t.promoElements.items[PROMO_ELEMENTS_PLACEMENT_BLOCKS.homeCarouselV2])!=null&&u.length)&&(!o||((h=o.blocks.filter(g=>g.renderingMethods.includes("promo-carousel-v2")))==null?void 0:h.length)),l=t.languageCode!==((f=r.find(g=>g.isDefault))==null?void 0:f.code)?`/${t.languageCode}`:"";
5(s===l||s==="/adult")&&a&&(makeHeaderTransparent(t),setHeaderAboveContent(t,!0)),log$t.debug(`preloadData - ${Date.now()-n}ms`)},preloadDataFe=async(t,e,s=!0)=>{await loadAssetTokens(t,e);const n=[loadAppInfo(t,e),loadSources(t,e),getProfileRestrictions(t,e),loadTvData(t,e),loadExternalPlayerSettings(t,e),loadAppSections(t,e),loadFavorites(t,e)];await Promise.all(n),s&&await loadBanners(t,e).catch(i=>{log$t.error(i)})},preloadDataBefore=async(t,e)=>{const s=await Promise.all([new Promise(n=>{n(getAllContentBlocks())}),new Promise(n=>{n(getLanguages())}),getAccount(t,e),new Promise(n=>{n(loadFiles(t))}),new Promise(n=>{n(loadTranslations(t))}),new Promise(n=>{n(loadSeoRules(t))})]);return await new Promise(n=>{n(loadSiteConfig(t))}),s},preloadDataMain=async(t,e,s="",n=null)=>{const i=getFeCookie(e);(i==null?void 0:i.session)===""&&!isAnonymousSelector(t)&&(clearFeCookie(),t.account=ACCOUNT_ANONYMOUS);const r=[new Promise(o=>{o(loadComponents(t,n))}),preloadDataFe(t,e,s!=="/provider")];await Promise.all(r)},preloadDataAfter=async(t,e,s)=>{const n=[new Promise(i=>{i(loadPages(t,s))})];isAnonymousSelector(t)||n.push(loadPopupNotices(t,e).catch(()=>{})),await Promise.all(n)},resetAllData=(t,e=!0)=>{log$t.info("resetAllData was triggered"),t.account.profile=void 0,t.flags.tvDataState.loaded=!1,t.promoElements.items={},t.promoElements.isBannersDataLoaded=!1,t.vod.states.recommendationsLoaded=!1,t.qs.shopSubscriptions=[],t.qs.availableSubscriptions=[],resetGenre(t),resetPauses(t),setChannelsLoaded(t,!1),resetChannels(t),resetRecentAndFavChannels(t),resetRecommendedChannels(t),resetFavorites(t),e&&resetSources(t),resetCurrentCategoryId(t),resetCollections(t),removeAssetTokens(t)},resetHowManyTimesBodyScrollWasLocked=t=>{var e;t.common.bodyScrollLockCount=0,(e=document==null?void 0:document.body)==null||e.classList.remove("locked-scroll")},lockBodyScroll=t=>{var e,s;t.common.bodyScrollLockCount++,(e=document==null?void 0:document.body)!=null&&e.classList.contains("locked-scroll")||(s=document==null?void 0:document.body)==null||s.classList.add("locked-scroll")},unlockBodyScroll=t=>{var e;bodyScrollLockCountSelector(t)>0&&t.common.bodyScrollLockCount--,bodyScrollLockCountSelector(t)<=0&&((e=document==null?void 0:document.body)==null||e.classList.remove("locked-scroll"))},common=Object.freeze(Object.defineProperty({__proto__:null,actualizeLocalTime,loadSiteConfig,loadTranslations,lockBodyScroll,makeHeaderOpaque,makeHeaderTransparent,preloadData,preloadDataFe,resetAllData,resetHowManyTimesBodyScrollWasLocked,setHeaderAboveContent,setIsOffline,setNeedServerTimeSync,unlockBodyScroll},Symbol.toStringTag,{value:"Module"})),loadAppInfo=async(t,e)=>{var s;try{t.appInfo=await getAppInfo({languageCode:t.languageCode,ctx:e}),(s=t.appInfo)!=null&&s.currentTime&&(t.common.serverTime=t.appInfo.currentTime)}catch{}},incrementServerTime=t=>{var e;if((e=t.appInfo)!=null&&e.currentTime){const s=Date.now()-t.common.localTime,i=dayjs().unix()-t.common.serverTime;(s<0||s>convertToMilliseconds(10,"minute"))&&setNeedServerTimeSync(t,!0),t.common.localTime+=s,t.appInfo.currentTime+=Math.round(convertToSeconds(s,"millisecond")),i>=60&&(t.common.serverTime=t.appInfo.currentTime)}},appInfo=Object.freeze(Object.defineProperty({__proto__:null,incrementServerTime,loadAppInfo},Symbol.toStringTag,{value:"Module"})),getCurrentBrandingMethods=(t,e)=>{var i,r,o;const s=(i=e.sort((a,l)=>(a==null?void 0:a.priority)-(l==null?void 0:l.priority))[0])==null?void 0:i.name,n=(r=t.brandingMethods)==null?void 0:r.find(a=>a.customId===BRANDING_METHODS_DEFAULT);if(!s)return n==null?void 0:n.options;if(s&&t.brandingMethods&&t.brandingMethods.length>0){const a=(o=t.brandingMethods)==null?void 0:o.find(l=>l.customId===s);return a?a==null?void 0:a.options:n==null?void 0:n.options}return[]},brandingMethods=Object.freeze(Object.defineProperty({__proto__:null,getCurrentBrandingMethods},Symbol.toStringTag,{value:"Module"})),setGaParams=(t,e)=>{t.gaParams={...t.gaParams,...e}},metrics=Object.freeze(Object.defineProperty({__proto__:null,setGaParams},Symbol.toStringTag,{value:"Module"})),log$s=logger$1("packages"),loadPackages=async(t,e,s)=>{if(!t.packages.items.length){const n=await getPackages()||{items:[]};t.packages.items=await Promise.all(n.items.filter(i=>i.page===s).map(async i=>{var c;const r=await getOfferShowcaseChannels(i.id,{ctx:e,languageCode:t.languageCode}).catch(d=>{log$s.error("getOfferChannels:",d)}),o=r==null?void 0:r.channels,a=await getOffer(i.id,{ctx:e,languageCode:t.languageCode}).catch(d=>{log$s.error("getOffer:",d)}),l=((c=a==null?void 0:a.preview)==null?void 0:c.price)||"";return{...i,price:!l||l==="0"?"":l,channels:o||[]}}))}},packages=Object.freeze(Object.defineProperty({__proto__:null,loadPackages},Symbol.toStringTag,{value:"Module"})),log$r=logger$1("player-playing-channel"),setLanguageIndex=(t,e)=>{if(!t.player.playbackInfo.smotreshkaPlaybackInfo){log$r.error("setLanguageIndex","invali
5d Smotreshka playbackInfo");return}t.player.playbackInfo.smotreshkaPlaybackInfo.languageIndex=e,setRenditionIndex(t,0),log$r.info("setLanguageIndex",e),saveLanguageSettings(t)},setRenditionIndex=(t,e)=>{if(!t.player.playbackInfo.smotreshkaPlaybackInfo){log$r.error("setRenditionIndex","invalid Smotreshka playbackInfo");return}t.player.playbackInfo.smotreshkaPlaybackInfo.renditionIndex=e,log$r.info("setRenditionIndex",e),saveChannelSettings(t)},markPlayingLanguageAsUnavailable=t=>{const e=languagesSelector(t),s=languageIndexSelector(t);log$r.info("Mark as unavailable language with index = ",s),e[s]&&(e[s].unavailable=!0)},unmarkPlayingLanguageAsUnavailable=t=>{const e=languagesSelector(t),s=languageIndexSelector(t);log$r.info("Remove unavailable language mark with index = ",s),e[s]&&(e[s].unavailable=void 0)},togglePlayingChannelFavorite=async(t,e)=>{const s=playingChannelIdSelector(t);s&&await toggleChannelFavorite(t,e,s)},saveLanguageSettings=t=>{const e=languageSelector(t);storage$1.set(STORE_KEYS.player.audioTrackTv,e.id),log$r.info("saveLanguageSettings",e.id)},saveChannelSettings=t=>{const e=playingChannelIdSelector(t);if(!e)return;const s=storage$1.get(STORE_KEYS.player.channelsSettings)||{},n=s[e]||{};n.isVideoScaled=isVideoScaledSelector(t),n.renditionIndex=renditionIndexSelector(t),s[e]=n,storage$1.set(STORE_KEYS.player.channelsSettings,s),log$r.info("saveChannelSettings",n)},playerPlayingChannel=Object.freeze(Object.defineProperty({__proto__:null,markPlayingLanguageAsUnavailable,setLanguageIndex,setRenditionIndex,togglePlayingChannelFavorite,unmarkPlayingLanguageAsUnavailable},Symbol.toStringTag,{value:"Module"})),hasAcquiringSelector=t=>{const e=allSubscriptionsOptionsTypeBaseSelector(t);return e&&e.length>0&&!isAutoTrialStatusUnknownSelector(t)&&!isAutoTrialStatusProcessStartedSelector(t)&&!wasAutoTrialCreatedSelector(t)},offersSelector=t=>{const e=["qs21-yakassa","qs20-tv-default","qs10-legacy-default"],s=allSubscriptionsSelector(t);if(!(s!=null&&s.subscriptionOptions))return[];const n=s.subscriptionOptions.filter(({renderingMethods:i})=>!!i.find(r=>e.includes(r.name)));return prepareSubscriptionOptions(n,t)},promoOffersSelector=t=>{const e=promoCodeSubscriptionsSelector(t);return e!=null&&e.subscriptionOptions?prepareSubscriptionOptions(e.subscriptionOptions,t):[]},prepareSubscriptionOptions=(t,e)=>t.map(s=>{var i,r;let n=s.channels||[];return!n.length&&((i=s.channelsIds)!=null&&i.length)&&(n=intersectionWith(Object.values(e.tvChannels.list),s.channelsIds,(o,a)=>o.id===a),s.channels=n),{...s,trialAvailable:e.registration.disableTrials?!1:s.trialAvailable,channels:n.map(processChannel),channelsIds:n.map(o=>o.id),trialDays:convertToDays(s.trialDurationSeconds,"second"),trialChannels:((r=s.trial)==null?void 0:r.channels)||[],id:s.offerId}}),hasApplicableTrialsSelector=t=>{const e=offersSelector(t);return(e==null?void 0:e.find(n=>n.trialAvailable))&&!wasAutoTrialCreatedSelector(t)&&!isAutoTrialStatusProcessStartedSelector(t)},currentOfferIdSelector=t=>t.registration.currentOfferId,currentOfferSelector=t=>{const e=offersSelector(t),s=currentOfferIdSelector(t);return e==null?void 0:e.find(n=>n.id===s)},confirmationUrlSelector=t=>t.registration.confirmationUrl,autoTrialStatusSelector=t=>t.registration.autoTrialStatus,autoTrialDurationSelector=t=>convertToDays(t.registration.autoTrialDuration,"second"),wasAutoTrialCreatedSelector=t=>autoTrialStatusSelector(t)===REGISTRATION_TRIAL_STATUSES.created,isAutoTrialStatusUnknownSelector=t=>autoTrialStatusSelector(t)===REGISTRATION_TRIAL_STATUSES.unknown||autoTrialStatusSelector(t)===null,isAutoTrialStatusProcessStartedSelector=t=>autoTrialStatusSelector(t)===REGISTRATION_TRIAL_STATUSES.processStarted,prepareOfferField=(t,e,s,n)=>{var o,a,l;const i=(a=(o=t.authAndReg)==null?void 0:o.trial)==null?void 0:a[e];if(!i)return"";let r=getByLanguage(i.translationDict,t.languageCode,t.defaultLanguageCode)||"";return s&&((l=i.variables)==null||l.forEach(c=>{var d,u,h;if(s[c])if(c==="vodAvailable"){const f=listOfAllSourceIdsSelector(t),g=offersSelector(t),p=g==null?void 0:g.find(S=>S.id===n),m=((d=p==null?void 0:p.renderingData)==null?void 0:d[c])||"",v=(h=(u=p==null?void 0:p.vodSources)==null?void 0:u.filter(S=>f.indexOf(S)>=0))==null?void 0:h.map(S=>translationSelector(t,S)).join(", ");r=`${m.split(":")[0]}`,v&&(r=`${r}: ${v}`)}else r=r.replace(`@${c}@`,s[c]);else r=""})),r},trialOfferBadgeTextSelector=(t,e)=>prepareOfferField(t,"badge",e),trialOfferTitleSelector=(t,e)=>prepareOfferField(t,"offerTitle",e),trialOfferPriceSelector=(t,e)=>prepareOfferField(t,"offerPrice",e),trialOfferChannelCountsSelector=(t,e)=>prepareOfferField(t,"offerChannelCount",e),trialOfferVodSourcesSelector=(t,e,s)=>prepareOfferField(t,"offerVodSources",s,e),registration$1=Object.freeze(Object.defineProperty({__proto__:null,autoTrialDurationSelector,autoTrialStatusSelector,confirmationUrlSelector,currentOfferIdSelector,currentOfferSelector,hasAcquiringSelector,hasApplicableTrialsSelector,isAutoTrialStatusProcessStartedSelector,isAutoTrialStatusUnknownSelector,offersSelector,promoOffersSelector,trialOfferBadgeTextSelector,trialOfferChannelCountsSelector,trialOfferPriceSelector,trialOfferTitleSelector,trialOfferVodSourcesSelector,wasAutoTrialCreatedSelector},Symbol.toStringTag,{value:"Module"})),getTrialStatusAfterRegistration=t=>fe.get(URLS.trialRegistrationStatus,t),retry=async(t,e)=>{t.contactsVerification=await contactsVerification.retry(e)},verify=async(t,e)=>{var s;if(t.authAndReg.useContactVerifyV2&&!((s=e.params)!=null&&s.token)&&t.contactsVerification){const n={code:e.data.code,id:t.contactsVerification.id};t.verificationResult=await contactsVerification.verifyV2({...e,data:n})}else t.verificationResult=await contactsVerification.verify(e);return t.verificationResult},verifyContacts=async(t,e,s,n,i,r={},o=!1,a="",l="")=>{const c=typeof n=="string";let d="startWithAccountSession",u={type:"phone",contacts:cleanupPhone(s,t.authAndReg.usePlusInPhoneMethods.registration),reason:i};o?(d="startRecaptcha",u={type:"phone",contacts:cleanupPhone(s,t.authAndReg.usePlusInPhoneMethods.registration),"g-recaptcha-response":n,reason:i}):c&&(d="start",u={type:"phone",contacts:cleanupPhone(s,t.authAndReg.usePlusInPhoneMethods.registration),captcha:n,reason:i},isVercontCaptchaImageEnabledSelector(t)&&l?r.captchaid=l:u.cookies=a),t.contactsVerification=await contactsVerification[d]({languageCode:t.languageCode,ctx:e,data:u,params:r})},registerWithToken=async(t,e)=>{const s=await registerWithToken$1(e);return t.registrationResult=s,s},registerMobileWithToken=async(t,e)=>{const s=await registerMobileWithToken$1(e);return t.registrationResult=s,s},loadSubscriptionOptions$1=async(t,e,s=!1)=>{t.flags.tvDataState.loaded||await loadChannelsAndGenres(t,e);let n=[];s?(await getPromoCodeSubscriptionOptions(t,{ctx:e,languageCode:languageCodeSelector(t)}),n=promoOffersSelector(t)):(await getAllSubscriptionOptions(t,{ctx:e,languageCode:languageCodeSelector(t)}),n=offersSelector(t)),n[0]&&setCurrentOfferId(t,n[0].id)},setCurrentOfferId=(t,e)=>{t.registration.currentOfferId=e},createSubscription=async(t,e,s="")=>{const n=currentOfferIdSelector(t),i=currentOfferSelector(t);if(!i){t.registration.createSubscriptionError="Оффер не доступен";return}let r;const o=s?`${location.origin}${makePath(t,"/acquiring-status")}?${s}`:`${location.origin}${makePath(t,"/acquiring-status")}`,a=await createYakassaSubscriptionV2(t,{languageCode:t.languageCode,ctx:e,data:{offer_id:n,return_url:o},params:{create_subscription_token:i.createSubscriptionToken}}).catch(async l=>{const c=await yakassaSubscriptions({ctx:e,languageCode:languageCodeSelector(t)}),d=c==null?void 0:c.find(u=>u.offer.id===n);d?r=d.last_payment.confirmation.confirmation_url:t.registration.createSubscriptionError=l.toString()});a&&(r=a.last_payment.confirmation.confirmation_url),r&&(t.registration.confirmationUrl=r)},disableTrials=t=>{t.registration.disableTrials=!0},setTrialStatusAfterRegistrationAsUnknown=t=>{t.registration.autoTrialStatus=REGISTRATION_TRIAL_STATUSES.unknown},loadTrialStatusAfterRegistration=async(t,e,s=0,n,i)=>{const r=await getTrialStatusAfterRegistration({languageCode:t.languageCode,ctx:e}).catch(()=>{});if(!r){setTrialStatusAfterRegistrationAsUnknown(t);return}if(t.registration.autoTrialStatus=r.status,t.registration.autoTrialDuration=r.duration,r.status===REGISTRATION_TRIAL_STATUSES.processStarted)return new Promise((o,a)=>{const l=n||o,c=i||a;t.registration.autoTrialStatus!==REGISTRATION_TRIAL_STATUSES.processStarted?l(!0):s>4?(setTrialStatusAfterRegistrationAsUnknown(t),c({code:GET_TRIAL_STATUS_ERROR_CODE})):setTimeout(async()=>{await loadTrialStatusAfterRegistration(t,e,s+1,l,c)},5e3)})},registration=Object.freeze(Object.defineProperty({__proto__:null,createSubscription,disableTrials,loadSubscriptionOptions:loadSubscriptionOptions$1,loadTrialStatusAfterRegistration,registerMobileWithToken,registerWithToken,retry,setCurrentOfferId,verify,verifyContacts},Symbol.toStringTag,{value:"Module"})),log$q=logger$1("tv-epg-v2");let epgOnAirTimeoutId;const loadEpgOnAir=async(t,e)=>{var r;epgOnAirTimeoutId&&(clearTimeout(epgOnAirTimeoutId),epgOnAirTimeoutId=void 0);const s=3*60*1e3,n=6*60*1e3;let i=n;if(!t.tvEpgV2.onAir.isLoaded){const o=await getOnAir({languageCode:t.languageCode,ctx:e,params:{"tv-asset-token":tvAssetTokenSelector(t)}}).catch(a=>{log$q.error(a)}).finally(()=>{t.tvEpgV2.onAir.isLoading=!1});if(!o)return;if(t.tvEpgV2.onAir.schedules=(r=o.schedules)==null?void 0:r.reduce((a,l)=>(a[l.scheduleId]=l.events,a),{}),t.tvEpgV2.onAir.relevantInterval=o.relevantInterval,t.tvEpgV2.onAir.updateDuringInterval=o.updateDuringInterval,o.updateDuringInterval){const a=dayjs(o.updateDuringInterval.begin).unix(),l=dayjs(o.updateDuringInterval.end).unix(),c=(a-t.common.serverTime)*1e3,d=(l-t.common.serverTime)*1e3;i=random(c,d),l*1e3<=Date.now()+s&&(i=random(s,n))}t.tvEpgV2.onAir.isLoaded=!0}log$q.info("epg-on-air was loaded, next update in ~",Math.round(i/1e3/60),"minutes"),epgOnAirTimeoutId=setTimeout(()=>{t.tvEpgV2.onAir.isLoaded=!1,loadEpgOnAir(t,e)},i)},tvEpgV2$1=Object.freeze(Object.defineProperty({__proto__:null,loadEpgOnAir},Symbol.toStringTag,{value:"Module"})),log$p=logger$1("unsubscription-retention-actions"),start=(t,e)=>{t.unsubscriptionRetention.isOverlayVisible=!0,t.unsubscriptionRetention.currentSubscription=e,actions.modals.hideAllModals(t)},loadSubscriptionOptions=async(t,e)=>{var i,r,o;const s=t.unsubscriptionRetention.currentSubscription,n=await getSubscriptionOptions({languageCode:t.languageCode,ctx:e,params:{subscriptionId:s==null?void 0:s.id,offerId:(i=s==null?void 0:s.mainOffer)==null?void 0:i.offerId,unsubscriptionReasonId:t.unsubscriptionRetention.currentReasonId,unsubscriptionContextToken:(r=t.unsubscriptionRetention.settings)==null?void 0:r.unsubscriptionContextToken}});if(!n){log$p.warn("loadSubscriptionOptions failed");return}t.qs.qsTransactionId=n.qsTransactionId,t.unsubscriptionRetention.hasUnsupportedSubscriptionOptions=!!((o=n.subscriptionOptions)!=null&&o.length),t.unsubscriptionRetention.subscriptionOptions=(await prepareQuickSubscribeData(t,e,n,{hasUnsubscriptionRetention:!0}
5)).subscriptionOptions},begin=async(t,e)=>{var r;const s=t.unsubscriptionRetention.currentSubscription,n=s==null?void 0:s.managementMethods[0].managementContextToken,i={subscriptionId:s==null?void 0:s.id,offerId:(r=s==null?void 0:s.mainOffer)==null?void 0:r.offerId,managementMethod:s==null?void 0:s.managementMethods[0].name};if(i.subscriptionId&&i.offerId&&i.managementMethod&&n){const o=await postBegin({languageCode:t.languageCode,ctx:e,params:i,data:{managementContextToken:n}});if(!o){log$p.warn("unsubscriptionRetentionBegin failed");return}o.retentionMethods&&(o.retentionMethods=o.retentionMethods.filter(a=>SUPPORTED_RETENTION_METHODS.includes(a))),t.unsubscriptionRetention.settings=o}else{for(const o in i)if(typeof i[o]>"u")throw new Error(`Required param "${o}" is not set`);throw new Error('"managementContextToken" is not set')}},end=async(t,e,s,n)=>{var l,c,d,u;const i=t.unsubscriptionRetention.currentSubscription,r=t.unsubscriptionRetention.currentReasonId,o=(c=(l=t.unsubscriptionRetention.settings)==null?void 0:l.retentionMethods)==null?void 0:c[0],a=(d=t.unsubscriptionRetention.settings)==null?void 0:d.unsubscriptionContextToken;try{await postEnd({languageCode:t.languageCode,ctx:e,data:{unsubscriptionContextToken:a},params:{subscriptionId:i==null?void 0:i.id,offerId:(u=i==null?void 0:i.mainOffer)==null?void 0:u.offerId,retentionMethod:o,unsubscriptionReasonId:r,unsubscriptionResult:s,retentionOfferResult:n}}),localStore.remove(LOCAL_STORAGE_NAMES.unsubscriptionRetention)}catch(h){log$p.error("unsubscriptionRetentionEnd",h)}},setData=(t,e)=>{t.unsubscriptionRetention.currentSubscription=e.currentSubscription||null,t.unsubscriptionRetention.settings=e.settings||null,t.unsubscriptionRetention.subscriptionOptions=e.subscriptionOptions||null},unsubscriptionRetention$1=Object.freeze(Object.defineProperty({__proto__:null,begin,end,loadSubscriptionOptions,setData,start},Symbol.toStringTag,{value:"Module"})),actions={adultOnboarding,appInfo,appSections,authAndReg,brandingMethods,common,home,metrics,modals,notifications,packages,payment:payment$1,pauses,player,playerPlayingChannel,popupNotices,profiles:profiles$1,providerInfo,qs:qs$1,registration,seo:seo$1,tokensV1,tokensV2,tvChannels,tvEpgV2:tvEpgV2$1,unsubscriptionRetention:unsubscriptionRetention$1,utmLabels,vod},log$o=logger$1("quick-subscribe"),trialSteps=[{name:"TrialAbout"},{name:QS_STEP_NAMES.CONFIRMED},{name:QS_STEP_NAMES.ERROR}],trialTemplate={component:"TrialQs",steps(t){var e;return{authenticated:[{name:"TrialAbout"},{name:"TrialConfirmed"}],"sub20-phone-collect-instant":trialSteps,"sub20-phone-collect-delayed":trialSteps}[((e=t.subscriptionMethod)==null?void 0:e.name)||""]},availableSubscriptionMethods:["authenticated","sub20-phone-collect-instant","sub20-phone-collect-delayed"]},qsSteps=[{name:"AboutSubscription",prev:"PaymentRetry"},{name:"SubscriptionDetails"},{name:QS_STEP_NAMES.ERROR},{name:"PaymentRetry"}],mainTemplate={component:"AcquiringQs",steps(t){var e;return{authenticated:qsSteps,"sub20-yakassa-mvp":qsSteps,"sub20-phone-collect-instant":qsSteps,"sub21-yakassa":qsSteps,[SUBSCRIPTION_METHOD_NAMES.UPSALE]:qsSteps,[SUBSCRIPTION_METHOD_NAMES.UPSALE_V2]:qsSteps,[SUBSCRIPTION_METHOD_NAMES.UPSALE_V21]:qsSteps}[((e=t.subscriptionMethod)==null?void 0:e.name)||""]},availableSubscriptionMethods:["authenticated","sub20-phone-collect-instant","sub20-yakassa-mvp","sub21-yakassa",SUBSCRIPTION_METHOD_NAMES.UPSALE,SUBSCRIPTION_METHOD_NAMES.UPSALE_V2,SUBSCRIPTION_METHOD_NAMES.UPSALE_V21]},availableTemplates={"qs20-yakassa-v2":mainTemplate,"qs21-yakassa":mainTemplate,"qs10-legacy-default":mainTemplate,"qs20-vod-trial":trialTemplate,"qs20-tv-trial":trialTemplate,"qs20-tv-default":mainTemplate,"qs20-vod-default":mainTemplate,"qs22-promo-offer":mainTemplate,"buy-on-website":{component:"QsFallback"}},unsubscriptionRetentionAvailableTemplates={"qs22-unsub-retention-offer":{component:"",availableSubscriptionMethods:["authenticated","sub20-phone-collect-instant","sub20-yakassa-mvp","sub21-yakassa",SUBSCRIPTION_METHOD_NAMES.UPSALE,SUBSCRIPTION_METHOD_NAMES.UPSALE_V2,SUBSCRIPTION_METHOD_NAMES.UPSALE_V21]}},getStepsForSubscription=(t,e)=>{var n,i;const s=((n=t.renderingMethod)==null?void 0:n.name)||"";return(i=e[s])!=null&&i.steps?e[s].steps(t):[]},prepareRenderingData=(t,e,s,n,i,r)=>{var d,u;if(!e||!t.qsConfig||!s)return log$o.info("Subscription option was not provided"),{};const a=FALLBACK_RENDERING_METHODS.includes(e)?FALLBACK_RENDERING_METHOD_NAME:e,l=cloneDeep(t.qsConfig.methods[a]),c={};for(const h in l){const f=l[h].translationId,g=l[h].translation,p=l[h].contentBlockId,m=l[h].contentBlock;f&&g&&(c[h]=((d=getByLanguageWithReplace(t,g,n,r))==null?void 0:d.trim())||`{${f}}`),p&&m&&(c[h]=((u=getByLanguageWithReplace(t,m,n,r))==null?void 0:u.trim())||`{${p}}
5`),l[h].variables.forEach(v=>{var y;let S=s[v]||"";if(v==="vodAvailable"){const E=(y=[...n?["archive"]:[],...i||[]].filter(L=>sourcesSelector(t)[L]))==null?void 0:y.map(L=>sourcesSelector(t)[L].title).join(", ");E&&(S=E)}c[h]=c[h].replaceAll(`@${v}@`,S)})}return{...s,...c}},prepareQuickSubscribeData=async(t,e,s,n)=>{var l,c,d,u,h,f;const i=sortByPriority(s.subscriptionOptions),r=n!=null&&n.hasUnsubscriptionRetention?unsubscriptionRetentionAvailableTemplates:availableTemplates;let o=[];if(i!=null&&i.length){if(((c=(l=s.existingSubscriptions)==null?void 0:l[0])==null?void 0:c.paymentSystemType)===PaymentSystem.Uztelecom){const g=i.find(p=>{var m,v;return p.offerId===((v=(m=s.existingSubscriptions)==null?void 0:m[0])==null?void 0:v.offerId)});g&&(g.priority=0)}for(const g of i){const p=cloneDeep(g),m=sortByPriority(p.renderingMethods),v=sortByPriority(p.subscriptionMethods);for(const S of m){const y=r[S.name];if(y)for(const C of v){const E=C.name;if((d=y.availableSubscriptionMethods)!=null&&d.includes(E)){p.renderingMethod=S,p.subscriptionMethod=C;break}}if(p.renderingMethod)break}if(p.renderingMethod&&p.subscriptionMethod){try{const S=JSON.parse(p.renderingDataJson);if(p.renderingData={...S,...prepareRenderingData(t,p.renderingMethod.name,S,p.showcaseChannelsCount,p.vodSources,p.trialDurationSeconds)},p.trialAvailable&&p.trial){const y=JSON.parse(p.trial.renderingDataJson);p.trial.renderingData={...y,...prepareRenderingData(t,p.renderingMethod.name,y,p.trial.showcaseChannelsCount,p.trial.vodSources,p.trial.trialDurationSeconds)}}}catch(S){log$o.error(S)}if(!p.trialAvailable){const S=i.filter(y=>{const C=y.renderingMethods.filter(E=>E.name===RENDERING_METHOD_NAMES.BILLING_PERIOD);return p.title===y.title&&C.length});S!=null&&S.length&&(S.forEach(y=>{y.hasDifferentPeriod=!0;try{y.renderingData=JSON.parse(y.renderingDataJson)}catch(C){log$o.error(C)}}),p.differentPeriods=[p,...S])}await actions.qs.addChannelsToOffer(t,e,p),o.push(p)}}if(!(n!=null&&n.withPromoCode)){const g=((h=(u=o==null?void 0:o[0])==null?void 0:u.subscriptionMethod)==null?void 0:h.name)||"";o=o.filter(p=>{var m;return((m=p.subscriptionMethod)==null?void 0:m.name)===g})}}const a=s.fallback;if(!o.length&&!(n!=null&&n.withPromoCode)&&a&&!(n!=null&&n.hasUnsubscriptionRetention)){a.renderingMethods=sortByPriority(a.renderingMethods.filter(p=>availableTemplates[p.name]));const g=a.renderingMethods;if(g.length){const p={androidInApp:void 0,appleInApp:void 0,createSubscriptionToken:"",images:[],offerId:"",priority:0,shopSettings:void 0,showcaseChannelsCount:0,subscriptionMethods:[],title:"",trial:void 0,trialAvailable:!1,trialDurationSeconds:0,type:"",vodSources:[],...a};try{const m=JSON.parse(p.renderingDataJson);p.renderingData={...m,...prepareRenderingData(t,g[0].name,m,p.showcaseChannelsCount,p.vodSources,p.trialDurationSeconds)}}catch(m){log$o.error(m)}p.renderingMethod=g[0],o.push(p)}else((f=g[0])==null?void 0:f.name)===RENDERING_METHOD_NAMES.OPERATOR_CONTACT_INFO&&actions.notifications.showProviderInfoNotification(t)}return{existingSubscriptions:s.existingSubscriptions,subscriptionOptions:o,steps:o[0]?getStepsForSubscription(o[0],r):[],qsTransactionId:s.qsTransactionId,fallback:void 0}},isPaymentSuccessful=t=>t===SUBSCRIPTION_STATUSES.WAITING_FOR_CAPTURE||t===SUBSCRIPTION_STATUSES.SUCCEEDED,validatePromoCodeOffer=async(t,e)=>{var l;if(!t)return"promo_code_offer_id_was_not_set";const s=await loadAllAvailableSubscriptionOptions$1(e);if(!s)return"";const n=s==null?void 0:s.subscriptionOptions.find(c=>c.offerId===t);if(!n)return"promo_code_offer_was_not_found";const i=sortByPriority(n.renderingMethods),r=sortByPriority(n.subscriptionMethods);if(!(i!=null&&i.length))return"rendering_methods_were_not_found";if(!i.filter(c=>c.name===SUBSCRIPTION_METHOD_NAMES.PROMO_OFFER).length)return"promo_rendering_method_was_not_found";if(!(r!=null&&r.length))return"subscription_methods_were_not_found";let a=!1;for(const c of i){const d=availableTemplates[c.name];if(d)for(const u of r)(l=d.availableSubscriptionMethods)!=null&&l.includes(u.name)&&(a=!0)}if(!a)return"supported_rendering_method_was_not_found"},currentSourceSubscriptionsSelector=t=>{var e,s,n;if(t.qs.currentSourceId)return(n=(e=t.qs)==null?void 0:e.subscriptionsBySource)==null?void 0:n[(s=t.qs)==null?void 0:s.currentSourceId]},allSubscriptionsSelector=t=>t.qs.allSubscriptions,promoCodeSubscriptionsSelector=t=>t.qs.promoCodeSubscriptions,allAvailableSubscriptionsSelector=t=>t.qs.allAvailableSubscriptions,availableSubscriptionsSelector=t=>t.qs.availableSubscriptions||[],shopSubscriptionsSelector=t=>t.qs.shopSubscriptions||[],existingSubscriptionsSelector=t=>t.qs.existingSubscriptions,allSubscriptionsOptionsTypeBaseSelector=t=>{var e;return(e=allSubscriptionsSelector(t))==null?void 0:e.subscriptionOptions.filter(s=>s.type==="base"&&!!s.subscriptionMethods.find(n=>n.name==="sub20-yakassa-mvp"))},currentStepSelector=t=>{var e;return(e=currentSourceSubscriptionsSelector(t))==null?void 0:e.steps[t.qs.currentStepIndex]},currentStepComponentNameSelector=t=>{var e;return(e=currentStepSelector(t))==null?void 0:e.name},getStepIndexByName=(t,e)=>{var s,n;return(n=(s=currentSourceSubscriptionsSelector(t))==null?void 0:s.steps)==null?void 0:n.findIndex(i=>i.name===e)},currentTemplateSelector=t=>
5{const e=prioritySubscriptionSelector(t),s=e==null?void 0:e.renderingMethod;return s&&s.name?availableTemplates[s.name]:{component:null}},currentTemplateComponentSelector=t=>{var e;return(e=currentTemplateSelector(t))==null?void 0:e.component},prioritySubscriptionSelector=t=>{var e;return(e=currentSourceSubscriptionsSelector(t))==null?void 0:e.subscriptionOptions[0]},otherSubscriptionsSelector=t=>{var e,s;return(s=(e=currentSourceSubscriptionsSelector(t))==null?void 0:e.subscriptionOptions)==null?void 0:s.slice(1)},allSubscriptionOptionsSelector=t=>{var e;return((e=currentSourceSubscriptionsSelector(t))==null?void 0:e.subscriptionOptions)||[]},subscriptionOptionsWithoutExistingSelector=t=>{var n,i;const e=currentSourceSubscriptionsSelector(t),s=(n=e==null?void 0:e.existingSubscriptions)==null?void 0:n.map(r=>r.offerId);return(i=allSubscriptionOptionsSelector(t))==null?void 0:i.filter(r=>!(s!=null&&s.includes(r.offerId)))},existingSubscriptionInRetrySelector$1=t=>{var s,n;const e=((n=(s=currentSourceSubscriptionsSelector(t))==null?void 0:s.existingSubscriptions)==null?void 0:n.filter(i=>i.paymentSystemType===PaymentSystem.Yakassa.toLowerCase()&&i.subscriptionStatus===SubscriptionStatus.IN_RETRY.toLowerCase()||i.paymentSystemType===PaymentSystem.Uztelecom))||[];return e.length?e[0]:null},paymentRetrySelector=t=>t.qs.paymentRetry,loadingSelector=t=>t.qs.loading,subscriptionShopLoadingIdSelector=t=>t.qs.subscriptionShop.loadingId,additionalActionsCurrentStepIndex=t=>t.qs.additionalActions.currentStepIndex,tvBackgroundImageUrlSelector=t=>{var e,s,n;return(n=getByLanguage((s=(e=t.qsConfig)==null?void 0:e.qsTvBackground)==null?void 0:s.image,t.languageCode,t.defaultLanguageCode))==null?void 0:n.url},qs=Object.freeze(Object.defineProperty({__proto__:null,additionalActionsCurrentStepIndex,allAvailableSubscriptionsSelector,allSubscriptionOptionsSelector,allSubscriptionsOptionsTypeBaseSelector,allSubscriptionsSelector,availableSubscriptionsSelector,currentSourceSubscriptionsSelector,currentStepComponentNameSelector,currentStepSelector,currentTemplateComponentSelector,currentTemplateSelector,existingSubscriptionInRetrySelector:existingSubscriptionInRetrySelector$1,existingSubscriptionsSelector,getStepIndexByName,loadingSelector,otherSubscriptionsSelector,paymentRetrySelector,prioritySubscriptionSelector,promoCodeSubscriptionsSelector,shopSubscriptionsSelector,subscriptionOptionsWithoutExistingSelector,subscriptionShopLoadingIdSelector,tvBackgroundImageUrlSelector},Symbol.toStringTag,{value:"Module"})),paymentMethodAvailableSelector=t=>{var e,s,n,i;return((s=(e=t.payment)==null?void 0:e.method)==null?void 0:s.saved)&&!((i=(n=t.payment)==null?void 0:n.method)!=null&&i.is_cancelled)||!1},yakassaSubscriptionsSelector=t=>t.payment.yakassaSubscriptions,currentSubscriptionsSelectorV2=t=>t.payment.currentSubscriptions.filter(e=>{const s=t.payment.yakassaSubscriptions.find(n=>n.id===e.id);return e.managementMethods.length&&s?s.last_payment.status!==SUBSCRIPTION_STATUSES.PENDING||s.subscription_renew_status===SUBSCRIPTION_STATUSES.IN_RETRY:!0}),hasActiveSubscriptionsSelector=t=>currentSubscriptionsSelectorV2(t).length,cardSelector=t=>{var e,s;return(s=(e=t.payment)==null?void 0:e.method)==null?void 0:s.card},cardTypeSelector=t=>{var e;return((e=cardSelector(t))==null?void 0:e.card_type)||""},cardLast4Selector=t=>{var e;return((e=cardSelector(t))==null?void 0:e.last4)||""},subscriptionsInRetrySelector=t=>yakassaSubscriptionsSelector(t).filter(e=>e.subscription_renew_status===SUBSCRIPTION_STATUSES.IN_RETRY),existingSubscriptionInRetrySelector=t=>{const e=existingSubscriptionInRetrySelector$1(t);return e?yakassaSubscriptionsSelector(t).find(s=>s.id===e.subscriptionId):null},payment=Object.freeze(Object.defineProperty({__proto__:null,cardLast4Selector,cardSelector,cardTypeSelector,currentSubscriptionsSelectorV2,existingSubscriptionInRetrySelector,hasActiveSubscriptionsSelector,paymentMethodAvailableSelector,subscriptionsInRetrySelector,yakassaSubscriptionsSelector},Symbol.toStringTag,{value:"Module"})),personalSettingsSelector=t=>t.personalArea||{},personal=Object.freeze(Object.defineProperty({__proto__:null,personalSettingsSelector},Symbol.toStringTag,{value:"Module"})),currentActionSelector=t=>t.profiles.currentAction,profileIdToDeleteSelector=t=>t.profiles.profileIdToDelete,isProfileLoadingSelector=t=>t.profiles.isProfileLoading,isProfileLoadedSelector=t=>t.profiles.isProfileLoaded,profileSelectedSelector=t=>t.profiles.profileSelected,profiles=Object.freeze(Object.defineProperty({__proto__:null,currentActionSelector,isProfileLoadedSelector,isProfileLoadingSelector,profileIdToDeleteSelector,profileSelectedSelector},Symbol.toStringTag,{value:"Module"})),reviewsSettingsSelector=t=>t.reviews||{},reviews=Object.freeze(Object.defineProperty({__proto__:null,reviewsSettingsSelector},Symbol.toStringTag,{value:"Module"})),isSeoBotSelector=(t,e)=>{var i,r;const s=((r=(i=t.siteConfig)==null?void 0:i.searchBots)==null?void 0:r.uaRegExp)||SEO_BOTS_DEFAULT_UA_REGEXP,n=getUserAgent()||"unknown";return new RegExp(s,"i").test(n)},titleSelector=t=>t.seo.title,metaSelector=t=>t.seo.meta,breadcrumbsSelector=t=>t.seo.breadcrumbs,breadcrumbTelevisionChannelSelector=t=>t.seo.breadcrumbTelevisionChannel,breadcrumbProductSelector=t=>t.seo.breadcrumbProduct,defaultMetaOgImageSelector=t=>{var s;const e=(s=t.cmsPages)==null?void 0:s.find(n=>n.path==="/");
5return e?e.dataObject.metaImages.ogFileKey:""},seo=Object.freeze(Object.defineProperty({__proto__:null,breadcrumbProductSelector,breadcrumbTelevisionChannelSelector,breadcrumbsSelector,defaultMetaOgImageSelector,isSeoBotSelector,metaSelector,titleSelector},Symbol.toStringTag,{value:"Module"})),parseInterval=t=>({begin:dayjs(t.begin),end:dayjs(t.end)}),parseActuallyStartedAt=t=>"actuallyStartedAt"in t&&t.actuallyStartedAt?dayjs(t.actuallyStartedAt):void 0,prepareActuallyScheduledFor=(t,e)=>{let s;const n=parseActuallyStartedAt(t);if(n){const i=e?parseActuallyStartedAt(e):void 0;s={begin:n,end:i,isValidForTimeline:!!i&&i.unix()-n.unix()>EPG_MIN_PROGRAM_DURATION}}return s},enhanceProgram=(t,e)=>{if(!t.scheduledFor)return null;const s=parseInterval(t.scheduledFor);let n=s.end.unix()-s.begin.unix();const i=prepareActuallyScheduledFor(t,e);return i!=null&&i.isValidForTimeline&&(i!=null&&i.end)&&(n=i.end.unix()-i.begin.unix()),{...t,scheduledFor:s,description:"eventDescriptionMedium"in t?t.eventDescriptionMedium:"",duration:n,actuallyScheduledFor:i}},enhancePrograms=t=>t.reduce((e,s,n)=>{const i=t[n+1],r=enhanceProgram(s,i);return r&&e.push(r),e},[]),formatTimeHM=t=>(t==null?void 0:t.format("HH:mm"))||"",onAirScheduleProgramsSelector=(t,e)=>{var i,r,o;const s=((r=(i=e==null?void 0:e.medias)==null?void 0:i[0])==null?void 0:r.scheduleId)||"",n=((o=t.tvEpgV2.onAir.schedules)==null?void 0:o[s])||[];return enhancePrograms(n)},onAirLiveProgramIndexSelector=(t,e)=>{const s=onAirScheduleProgramsSelector(t,e);if(!s.length)return-1;const n=dayjs().unix();return s.findIndex(i=>i.scheduledFor.begin.unix()<=n&&i.scheduledFor.end.unix()>n)},onAirLiveProgramSelector=(t,e)=>{const s=onAirLiveProgramIndexSelector(t,e);return s<0?void 0:onAirScheduleProgramsSelector(t,e)[s]},onAirNextProgramSelector=(t,e)=>{var l;const s=onAirScheduleProgramsSelector(t,e),n=onAirLiveProgramIndexSelector(t,e);if(n<0)return;const i=s[n+1];if(!i)return;const r=dayjs(),o=(i.scheduledFor.begin||r).unix(),a=(l=t==null?void 0:t.common)!=null&&l.serverTime?t.common.serverTime:r.unix();return{title:i.title,scheduledFor:i.scheduledFor,startsIn:secondsToHMSelector(t,o-a)}},tvEpgV2=Object.freeze(Object.defineProperty({__proto__:null,onAirLiveProgramSelector,onAirNextProgramSelector},Symbol.toStringTag,{value:"Module"})),isEnabledSelector=t=>{var e,s;return(s=(e=t.siteConfig)==null?void 0:e.unsubscriptionRetention)==null?void 0:s.enabled},unsubscriptionRetention=Object.freeze(Object.defineProperty({__proto__:null,isEnabledSelector},Symbol.toStringTag,{value:"Module"})),selectors={account,adultOnboarding:adultOnboarding$1,appInfo:appInfo$1,authAndReg:authAndReg$1,brandingMethods:brandingMethods$1,channelCollections,common:common$1,fileRecords,home:home$1,metrics:metrics$1,modals:modals$1,notifications:notifications$1,packages:packages$1,pauses:pauses$1,payment,personal,player:player$1,playerPlayingChannel:playerPlayingChannel$1,popupNotices:popupNotices$1,profiles,promoElements,providerInfo:providerInfo$1,qs,registration:registration$1,reviews,seo,siteConfig,tokensV1:tokensV1$1,tokensV2:tokensV2$1,translations,tvChannels:tvChannels$1,tvEpgV2,unsubscriptionRetention,utmLabels:utmLabels$1,vod:vod$1};var __getOwnPropDesc$a=Object.getOwnPropertyDescriptor,__decorateClass$a=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$a(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let Global=class extends Vue{constructor(){super(...arguments);$(this,"uid",null)}get languageCode(){return selectors.common.languageCodeSelector(this.$store)}get isAnonymous(){return selectors.account.isAnonymousSelector(this.$store)}get currentVodSourceId(){var e;return((e=this.$route.params.sourceId)==null?void 0:e.toString())||"archive"}get theme(){return this.$store.theme}get isWelcomeScreenVisible(){return!this.isAnonymous&&selectors.modals.isWelcomeScreenOpenSelector(this.$store)&&this.$route.name!=="reg"&&this.$route.name!=="qr-success"}get isWl(){return!wlDetector().isSmotreshka}get isAltel(){return wlDetector().isAltel}get isIntersv(){return wlDetector().isIntersv}get isKcell(){return wlDetector().isKcell}get isKt(){return wlDetector().isKt}get isMegacom(){return wlDetector().isMegacom}get isMegafon(){return wlDetector().isMegafon}get isMts(){return wlDetector().isMts}get isN3(){return wlDetector().isN3}get isSanta(){return wlDetector().isSanta}get isSmotreshka(){return wlDetector().isSmotreshka}get isTele2(){return wlDetector().isTele2}get isRzd(){return wlDetector().isRzd}get isUcell(){return wlDetector().isUcell}
5get isUztel(){return wlDetector().isUztel}get isGalam(){return wlDetector().isGalam}get isOyna(){return wlDetector().isOyna}getByLanguage(e){return getByLanguage(e,this.languageCode,this.$store.defaultLanguageCode)}getTranslation(e){return selectors.translations.translationSelector(this.$store,e)}getTranslationWithLink(e){return makePathInHtml(this.$store,selectors.translations.translationSelector(this.$store,e))}translationWithReplace(e,s,n){const i=this.getTranslation(e);return n?i.replace(s,`${n}`):i}hasTranslation(e){return selectors.translations.hasTranslationIdSelector(this.$store,e)&&!!this.getTranslation(e)}getChannelsWord(e){return plurar(e,this.getTranslation("channel"),this.getTranslation("channel_genitive"),this.getTranslation("channels_genitive"))}getSendCodeAgainText(e){return`${this.getTranslation("send_code_again_in")}: ${e} ${this.getTranslation("sec")}.`}goToMainPage(){location.replace(makePath(this.$store,"/"))}};Global=__decorateClass$a([ComponentBase],Global);var __getOwnPropDesc$9=Object.getOwnPropertyDescriptor,__decorateClass$9=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$9(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let Metrics=class extends Vue{constructor(){super(...arguments);$(this,"yaMetrikaGoal",yaMetrikaGoal)}gaEvent(e){gaEvent(e,this.$store)}gaEventOnce(e){gaEventOnce(e,this.$store)}};Metrics=__decorateClass$9([ComponentBase],Metrics);var __getOwnPropDesc$8=Object.getOwnPropertyDescriptor,__decorateClass$8=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$8(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let Seo=class extends Vue{get breadcrumbs(){return[]}get breadcrumbTvChannel(){return null}get breadcrumbProduct(){return null}created(){var t;this.initMeta(),(t=this.breadcrumbs)!=null&&t.length&&actions.seo.addBreadcrumbs(this.$store,this.breadcrumbs),this.breadcrumbTvChannel&&actions.seo.addBreadcrumbTelevisionChannel(this.$store,this.breadcrumbTvChannel),this.breadcrumbProduct&&actions.seo.addBreadcrumbProduct(this.$store,this.breadcrumbProduct)}getMetaInfo(){return{title:"",meta:[]}}initMeta(){const{title:t,meta:e}=this.getMetaInfo();actions.seo.initMeta(this.$store,{title:t,meta:e})}getDefaultMetaOgImage(){var e;const t=(e=this.$store.cmsPages)==null?void 0:e.find(s=>s.path==="/");return t?t.dataObject.metaImages.ogFileKey:""}};Seo=__decorateClass$8([ComponentBase],Seo);var __getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$7(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let SequoiaComponent=class extends mixins(Global,Metrics){};SequoiaComponent=__decorateClass$7([ComponentBase],SequoiaComponent);let SequoiaPage=class extends mixins(Global,Metrics,Seo){};SequoiaPage=__decorateClass$7([ComponentBase],SequoiaPage);const scriptRel="modulepreload",assetsURL=function(t){return"/"+t},seen={},__vitePreload=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(s.map(l=>{if(l=assetsURL(l),l in seen)return;seen[l]=!0;const c=l.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${d}`))return;const u=document.createElement("link");if(u.rel=c?"stylesheet":scriptRel,c||(u.as="script"),u.crossOrigin="",u.href=l,a&&u.setAttribute("nonce",a),document.head.appendChild(u),c)return new Promise((h,f)=>{u.addEventListener("load",h),u.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})},initialState$n={currentStep:"",stepsHistory:[],nextStep:"",pinAction:"",isShown:!1},initialState$m={checkboxes:[],phoneMask:{use:!1,phoneCode:"+7 (999) 999 - 9999"},loginMask:"",textBelowLoginButtonId:"",textBelowRegButtonId:"",registration:{checkboxes:[],contentBlock:{},contentBlockId:"",show:!1,usePhoneRegistration:!1},contentBlock:{},contentBlockId:"",eula:{},eulaId:"",image:{},imageId:"",password:{min:1,max:30},regAcquiring:{disclaimerBlockId:"",advertisementTextBlockId:"",controlSubscriptionsOnlyOnSmotreshkaBlockId:"",disclaimerInChannelsListBlockId:"",disclaimer:{},advertisementText:{},controlSubscriptionsOnlyOnSmotreshka:{},disclaimerInChannelsList:{}},regTrials:{activeTrialId:"",enabled:!1},reportProblem:{},reportProblemId:"",restorePassword:{show:!0,contentBlock:{},contentBlockId:""},showPhoneUnlinkPage:!0,showRegCaptcha:!0,showRegPage:!0,showRestorePwdPage:!0,showRegistrationButton:!0,registrationButtonUrl:"",phone:"",usePromoCodes:!1,usePlusInPhoneMethods:{auth:!1,registration:!1,restorePassword:!1,phoneInfo:!1},recaptchaId:"",termsOfUse:[],methodAuth:"",isVercontServerEnabled:!0,staticProviderId:"",individualPage:!0,logoId:"",trial:{},isNewProviderSelected:!1,useContactVerifyV2:!0,isVercontCaptchaImageEnabled:!1},initialState$l={bodyScrollLockCount:0,isHeaderTransparent:!1,isHeaderAboveContent:!1,isHttps:!0,isOffline:!1,isProfileConfirmationOverlayVisible:!1,isPromoCodeOfferSkipVisible:!1,isSmartAppBannerVisible:!1,localTime:Date.now(),needServerTimeSync:!1,serverTime:Date.now()},initialState$k={items:{}},initialState$j={params:{},scrollPosition:0,title:"",visibility:{adultOnboarding:!1,byRoute:!1,dvrError:!1,dvrWarning:!1,feSettings:!1,mobileAp
5ps:!1,offerDetails:!1,offerExitConfirmation:!1,offerGift:!1,personalData:!1,phoneVerification:!1,playerHelp:!1,popupNotice:!1,profileAction:!1,profileProtected:!1,qs:!1,qsQr:!1,skipPromoOffers:!1,subscriptionConfirmation:!1,subscriptionShop:!1,subscriptionV2:!1,trialGift:!1,unsubscriptionRetentionOfferDetails:!1,verificationSubscription:!1,welcomeScreen:!1}},initialState$i={simple:[],complex:{adultOnboarding:{isVisible:!1,title:"",message:"",withButton:!1},authAndReg:{isVisible:!1,returnUrl:""},autologinMegafon:{isVisible:!1},dvrRestriction:{isVisible:!1},dvrRestrictionWithButton:{isVisible:!1},playerError:{isVisible:!1},providerContactInfo:{isVisible:!1,title:"",message:""},retry:{isVisible:!1},review:{isVisible:!1},subscriptionPaymentError:{isVisible:!1},subscriptionProlongationError:{isVisible:!1,message:""},unavailableContent:{isVisible:!1,image:null,sourceId:"",titleId:"",titleText:""}},queue:[]},initialState$h={items:[]},initialState$g={method:null,yakassaSubscriptions:[],currentSubscriptions:[]},initialState$f={alert:"",dvrWarningOverlay:{channelId:null,message:""},error:null,fastForwarding:!1,isDateTimeVisible:!0,isEpgVisible:!1,isFullscreenMenuVisible:!1,isLive:!0,isPrerollVisible:!0,isScrollLocked:!1,isSettingsMenuVisible:!1,loading:!1,loaded:!1,minimized:!1,nextProgram:null,overlay:{frozen:!1,hideTimeoutId:null,visible:!1},playbackMethod:"",playbackSessionContext:void 0,ready:!1,rewinding:!1,timeline:{isBalloonFollowingMouse:!0,isBalloonVisible:!1},touchedTimes:0,type:"",video:{duration:0,fps50:!0,isFullscreen:!1,isPlaying:!1,hasSubtitles:!1,muted:!1,playingTime:0,poster:"",scaled:!1,src:"",subtitleDisplay:!1,volume:.5,wasLanguageChanged:!1,wasPlayingBeforeOffline:!1},visible:!1,volumeSlider:{isMounted:!1,hideTimeoutId:null,visible:!1},playing:{channelId:"",episodeId:"",program:null,mediaItemId:"",sourceId:"",titleId:""},playbackInfo:{amedia2V1:void 0,ivi:void 0,megogoV1:void 0,smotreshkaPlaybackInfo:void 0,smotreshkaVodV2:void 0}},initialState$e={elements:[],currentElement:null,showTimeoutId:null,showTimeMs:0,contextToken:"",sendTimeoutStatId:null},initialState$d={currentAction:"",isProfileLoading:!1,isProfileLoaded:!0,profileIdToDelete:"",profileSelected:{}},initialState$c={items:{},isBannersDataLoaded:!1,isBannersDataLoading:!1},initialState$b=null,initialState$a={existingSubscriptions:null,allAvailableSubscriptions:null,availableSubscriptions:null,shopSubscriptions:null,allSubscriptions:null,promoCodeSubscriptions:null,channel:null,confirmationUrl:"",currentSourceId:"",currentStepIndex:0,paymentRetry:!1,phone:"",qrPayment:{isPaid:!1,isError:!1,title:"",expiresAt:""},qsTransactionId:"",serverError:{code:"",message:""},sourceType:"",subscriptionDetails:null,subscriptionsBySource:{},tempSubscription:null,toPrevStep:!1,usePm:!0,vod:null,loading:!1,availableSubscriptionDetails:null,activeSubscriptionDetails:null,subscriptionShop:{isLoading:!1,loadingId:""},additionalActions:{currentStepIndex:0},isOtherSubscriptionVisible:!1,scrollPosition:0},initialState$9={currentOfferId:"",confirmationUrl:"",vodCaption:"Кинотеатры: ivi, Megogo, AMEDIATEKA, START",createSubscriptionError:"",disableTrials:!1,autoTrialStatus:null,autoTrialDuration:0},initialState$8={onAir:{isLoading:!1,isLoaded:!1,schedules:{},relevantInterval:void 0,updateDuringInterval:void 0},full:{schedules:{},isLoading:!1}},initialState$7={channelsNotForPurchase:{},currentGenre:TV_SPECIAL_GENRES.recommended,favorites:{},genres:[],isChannelsCatalogNowOpen:!0,loaded:!1,loading:!1,list:{},listWithOnAirPrograms:[],recentAndFavLoaded:!1,recentAndFavLoading:!1,recentlyWatched:{},recommended:{},searchQuery:"",clientPlatform:"",settings:{}},initialState$6=null,initialState$5={loaded:!1,loading:!1,analyticsToken:"",audienceToken:"",tvAssetToken:"",expiresAt:""},initialState$4={loaded:!1,loading:!1,timeout:null,assetTokens:void 0,contextToken:"",regularUpdate:{etag:"",intervalSec:0}},initialState$3={audioTrackIndex:0,favorites:[],similarities:[],states:{favoritesLoaded:!1,favoritesLoading:!1,recommendationsLoaded:!1,sourcesLoading:!1,sourcesLoaded:!1,isSourceCollectionLoading:!1,isSourceCollectionLoaded:!1,isAnyHomeCollectionLoaded:!1,isAnyHomeCollectionLoading:!1},homeCollections:[],sourceCollections:[],searchQuery:"",sources:{},sourcesFe:[],sourcesBe:[],sorting:"",sortings:[]},initialState$2=null,initialState$1={sections:[]},initialState={settings:null,isOverlayVisible:!1,subscriptionOptions:null,currentSubscription:null,currentReasonId:null,returnUrlParams:{},hasUnsupportedSubscriptionOptions:!1},store$1={returnRoute:"",returnMetaTitle:"",premiumPage:{loaded:!1,provider:void 0},personalArea:void 0,adultOnboarding:initialState$n,authAndReg:initialState$m,common:initialState$l,fileRecords:initialState$k,modals:initialState$j,notifications:initialState$i,packages:initialState$h,payment:initialState$g,player:initialState$f,profiles:initialState$d,qs:initialState$a,pauses:initialState$o,popupNotices:initialState$e,a
5ppSections:initialState$1,providerInfo:initialState$b,providerInfoV2:null,registration:initialState$9,registrationResult:null,seo:initialState$p,seoRules:void 0,tokensV1:initialState$5,tokensV2:initialState$4,tvChannels:initialState$7,playerPlayingChannel:initialState$6,tvEpgV2:initialState$8,utmLabels:initialState$2,vod:initialState$3,theme:"light",styles:"",header:null,footer:null,cmsPages:[],feSessionId:"",profileRestrictions:[],profileSubscriptions:[],account:{anonymous:!0,delete_reason:"",id:"",is_phone_verified:!1,IVI:void 0,next_provider:void 0,profile:{favorites:[],age_rating:0,name:"anonymous",id:"",is_master:!1,recent_views:[],restriction:"",pin_required:!1},profiles:[],provider:void 0,user:{id:"",is_master:!1,login:"anonymous",email:"",phone:"",session:""},users:[]},appInfo:null,page:null,pages:[],pageFolders:[],defaultLanguageCode:"",languageCode:"",languages:[],translations:{},components:{},flags:{isSigningOut:!1,tvDataState:{loading:!1,loaded:!1}},siteConfig:null,contactsVerification:null,verificationResult:null,availableLogins:null,isPhoneMode:!0,secretSanta:!1,modalCallback:!1,incompletePhone:null,incompletePhoneInitialFlag:!0,page404:null,qsConfig:null,brandingMethods:[],gaParams:{},homeScreenConfig:{config_list:[],options:{}},promoElements:initialState$c,unsubscriptionRetention:initialState},useStore=()=>{const t=getCurrentInstance();return(t==null?void 0:t.appContext.config.globalProperties.$store)||cloneDeep(store$1)},useTranslation=()=>{const t=useStore(),e=a=>selectors.translations.translationSelector(t,a);return{getDaysWord:a=>plurar(a,e("day"),e("day_genitive"),e("days_genitive")),t:e,translationWithReplace:(a,l,c)=>{const d=e(a);return c?d.replace(l,`${c}`):d},hasTranslation:a=>selectors.translations.hasTranslationIdSelector(t,a)&&!!e(a),translationWithLink:a=>makePathInHtml(t,selectors.translations.translationSelector(t,a)),secondsToHM:a=>selectors.translations.secondsToHMSelector(t,a)}},useGetLanguageIcon=()=>t=>{switch(t){case"ru":return IconRu;case"br":return IconBr;case"kg":return IconKg;case"kz":return IconKz;case"tj":return IconTj;case"uk":return IconUk;case"us":return IconUs;case"uz":return IconUz;default:return""}},useChangeLanguage=()=>{const t=useStore();return e=>{const s=selectors.common.languageCodeSelector(t),n=selectors.common.defaultLanguageCodeSelector(t),r=t.languages.filter(l=>l.code!==s).find(l=>l.name===e.name),o=(r==null?void 0:r.code)||n;cookieStore.set(COOKIE_NAMES.languageCode,o);let a=window.location.pathname;a=s!==n?a.substring(3):a,a=a===""?"/":a,a=o!==n?`/${o}`+a:a,window.location.href=a+window.location.search}},useGetByLanguage=()=>{const t=useStore(),e=selectors.common.languageCodeSelector(t);return s=>getByLanguage(s,e,t.defaultLanguageCode)},useSSRContext=()=>{},useUa=()=>{const t=getCurrentInstance();return(t==null?void 0:t.appContext.config.globalProperties.$ua)||getUserAgent()},useEvents=()=>{const t=getCurrentInstance();return t==null?void 0:t.appContext.config.globalProperties.$events},useGaEvent=t=>{const e=useStore();gaEvent(t,e)},useGaEventOnce=t=>{const e=useStore();gaEventOnce(t,e)},useMetrics=()=>{const t=useStore(),e=computed(()=>t.gaParams);return{setGaParams:n=>{t.gaParams={...t.gaParams,...n}},gaParams:e}},verificationWaitingTime=ref(0),verificationTimerId=ref(null),timeoutIdUntilSessionTokenOutdated=ref(null),useVerification=()=>{const t=useStore(),e=()=>{var o;verificationWaitingTime.value=((o=t.contactsVerification)==null?void 0:o.interval)||REGISTRATION_RESEND_SMS_CODE_IN_SECONDS,verificationTimerId.value=setInterval(r,convertToMilliseconds(1,"second"))},s=()=>{verificationTimerId.value&&clearInterval(verificationTimerId.value)},n=(o,a)=>{var d,u;const l=(d=t.contactsVerification)==null?void 0:d.expiresAt;let c=l?convertToMilliseconds(l-(((u=t.appInfo)==null?void 0:u.currentTime)||Date.now()),"second"):REGISTRATION_SESSION_LIFETIME;c=Math.max(c,0),timeoutIdUntilSessionTokenOutdated.value=setTimeout(()=>{a&&o?a(o):actions.qs.additionalActionsGoToStepByName(t,QS_VERIFICATION_PHONE_STEPS.verificationError)},c)},i=()=>{timeoutIdUntilSessionTokenOutdated.value&&clearTimeout(timeoutIdUntilSessionTokenOutdated.value)},r=()=>{verificationWaitingTime.value--,verificationWaitingTime.value===0&&verificationTimerId.value&&clearInterval(verificationTimerId.value)};return{verificationClearTimeout:i,verificationSetTimeout:n,verificationStartTimer:e,verificationStopTimer:s,verificationTimerId,verificationWaitingTime}};var TClientAnalyticsUiEvent=(t=>(t.pageImpression="page_impression",t.pageUpdate="page_update",t.itemFocus="item_focus",t.itemClick="item_click",t))(TClientAnalyticsUiEvent||{});const eventsQueue=ref([]),contextToken=ref(""),log$n=logger$1("client-analytics");let sessionStartTime=0,lastEventTime=0,lastSendUnifiedEventsPromise=null,sendQueuedEventsTimeout;const useClientAnalytics=()=>{const t=useStore(),e=useSSRContext(),s=async o=>{if(!selectors.siteConfig.isClientAnalyticsEnabled(t))return;sendQueuedEventsTimeout&&clearTimeout(sendQueuedEventsTimeout);const a=Date.now(),l={analyticsToken:selectors.tokensV2.analyticsTokenSelector(t),localClientTimestamp:dayjs().format("YYYY-MM-DDTHH:mm:ss[Z]"),clientTimezoneOffset:new Date().getTimezoneOffset(),events:[]},c={sinceAppSessionStartMs:contextToken.value?a-sessionStartTime:0,sincePrevEventMs:contextToken.value?a-lastEventTime:0,...o};l.events.push(c),contextToken.value||(sessionStartTime=a),lastEventTime=a,eventsQueue.value.push(c),sendQueuedEventsTimeout=setTimeout(async()=>{await i(l)},400)},n=async o=>{try{lastSendUnifiedEventsPromise&&await lastSendUnifiedEventsPromise,lastSendUnifiedEventsPromise=sen
5dUnifiedEvents({languageCode:t.languageCode,ctx:e,jsonData:!0,data:o});const a=await lastSendUnifiedEventsPromise;contextToken.value=(a==null?void 0:a.contextToken)||""}catch(a){log$n.error(a.message)}finally{lastSendUnifiedEventsPromise=null}},i=async o=>{if(eventsQueue.value.length){const a=[];for(let l=0;l<eventsQueue.value.length;l+=CLIENT_ANALYTICS_MAX_EVENTS_COUNT)a.push(eventsQueue.value.slice(l,l+CLIENT_ANALYTICS_MAX_EVENTS_COUNT));eventsQueue.value=[];for(const l of a)await n({...o,contextToken:contextToken.value,events:l})}};return{sendUnifiedEvents:s,sendClickEvent:async({item:o,block:a,flow:l,page:c,subFlow:d})=>{await s({ui:{event:TClientAnalyticsUiEvent.itemClick,flow:l,subFlow:d,page:c,item:o,block:a}})}}},useAuth=()=>{const t=useStore();return{isAnonymous:computed(()=>{var s;return!!((s=t.account)!=null&&s.anonymous)})}},authAndRegCheckboxes=ref([]),useAuthAndRegCheckboxes=()=>{const t=useStore(),e=useGetByLanguage(),s=[CHECKBOX_ADS_AGREEMENT_ID],n=computed(()=>authAndRegCheckboxes.value.some(a=>!a.value&&a.required)),i=computed(()=>authAndRegCheckboxes.value.some(a=>a.id===CHECKBOX_ADS_AGREEMENT_ID)),r=computed(()=>authAndRegCheckboxes.value.some(a=>a.id===CHECKBOX_ADS_AGREEMENT_ID&&a.value));return{authAndRegCheckboxes,hasUncheckedSignUpCheckbox:n,hasAdsAgreementCheckbox:i,checkedAdsAgreementCheckbox:r,initAuthAndRegCheckboxes:a=>{var c,d;let l={checkboxes:[]};a==="reg"?l=t.authAndReg.registration:a==="login"&&(l=t.authAndReg),authAndRegCheckboxes.value=(d=(c=l==null?void 0:l.checkboxes)==null?void 0:c.filter(u=>u.contentBlockId))==null?void 0:d.map(u=>({value:s.includes(u.contentBlockId),content:e(u.contentBlock),id:u.contentBlockId,required:!s.includes(u.contentBlockId)}))}}},email=ref(""),errors=ref([]),isLoading$2=ref(!1),isLoadingRetry=ref(!1),initialLoading=ref(!0),nextStepAfterGetLogins=ref(""),currentStep$2=ref(AUTH_STEPS.start),needUseRecaptcha=ref(!0),passwordAuth=ref(""),currentLogin=ref(""),captcha=ref(""),checkCode=ref(""),errorMessages=ref([]),errorText=ref(""),gaNameComponent=ref(""),verificationComponentName=ref(""),registerProviderInfo=ref({regionId:"",providerId:"",providerIdFromUrl:"",providerName:""}),isSmsAuth=ref(!1),isAuthWithPassword=ref(!1),phoneUnsupported=ref(!1),phoneUnsupportedMessage=ref(""),phoneTechnicalSim=ref(!1),recommendProvider=ref(""),recommendOfferId=ref(""),phoneInfoToken=ref(""),promoCode=ref(""),isPromoCodeValid=ref(!1),promoCodeResultText=ref(""),promoCodeMessage=ref(""),promoCodeId=ref(""),canonicalValue=ref(""),authPhoneNotFound=ref(""),registrationSettings=ref([]),selectedPromoCodeOffer=ref(""),isAutoLoginLoading=ref(!1),logins=ref([]),evictedSession=ref({displayMessage:"",evictedDeviceCaption:""}),captchaId=ref(""),cookieCaptcha=ref(""),captchaRefreshValue=ref(0),log$m=logger$1("auth"),useAuthAndReg=()=>{const t=useStore(),e=useSSRContext(),s=useRoute(),n=useRouter(),{t:i}=useTranslation(),{isAnonymous:r}=useAuth(),{sendUnifiedEvents:o,sendClickEvent:a}=useClientAnalytics(),{verificationStopTimer:l,verificationClearTimeout:c,verificationStartTimer:d,verificationSetTimeout:u}=useVerification(),{hasAdsAgreementCheckbox:h,checkedAdsAgreementCheckbox:f}=useAuthAndRegCheckboxes(),g=[{index:0,number:1,text:i("by_sms_code")},{index:1,number:2,text:i("by_login")}],p=useGetByLanguage(),m=computed(()=>t.authAndReg.phone),v=computed(()=>{var j;let x=AUTH_METHODS.sms;return wlDetector().isSmotreshka||wlDetector().isOyna?x=AUTH_METHODS.smotreshka:wlDetector().isN3?x=AUTH_METHODS.n3:(wlDetector().isAltel||wlDetector().isTele2)&&(x=AUTH_METHODS.smsAndPasswd),((j=s.params)==null?void 0:j.type)||t.authAndReg.methodAuth||x}),S=computed(()=>v.value===AUTH_METHODS.smotreshka),y=computed(()=>v.value===AUTH_METHODS.n3),C=computed(()=>(v.value===AUTH_METHODS.sms||v.value===AUTH_METHODS.smsAndPasswd)&&!isAuthWithPassword.value),E=computed(()=>{var x;return(s==null?void 0:s.name)==="login"&&((x=s==null?void 0:s.query)==null?void 0:x.type)!=="reg"}),L=computed(()=>{var x;return(s==null?void 0:s.name)==="reg"||((x=s==null?void 0:s.query)==null?void 0:x.type)==="reg"}),T=computed(()=>!!(needUseRecaptcha.value&&t.authAndReg.recaptchaId)),b=computed(()=>selectors.common.authAndRegPasswordMinSelector(t)),_=computed(()=>selectors.common.authAndRegPasswordMaxSelector(t)),I=computed(()=>errors.value.find(x=>x.name==="login")),P=computed(()=>errors.value.find(x=>x.name==="Captcha")),R=computed(()=>{var x;return(x=t.authAndReg.phoneMask)==null?void 0:x.phoneCode}),D=computed(()=>I.value?"error":void 0),O=computed(()=>{var x;return((x=P.value)==null?void 0:x.message)||""}),N=computed(()=>P.value?"error":void 0),H=computed(()=>{var x,j;return(j=(x=errors.value)==null?void 0:x[0])==null?void 0:j.message}),W=computed(()=>wlDetector().isUztel?9:wlDetector().isMts?13:CORRECT_PHONE_LENGTH),M=computed(()=>t.incompletePhone||I.value?"error":void 0),A=computed(()=>t.authAndReg.usePlusInPhoneMethods),w=computed(()=>t.authAndReg.isVercontServerEnabled),k=computed(()=>{var x,j;return(j=(x=t.authAndReg)==null?void 0:x.regTrials)==null?void 0:j.enabled}),F=computed(()=>cleanupPhone(m.value,!1)),B=computed(()=>t.incompletePhoneInitialFlag),K=computed(()=>t.incompletePhone),G=computed(()=>i(t.authAndReg.textBelowRegButtonId?t.authAndReg.textBelowRegButtonId:"")),U=computed(()=>K.value?i("incomplete_phone_reg"):I.value?I.value.message:""),Y=computed(()=>{var x;return currentLogin.value||((x=logins.value)!=null&&x.length?logins.value[0].login:F.value)}),J=computed(()=>isEmptyObject(t.authAndReg.contentBlock)?"":p(t.authAndReg.contentBlock)||""),z=(x,j=!0)=>
5{if(!Object.getOwnPropertyDescriptor(AUTH_STEPS,x)){currentStep$2.value=AUTH_STEPS.start;return}currentStep$2.value=x,Q(!1),j&&r.value&&le(x),GA_AUTH_STEPS.includes(x)&&useGaEvent({action:x,error_text:AUTH_STEPS.error?"Что-то пошло не так":"Сессия истекла"})},le=(x,j="")=>{const{subFlow:X,page:ee}=ae(x,j);!X||!ee||ue({event:TClientAnalyticsUiEvent.pageImpression,subFlow:X,page:ee})},ae=(x,j="")=>{var ee;const X=j||`${x}-${(ee=s==null?void 0:s.name)==null?void 0:ee.toString()}${promoCode.value&&isPromoCodeValid.value?"-promoCode":""}`;return{subFlow:(CLIENT_ANALYTICS_AUTH_AND_REG_SUB_FLOW==null?void 0:CLIENT_ANALYTICS_AUTH_AND_REG_SUB_FLOW[X])||"",page:(CLIENT_ANALYTICS_AUTH_AND_REG_UI_PAGE==null?void 0:CLIENT_ANALYTICS_AUTH_AND_REG_UI_PAGE[X])||""}},ue=({event:x,subFlow:j,page:X})=>{o({ui:{flow:"smotreshka-lir-v2",event:x,subFlow:j,page:X}}).then()},ne=({item:x,block:j})=>{const{subFlow:X,page:ee}=ae(currentStep$2.value);if(!X||!ee)return;const oe={flow:"smotreshka-lir-v2",subFlow:X,page:ee,item:x};j&&(oe.block=j),a(oe).then()},Q=x=>isLoading$2.value=x,q=()=>{useGaEvent({action:"Клик - Забыли пароль"}),ne({item:"button_forgot_password"}),t.isPhoneMode&&m.value&&(t.authAndReg.phone=cleanupPhone(m.value),passwordAuth.value="",captcha.value="")},te=x=>{isNaN(parseFloat(x.key))&&x.preventDefault()},se=(x=!0)=>{x&&(t.authAndReg.phone=""),captcha.value="",errorText.value="",checkCode.value="",evictedSession.value.evictedDeviceCaption="",evictedSession.value.displayMessage="",z(AUTH_STEPS.start,!1),errors.value.length=0,errorMessages.value.length=0,c(),l()},re=()=>{se(),useGaEvent({action:"Клик по кнопке - Ввести другой номер"}),ne({item:"button_use_another_phone"})},me=async()=>{isLoadingRetry.value=!0,useGaEvent({action:"Клик по кнопке - Выслать заново"}),await actions.registration.retry(t,{languageCode:t.languageCode,ctx:e,data:{type:"phone",id:t.contactsVerification.id}}),isLoadingRetry.value=!1,d()},ce=x=>{errorText.value=x.message||x.msg||x.toString()||"Unknown error",z(AUTH_STEPS.error)},ie=x=>{gaNameComponent.value&&(x.category=gaNameComponent.value,useGaEvent(x))},Ce=x=>{gaNameComponent.value&&(x.category=gaNameComponent.value,useGaEventOnce(x))},_e=()=>{const x=s.query,j=localStore.get(LOCAL_STORAGE_NAMES.utmParameters),X=getAppVersionParams(e);localStore.remove(LOCAL_STORAGE_NAMES.utmParameters);const ee=j||{utmSource:x.utm_source||"",utmMedium:x.utm_medium||"",utmCampaign:x.utm_campaign||"",utmContent:x.utm_c
5ontent||"",utmTerm:x.utm_term||""};let oe=`${X.app.id}.${X.app.buildType}`;return h.value&&!f.value&&(oe=`${oe}.nopromo`),{"contacts-session-token":t.verificationResult.sessionToken,"phone-info-token":phoneInfoToken.value,utm_source:ee.utmSource,utm_medium:oe,utm_campaign:ee.utmCampaign,utm_content:ee.utmContent,utm_term:ee.utmTerm}},he=async x=>{Q(!0);try{await Se(x)}catch(j){j.resStatus===HTTP_CODES.BAD_REQUEST?(needUseRecaptcha.value=!1,z(AUTH_STEPS.captcha)):ce(j)}},Se=async x=>{var j,X,ee,oe;if(Q(!0),!t.isPhoneMode&&email.value){if(ie({action:"Клик по кнопке - Далее после ввода логина"}),E.value)try{if(await actions.authAndReg.login(t,e,email.value,passwordAuth.value),(X=(j=t.siteConfig)==null?void 0:j.welcomeScreen)!=null&&X.isRegistrationOnlyEnabled&&(cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,"1"),t.common.isProfileConfirmationOverlayVisible=!0),await actions.authAndReg.getAccount(t,e),await managing({languageCode:t.languageCode,ctx:e,data:{email:(oe=(ee=t.account)==null?void 0:ee.user)==null?void 0:oe.login,password:passwordAuth.value}}),await Le()||await ke())return;await Te()}catch(de){errors.value.push({code:de.resStatus,message:de.message,name:"login"}),Q(!1),passwordAuth.value=""}else t.languageCode,email.value.toLowerCase(),captcha.value,selectors.authAndReg.isVercontCaptchaImageEnabledSelector(t)?captchaId.value:cookieCaptcha.value,await restorePassword({languageCode:t.languageCode,ctx:e,data:{login:email.value.toLowerCase(),captcha:captcha.value,cookies:cookieCaptcha.value}}),z(AUTH_STEPS.emailFinish);return!0}try{await actions.registration.verifyContacts(t,e,m.value,x||captcha.value,verificationComponentName.value,{},T.value,cookieCaptcha.value,captchaId.value),z(AUTH_STEPS.checkCode)}catch(de){if(Q(!1),de.resStatus===HTTP_CODES.BAD_REQUEST&&wlDetector().isMts){ce(de);return}else de.resStatus===HTTP_CODES.BAD_REQUEST&&ie({action:"Неверная капча"});throw de}},Le=async()=>{const x=s.query.qr;return x&&(await actions.authAndReg.qrLogin(t,e,x),await n.replace(AUTH_AND_REG_URLS.qrSuccess)),!!x},Te=async()=>{cookieStore.remove(COOKIE_NAMES.promoCode);const x=sessionStore.get("backUrlAfterLogin");x?(await n.push(x),sessionStore.remove("backUrlAfterLogin")):await n.push(makePath(t,"/")),ie({action:"Клик по кнопке - Войти"})},Pe=async x=>{if(!isLoading$2.value){if(Q(!0),errors.value.length=0,errorMessages.value.length=0,phoneTechnicalSim.value){z(AUTH_STEPS.simPassword);return}try{ie({action:"Клик по кнопке - Далее после ввода телефона"}),yaMetrikaGoal("Phone_submit"),T.value?x.execute():await Se(null)}catch(j){ye(j),ie({action:"Клик по кнопке - Далее после ввода телефона",error_text:j.message})}}},Ne=async()=>{var j,X,ee,oe,de,ve,ge,pe;if(isLoading$2.value)return;Q(!0),errors.value.length=0,errorMessages.value.length=0;const x=t.isPhoneMode?cleanupPhone(m.value,A.value.auth):m.value;if(cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,(X=(j=t.siteConfig)==null?void 0:j.welcomeScreen)!=null&&X.isRegistrationOnlyEnabled?"0":"1"),isPromoCodeValid.value){await we(x);return}errorMessages.value=[];try{if(await actions.authAndReg.login(t,e,x,passwordAuth.value),await managing({languageCode:t.languageCode,ctx:e,data:{email:(oe=(ee=t.account)==null?void 0:ee.user)==null?void 0:oe.login,password:passwordAuth.value}}),await Le())return;cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,(ve=(de=t.siteConfig)==null?void 0:de.welcomeScreen)!=null&&ve.isRegistrationOnlyEnabled?"1":"0"),t.common.isProfileConfirmationOverlayVisible=(pe=(ge=t.siteConfig)==null?void 0:ge.welcomeScreen)==null?void 0:pe.isRegistrationOnlyEnabled,await Te()}catch(Ie){Q(!1),Ie.resStatus===HTTP_CODES.FORBIDDEN?errors.value.push({code:Ie.resStatus,message:Ie.message,name:"login"}):ye(Ie)}},we=async x=>{try{await V(passwordAuth.value,x),await Z(),Q(!1)}catch(j){if(Q(!1),j.resStatus===HTTP_CODES.NOT_FOUND)z(AUTH_STEPS.outdated);else if(j.resStatus===HTTP_CODES.BAD_REQUEST)ce(j);else throw errorMessages.value.push(j.message),j}},V=async(x,j="")=>{var X;errors.value.length=0,errorMessages.value.length=0;try{switch(c(),await actions.registration.verify(t,{languageCode:t.languageCode,ctx:e,data:{type:"phone",contacts:j||cleanupPhone(m.value,A.value.registration),code:x}}),ie({action:"Сабмит кода из смс"}),u(AUTH_STEPS.outdated,z),await actions.authAndReg.getAvailableLogins(t,e),logins.value=((X=t.availableLogins)==null?void 0:X.options)||[],logins.value.length){case 0:z(AUTH_STEPS.phoneNotFound);break;case 1:currentLogin.value=logins.value[0].login,z(nextStepAfterGetLogins.value);break;default:z(AUTH_STEPS.multipleLogins);break}}catch(ee){if(ie({action:"Сабмит кода из смс",error_text:ee.message}),log$m.error(ee),ee.resStatus===HTTP_CODES.NOT_FOUND)z(AUTH_STEPS.outdated);else throw errorMessages.value.push(ee.message),Q(!1),ee}},Z=async()=>{var x;try{S.value||y.value?t.registrationResult=await registerWithPromoCode({ctx:e,languageCode:t.languageCode,params:{"contacts-session-token":t.verificationResult.sessionToken,"phone-info-token":phoneInfoToken.value},data:{promocode:promoCodeId.value}}):promoCodeResultText.value=await registerWithPromoCodeMobile({languageCode:t.languageCode,ctx:e,params:{"contacts-session-token":t.verificationResult.sessionToken},data:{promocode:promoCodeId.value}}),cookieStore.set("welcomeScreenConfirmed","1"),recommendOfferId.value?(await Re(),Q(!1),await Ee(!1,!!wlDetector().isSmotreshka),t.common.isProfileConfirmationOverlayVisible=!1,
5cookieStore.set(COOKIE_NAMES.promoCode,JSON.stringify({recommendOfferId:recommendOfferId.value,code:canonicalValue.value,promoCodeId:promoCodeId.value,message:promoCodeMessage.value,phone:m.value,resultText:promoCodeResultText.value})),z(AUTH_STEPS.promoOffers),Q(!0),c(),l()):z(AUTH_STEPS.promoCodeSuccess)}catch(j){let X;switch(j.resStatus){case HTTP_CODES.BAD_REQUEST:case HTTP_CODES.CONFLICT:X=AUTH_STEPS.promoCodeUserExist;break;case HTTP_CODES.SERVER_ERROR:X=AUTH_STEPS.promoCodeError;break;default:X=AUTH_STEPS.promoCodeNotFound}j.resStatus===HTTP_CODES.CONFLICT&&(t.registrationResult={registeredLogin:(x=j.response.data)==null?void 0:x.existingLogin}),errorText.value=j.message,z(X)}},ye=x=>{var X,ee,oe,de,ve;errors.value.length=0,errorMessages.value.length=0,Q(!1);const j=x.resStatus;if(j===HTTP_CODES.BAD_REQUEST||x.name==="Error"){captcha.value="",captchaRefreshValue.value++;const ge=(ee=(X=x.response)==null?void 0:X.data)==null?void 0:ee.errors;ge!=null&&ge.length?ge.forEach(pe=>{errors.value.push({code:j,message:pe.msg,name:pe.name})}):x!=null&&x.message?errors.value.push({code:x.code||"",message:x.message,name:x.name||""}):(de=(oe=x.response)==null?void 0:oe.data)!=null&&de.msg&&errors.value.push({code:j,message:x.response.data.msg,name:x.name||""}),(ve=errors.value)!=null&&ve.length&&errors.value.forEach(pe=>{errorMessages.value.push(pe.message)})}else ce(x)},xe=async()=>{if(!isLoading$2.value){Q(!0);try{await actions.authAndReg.sendPassword(t,e,currentLogin.value||logins.value[0].login),z(AUTH_STEPS.phoneFoundAfterReset),ie({action:"Выслать новый пароль"})}catch(x){ce(x)}}},De=async()=>{if(!isLoading$2.value)try{c(),Q(!0),errors.value.length=0,errorMessages.value.length=0,await actions.registration.verify(t,{ctx:e,languageCode:t.languageCode,data:{type:"phone",contacts:cleanupPhone(m.value,A.value.auth),code:checkCode.value}}),ie({action:"Сабмит кода из смс"}),yaMetrikaGoal("Sms_code_submit")}catch(x){throw ie({action:"Сабмит кода из смс",error_text:x.message}),x}finally{Q(!1)}},Re=async()=>{var x;await actions.authAndReg.getAvailableLogins(t,e),logins.value=((x=t.availableLogins)==null?void 0:x.options)||[]},Oe=()=>{promoCode.value="",isPromoCodeValid.value=!1,ne({item:"button_continue_without_promocode"}),z(AUTH_STEPS.start)},Ee=async(x=!0,j=!1)=>{var ee,oe,de,ve,ge,pe,Ie,Me;if(isLoading$2.value)return;Q(!0);let X=Y.value;if(E.value)ie({action:"Клик по кнопке - Войти"});else{let Ae=A.value.auth;wlDetector().isN3&&(Ae=!0),wlDetector().isSmotreshka&&(Ae=!1),X=((ee=t.registrationResult)==null?void 0:ee.registeredLogin)||cleanupPhone(m.value,Ae),ie({action:"Регистрация нового пользователя"})}yaMetrikaGoal("Reg_completion");try{if(await actions.authAndReg.loginWithVerifiedContacts(t,e,X),await managingWithVerifiedContacts({languageCode:t.languageCode,ctx:e,params:{"contacts-session-token":((oe=t.verificationResult)==null?void 0:oe.sessionToken)||""},data:{login:X}}),t.common.isProfileConfirmationOverlayVisible=((ve=(de=t.siteConfig)==null?void 0:de.welcomeScreen)==null?void 0:ve.isRegistrationOnlyEnabled)&&j&&((pe=(ge=t.account)==null?void 0:ge.profile)==null?void 0:pe.pin_required),(Me=(Ie=t.siteConfig)==null?void 0:Ie.welcomeScreen)!=null&&Me.isRegistrationOnlyEnabled&&!authPhoneNotFound.value&&(E.value||j)?(cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,"1"),t.common.isProfileConfirmationOverlayVisible=!0):(cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,"0"),isPromoCodeValid.value&&recommendOfferId.value&&actions.modals.showWelcomeScreen(t)),wlDetector().isUztel)try{await actions.payment.loadCurrentSubscriptions(t,e)}catch(Ae){log$m.error("onLoadPaymentSubscriptions",Ae)}if(E.value&&await ke())return;x&&await Te()}catch(Ae){ce(Ae)}},Fe=async x=>(currentLogin.value=x,ie({action:"Клик по аккаунту (выбор из списка аккаунтов)"}),ne({item:"context_item",block:"profiles_list"}),isPromoCodeValid.value?await Z():await Ee(!0,!0)),Ue=async()=>{await n.push("/reg"),z(AUTH_STEPS.promoOffers)},$e=()=>{t.isPhoneMode=!t.isPhoneMode,t.authAndReg.phone="",passwordAuth.value="",t.incompletePhoneInitialFlag=!0,t.incompletePhone=!1,errorMessages.value.length=0},Be=async()=>{await Re(),Q(!1),await Ee(!1),k.value?(await sleep(REGISTRATION_TIMEOUT_AFTER_SIGN_IN),await actions.registration.loadSubscriptionOptions(t,e),await actions.registration.loadTrialStatusAfterRegistration(t,e),selectors.registration.isAutoTrialStatusUnknownSelector(t)?z(AUTH_STEPS.retryTrialStatus):z(AUTH_STEPS.finish)):z(AUTH_STEPS.finish),Q(!1)},ke=async()=>
5{if(selectors.siteConfig.isEvictedSessionEnabled(t))try{const x=await evictedSession$1({languageCode:t.languageCode,ctx:e});return evictedSession.value.displayMessage=(x==null?void 0:x.displayMessage)||"",evictedSession.value.evictedDeviceCaption=(x==null?void 0:x.evictedDeviceCaption)||"",x!=null&&x.displayMessage?(c(),z(AUTH_STEPS.evictedDevices),!0):!1}catch{return!1}return!1};return{email,errors,isLoading:isLoading$2,isLoadingRetry,initialLoading,nextStepAfterGetLogins,currentStep:currentStep$2,needUseRecaptcha,passwordAuth,currentLogin,captcha,checkCode,errorMessages,errorText,gaNameComponent,verificationComponentName,registerProviderInfo,isSmsAuth,isAuthWithPassword,phoneUnsupported,phoneUnsupportedMessage,phoneTechnicalSim,recommendProvider,recommendOfferId,phoneInfoToken,promoCode,isPromoCodeValid,promoCodeResultText,promoCodeMessage,promoCodeId,canonicalValue,authPhoneNotFound,registrationSettings,selectedPromoCodeOffer,isAutoLoginLoading,logins,evictedSession,captchaId,cookieCaptcha,captchaRefreshValue,itemsLoginType:g,phone:m,loginMethod:v,isLoginSmotreshka:S,isLoginN3:y,isLoginSms:C,isAuth:E,isReg:L,isRecaptchaUsed:T,passwordMinLength:b,passwordMaxLength:_,errorLogin:I,phoneMask:R,statusForLoginInput:D,messageForCaptchaInput:O,statusForCaptchaInput:N,passwordErrorText:H,correctPhoneLength:W,statusForPhoneInput:M,usePlusInPhoneMethods:A,isVercontServerEnabled:w,regTrialsEnabled:k,phoneCleaned:F,incompletePhoneInitialFlag:B,incompletePhone:K,textBelowRegButton:G,messageForPhoneInput:U,login:Y,contentBlock:J,changeStep:z,clientAnalyticsShowPage:le,clientAnalyticsClick:ne,setLoading:Q,onClickOnForgotPassword:q,onInput:te,flushProcess:se,changePhoneClick:re,retry:me,showErrorPage:ce,gaEventAuth:ie,gaEventOnceAuth:Ce,prepareFinishRegistration:_e,onRecaptchaExecute:he,contactVerification:Se,qrLogin:Le,redirectAfterLogin:Te,start:Pe,auth:Ne,authWithPromoCode:we,verifyAndGetLogins:V,promoCodeRegister:Z,handleError:ye,sendNewPassword:xe,sendCheckedCode:De,getLogins:Re,continueWithoutPromoCode:Oe,signIn:Ee,selectLogin:Fe,tryAgainSelectPromoOffer:Ue,handleSwitch:$e,afterFinishRegistration:Be,checkEvictedSession:ke,initCurrentStep:()=>{let x=AUTH_STEPS.start;getPromoCodeCookie()&&!r.value&&(x=AUTH_STEPS.promoOffers),z(x)}}},log$l=logger$1("router-utils"),getRelatedRoutes=(t,e)=>{const s=parseListRouteName(e);return s?t.getRoutes().filter(n=>{var i;return parseRouteName(n.name).endsWith(`-from-${s}`)&&((i=n.components)==null?void 0:i.default)}):[]},getRouteRecordRaw=(t,e)=>{var s;return{name:t.name,path:t.path,component:t.components.default,props:(s=t.props)==null?void 0:s.default,sensitive:e}},prioritizeRoute=(t,e)=>{t.addRoute(getRouteRecordRaw(e,!0))},resetRoute=(t,e)=>{t.addRoute(getRouteRecordRaw(e,!1))},parseRouteName=t=>(t||"").toString(),hasModalInRouteName=t=>parseRouteName(t).includes("modal")||!1,hasPlayerInRouteName=t=>parseRouteName(t).includes("with-player")||!1,hasWatchInRoutePath=t=>t.endsWith("/watch"),parseListRouteName=t=>{const e=parseRouteName(t);return hasModalInRouteName(e)?e.split("-modal-from-")[1]:hasPlayerInRouteName(e)?e.replace("-with-player",""):e},getRouteNameForModal=(t,e)=>`${t}-modal-from-${e}`,getRouteNameForPlayer=t=>`${t}-with-player`,prioritizeRelatedRoutes=(t,e)=>{const s=getRelatedRoutes(t,e);s.length&&log$l.info("prioritize routes",s.map(n=>n.name)),s.forEach(n=>{prioritizeRoute(t,n)})},deprioritizeRelatedRoutes=(t,e)=>{const s=getRelatedRoutes(t,e);s.length&&log$l.info("deprioritize routes",s.map(n=>n.name)),s.forEach(n=>{resetRoute(t,n)})},usePlayerVideo=()=>{const t=useStore();return{playingTime:computed(()=>selectors.player.playingTimeSelector(t))}},useEpgHelpers=()=>{const t=useStore(),e=(d,u)=>{if(d!=null&&d.scheduledFor){const h=selectors.appInfo.commonServerTimeSelector(t)||dayjs().unix(),f=(u||h)-d.scheduledFor.begin.unix();return boundMinMax(0,f/d.duration,1)}return 0},s=d=>{const u=dayjs().unix();return c(u,d)},n=d=>{const u=dayjs().unix();return d.scheduledFor.begin.unix()>u},i=(d,u)=>{var g;if(!d||!(u!=null&&u.scheduledFor))return!1;const h=dayjs().unix(),f=u.scheduledFor.begin.unix()>h-getDvrDepthLimit(d);return!d.liveOnly&&!((g=d.medias)!=null&&g[0].liveOnly)&&!(u!=null&&u.dvrDisabled)&&f},r=d=>{var u;return(u=d.actuallyScheduledFor)!=null&&u.isValidForTimeline?d.actuallyScheduledFor.begin:d.scheduledFor.begin},o=d=>{var u;return(u=d.actuallyScheduledFor)!=null&&u.isValidForTimeline&&d.actuallyScheduledFor.end?d.actuallyScheduledFor.end:d.scheduledFor.end},a=d=>d?formatTimeHM(r(d)):"",l=d=>d?formatTimeHM(o(d)):"",c=(d,u,h=!1)=>{var f,g;if((f=u.actuallyScheduledFor)!=null&&f.isValidForTimeline&&!h){const p=u.actuallyScheduledFor.begin.unix(),m=((g=u.actuallyScheduledFor.end)==null?void 0:g.unix())||0;return d>=p&&d<m}return d>=u.scheduledFor.begin.unix()&&d<u.scheduledFor.end.unix()};return{getProgramTimelineProgress:e,isProgramLive:s,isProgramInFuture:n,isDvrAvailableForProgram:i,getProgramStartTime:r,getProgramStartTimeHM:a,getProgramEndTime:o,getProgramEndTimeHM:l,isTimestampRelatesToProgram:c}},log$k=logger$1("tv-epg-v2"),useEpgSchedule=()=>{const t=useStore(),e=useSSRContext(),{isTimestampRelatesToProgram:s}=useEpgHelpers(),n=ref(!1),i=computed(()=>t.tvEpgV2.full.isLoading),r=L=>{const T=getChannelMediaScheduleId(L);return t.tvEpgV2.full.schedules[T]},o=L=>{var b;return(((b=r(L))==null?void 0:b.pages)||[]).reduce((_,I)=>(I.coveredInterval&&_.push({...I,coveredInterval:parseInterval(I.coveredInterval)}),_),[])},a=L=>{var _;const b=(((_=r(L))==null?void 0:_.pagesWithEvents)||[]).reduce((I,P)=>{for(const R of P.events)I.set(R.id,R);return I},new Map);
5return enhancePrograms(Array.from(b.values()))},l=L=>{const T=dayjs().unix();return f(L,T)},c=L=>{const T=dayjs().unix(),b=p(L,T);return a(L).slice(b+1)},d=L=>{const T=r(L),b=o(L);if(!T||!b.length)return!1;const{lastRequestTime:_,regularUpdateIntervalSec:I}=T,P=(_||0)+(I||0),R=dayjs().unix();return P>R},u=(L,T)=>o(L).find(b=>T>=b.coveredInterval.begin.unix()&&T<b.coveredInterval.end.unix()),h=(L,T,b)=>o(L).filter(_=>T<=_.coveredInterval.end.unix()&&b>=_.coveredInterval.begin.unix()),f=(L,T)=>{const b=p(L,T);if(b>-1)return a(L)[b]},g=(L,T)=>{const b=p(L,T);if(b>-1)return a(L)[b+1]},p=(L,T)=>{const b=a(L);let _=b.findIndex(P=>P.scheduledFor?s(T,P):!1);const I=_>0&&b[_+1]||void 0;return(_<0||I&&s(T,I))&&(_=b.findIndex(P=>P.scheduledFor?s(T,P,!0):!1)),_},m=(L,T)=>a(L).find(b=>b.id===T),v=(L,T,b)=>a(L).filter(_=>_.scheduledFor.begin.unix()>=T&&_.scheduledFor.begin.unix()<=b),S=async L=>{var T;if(!d(L))try{const b=getChannelMediaScheduleId(L);if(!b||(T=t.tvEpgV2.full.schedules[b])!=null&&T.isEmpty)return;t.tvEpgV2.full.isLoading=!0;const _=await getScheduleIndex(b,{languageCode:t.languageCode,ctx:e});if(_){const{pages:I,regularUpdate:P}=_;t.tvEpgV2.full.schedules[b]={pages:I,pagesWithEvents:I.map(R=>({...R,events:[]})),regularUpdateIntervalSec:(P==null?void 0:P.intervalSec)||0,lastRequestTime:dayjs().unix(),isEmpty:!(I!=null&&I.length)}}}catch(b){log$k.error("getScheduleIndex error",b)}finally{t.tvEpgV2.full.isLoading=!1}},y=async(L,T="")=>{try{await S(L);const b=getChannelMediaScheduleId(L),_=await getScheduleSpread(b,{params:T?{centralPageId:T}:{},languageCode:t.languageCode,ctx:e});if(_!=null&&_.pagesWithEvents){const I=_.pagesWithEvents.reduce((P,R)=>(P[R.pageId]=R,P),{});for(const P of t.tvEpgV2.full.schedules[b].pagesWithEvents){const R=I[P.pageId];R&&(P.events=R.events,P.coveredInterval=R.coveredInterval)}}}catch(b){log$k.error("getScheduleSpread error",b)}};return{isLoading:i,getPages:o,getPrograms:a,getLiveProgram:l,getNextPrograms:c,findProgramById:m,findProgramByTimestamp:f,findNextProgramByTimestamp:g,findProgramsByRange:v,loadIndex:S,loadSpread:y,loadAllDay:async(L,T)=>{await S(L);const b=dayjs.unix(T),_=b.hour(0).minute(0).second(0).unix(),I=b.hour(23).minute(59).second(59).unix(),P=h(L,_,I).map(R=>R.pageId);t.tvEpgV2.full.isLoading=!0,await Promise.all(P.map(R=>y(L,R))),t.tvEpgV2.full.isLoading=!1},loadByTimestamp:async(L,T)=>{var b;if(!n.value){n.value=!0;try{await S(L);const _=(b=u(L,T))==null?void 0:b.pageId;_&&(t.tvEpgV2.full.isLoading=!0,await y(L,_),t.tvEpgV2.full.isLoading=!1)}finally{n.value=!1}}}}},log$j=logger$1("player-playing"),usePlayerPlaying=()=>{const t=useStore(),{isTimestampRelatesToProgram:e}=useEpgHelpers(),s=useEpgSchedule(),{playingTime:n}=usePlayerVideo(),i=computed(()=>selectors.player.playingChannelIdSelector(t)),r=computed(()=>selectors.player.playingChannelSelector(t)),o=computed(()=>t.player.playing.program||void 0),a=computed(()=>t.player.nextProgram),l=computed(()=>{var u;return((u=o.value)==null?void 0:u.id)||null}),c=computed(()=>{var u;return(u=o.value)!=null&&u.logoUrl?getResizedImageUrl(o.value.logoUrl,880,494):""});return{playingChannelId:i,playingChannel:r,playingProgram:o,playingProgramId:l,playingProgramImage:c,nextProgram:a,actualizePlayingAndNextPrograms:async()=>{if(!r.value||!n.value)return;let u=!1,h;(!o.value||o.value&&!e(n.value,o.value))&&(u=!0,h=s.findProgramByTimestamp(r.value,n.value)),t.player.playing.program||(u=!0,await s.loadByTimestamp(r.value,n.value),h=s.findProgramByTimestamp(r.value,n.value)),u&&(t.player.playing.program=h,t.player.nextProgram=s.findNextProgramByTimestamp(r.value,n.value),log$j.info("actualize playing program for",dayjs.unix(n.value).format("HH:mm:ss"),t.player.playing.program))}}},log$i=logger$1("channels-hook"),useChannels=()=>{const t=useStore(),e=useSSRContext(),{t:s}=useTranslation(),n=computed(()=>selectors.tvChannels.genresSelector(t)),i=computed(()=>selectors.tvChannels.favoritesSelector(t)),r=u=>selectors.tvChannels.channelByIdSelector(t,u),o=u=>u.map(({channelId:h})=>{var m;const f=r(h),g=(m=f==null?void 0:f.relevantGenres)==null?void 0:m.map(v=>v.genreId),p=!!i.value[h];return{...f,genres:g,inFavorites:p,program:{live:selectors.tvEpgV2.onAirLiveProgramSelector(t,f),next:selectors.tvEpgV2.onAirNextProgramSelector(t,f)}}}),a=u=>n.value.reduce((h,f)=>{const g=o(u).filter(p=>{var m,v;return((m=p==null?void 0:p.genres)==null?void 0:m.includes(f.id))||((v=p==null?void 0:p.genres)==null?void 0:v.includes(f.t
5itle))||null});return g.length>0&&(h[f.id]=g),h},{});return{availableChannels:o,findChannelById:r,getChannelUrl:u=>{const f=getChannelLogo(u);return f?{src:f,width:Math.round(200*16/9),height:200}:{src:""}},getChannelsGroupedByGenre:a,getChannelsWord:u=>plurar(u,s("channel"),s("channel_genitive"),s("channels_genitive")),loadChannelsGroupedByGenre:async(u="")=>{var h;try{const f=((h=await getOfferShowcaseChannels(u,{ctx:e,languageCode:t.languageCode}))==null?void 0:h.channels)||[];return a(f)}catch(f){return log$i.error(f),{}}}}},getEpisodesForSeasonIndex=(t,e=0)=>{var n,i,r;const s=((n=t.details)==null?void 0:n.seasons)||[];return((r=(i=t.details)==null?void 0:i.episodes)==null?void 0:r.filter(o=>{var a,l;return!s.length||((a=o.preview)==null?void 0:a.seasonId)===((l=s[e])==null?void 0:l.id)}))||[]},log$h=logger$1("vod"),useVod=()=>{const t=ref(-1),e=ref(0),s=useStore(),n=useRoute(),{isAnonymous:i}=useAuth(),{t:r}=useTranslation(),o=useSSRContext(),a=computed(()=>selectors.vod.sourcesSelector(s)),l=computed(()=>{var V;return((V=n.params.sourceId)==null?void 0:V.toString())||"archive"}),c=computed(()=>a.value[l.value]),d=computed(()=>l.value==="archive"?"archive":"vod"),u=computed(()=>{var V;return((V=c.value)==null?void 0:V.sourceType)||""}),h=computed(()=>u.value==="archive"),f=computed(()=>!!c.value),g=computed(()=>selectors.vod.sourcesLoadedSelector(s)),p=computed(()=>selectors.vod.sourcesLoadingSelector(s)),m=computed(()=>selectors.profiles.isProfileLoadingSelector(s)),v=computed(()=>selectors.profiles.isProfileLoadedSelector(s)),S=computed(()=>selectors.vod.titleEnhancedLoadingSelector(s,l.value,L.value)),y=computed(()=>selectors.vod.titleEnhancedLoadedSelector(s,l.value,L.value)),C=computed(()=>selectors.player.playingTitleIdSelector(s)),E=computed(()=>selectors.vod.playingTitleSelector(s)),L=computed(()=>{var V;return(V=n.params.titleId)==null?void 0:V.toString()}),T=computed(()=>selectors.vod.titleEnhancedSelector(s,l.value,L.value)),b=computed(()=>T.value||E.value),_=computed(()=>{var V;return!!((V=T.value)!=null&&V.preview)}),I=computed(()=>selectors.promoElements.mediaIdSelector(s,l.value,L.value)),P=computed(()=>{var Z;const V=(Z=n.params.seasonNum)==null?void 0:Z.toString();return V?parseInt(V):-1}),R=computed(()=>{var V,Z;return((Z=(V=b.value)==null?void 0:V.details)==null?void 0:Z.seasons)||[]}),D=computed(()=>{var V;return((V=R.value)==null?void 0:V.length)||0}),O=computed(()=>selectors.player.playingSeasonIdSelector(s)),N=computed(()=>!p.value&&!m.value&&v.value&&(s.vod.sources[l.value]&&y.value&&!S.value||!s.vod.sources[l.value])),H=computed(()=>!!R.value.find(V=>V.number===P.value)),W=computed(()=>N.value&&(!p.value&&!_.value||P.value>=0&&D.value&&!H.value)),M=computed(()=>{const V=R.value.findIndex(Z=>Z.number===P.value);return V>=0?V:0}),A=computed(()=>!(_.value&&f.value)&&i.value&&!S.value||P.value>=0&&D.value&&!H.value),w=computed(()=>selectors.pauses.pausesVodItemsSelector(s)),k=computed(()=>selectors.player.playingMediaItemIdSelector(s)),F=computed(()=>{var V;return(V=n.params.mediaItemId)==null?void 0:V.toString()}),B=computed(()=>selectors.vod.currentCategoryIdSelector(s,l.value)),K=computed(()=>selectors.vod.currentCategorySelector(s,l.value)),G=computed(()=>{var V;return((V=c.value)==null?void 0:V.categories)||{}}),U=computed(()=>Object.values(G.value).sort((V,Z)=>V.priority-Z.priority)),Y=computed(()=>Se(T.value)),J=computed(()=>{var V;return((V=K.value)==null?void 0:V.titles)||[]}),z=computed(()=>{var V;return(V=R.value)==null?void 0:V.map((Z,ye)=>({href:getTitlePathWithSeason(l.value,L.value,String(Z.number)),index:ye,number:Z.number,text:Z.title?Z.title:`${r("season")} ${Z.number}`}))}),le=computed(()=>selectors.vod.selectedSeasonIndexSelector(s,l.value,L.value,P.value,t.value)),ae=computed(()=>C.value===L.value),ue=computed(()=>{var V,Z;return(Z=(V=T.value)==null?void 0:V.pauses)==null?void 0:Z[0]}),ne=computed(()=>{var V,Z;return((Z=(V=b.value)==null?void 0:V.details)==null?void 0:Z.episodes)||[]}),Q=computed(()=>Le(le.value)),q=computed(()=>selectors.player.playingEpisodeIdSelector(s)),te=computed(()=>{var V;return(V=n.params.episodeId)==null?void 0:V.toString()}),se=computed(()=>{var V;return((V=Q.value)==null?void 0:V.length)||0}),re=computed(()=>selectors.vod.prevEpisodeSelector(s)),me=computed(()=>{var V,Z;return(Z=(V=re.value)==null?void 0:V.preview)==null?void 0:Z.id}),ce=computed(()=>{var xe,De,Re;const V=((De=(xe=T.value)==null?void 0:xe.details)==null?void 0:De.episodes
5)||[],Z=ae.value?q.value:(Re=ue.value)==null?void 0:Re.episodeId,ye=V.findIndex(Oe=>{var Ee;return((Ee=Oe.preview)==null?void 0:Ee.id)===Z});return ye>=0?V[ye+1]:null}),ie=computed(()=>{var V,Z;return(Z=(V=ce.value)==null?void 0:V.preview)==null?void 0:Z.id}),Ce=computed(()=>selectors.vod.playingEpisodeTitleSelector(s)),_e=computed(()=>selectors.vod.archivePosterWidthProportionSelector(s)),he=computed(()=>selectors.vod.archivePosterHeightProportionSelector(s)),Se=V=>selectors.vod.categoryIdFromTitleSelector(s,V,l.value),Le=(V=0)=>getEpisodesForSeasonIndex(b.value,V),Te=V=>selectors.vod.posterWidthProportionSelector(s,V),Pe=V=>selectors.vod.posterHeightProportionSelector(s,V);return{seasonIndex:t,seasonIndexFromRoute:M,seasonNumRoute:P,refreshKey:e,sources:a,currentSourceId:l,currentSource:c,sourceType:d,sourceTypeFe:u,isArchive:h,isCurrentSourceAvailable:f,vodSourcesLoaded:g,vodSourcesLoading:p,isProfileLoading:m,isProfileLoaded:v,isTitleLoading:S,isDataLoaded:N,isTitleUnavailable:W,is404:A,vodPauses:w,playingMediaItemId:k,currentCategoryId:B,currentCategory:K,categories:G,sortedCategories:U,currentTitleId:L,currentTitle:T,playingTitle:E,playingTitleId:C,currentMediaItemId:F,currentTitleCategoryId:Y,titles:J,itemsForSelectorSingle:z,selectedSeasonIndex:le,episodes:ne,episodesForNav:Q,currentEpisodeId:te,episodesForNavLength:se,playingEpisodeId:q,previousEpisode:re,previousEpisodeId:me,nextEpisode:ce,nextEpisodeId:ie,playingEpisodeTitle:Ce,posterWidthProportionForArchive:_e,posterHeightProportionForArchive:he,hasSeasons:D,seasons:R,playingSeasonId:O,isCurrentTitleAvailable:_,currentMediaId:I,isPlayingTitleEqualCurrentTitle:ae,getCategoryIdFromTitle:Se,getPosterWidthProportion:Te,getPosterHeightProportion:Pe,getPosterAspectRatio:V=>Pe(V)/Te(V),loadCurrentTitle:async()=>{_.value||(h.value?await actions.tvChannels.loadChannelsAndGenres(s,o):await actions.vod.loadSourceCategories(s,o,l.value));try{await actions.vod.loadTitleVod(s,o,l.value,L.value,n)}catch(V){V instanceof ApiError?log$h.error(V.reqInfo):log$h.error(V)}}}},scrollEverythingToTop=(t=!1)=>{setTimeout(()=>{const e=document.querySelector(".modal"),s=document.querySelector(".scroll-container");t?window.scrollTo(0,0):e?e.scrollTo(0,0):s&&s.scrollTo(0,0)},0)},log$g=logger$1("play"),usePlay=()=>{const t=useStore(),e=useSSRContext(),s=useRoute(),n=useRouter(),i=useEvents(),{isAnonymous:r}=useAuth(),{playingChannelId:o,actualizePlayingAndNextPrograms:a}=usePlayerPlaying(),{findChannelById:l}=useChannels(),{playingTime:c}=usePlayerVideo(),d=useEpgSchedule(),{isProgramLive:u,getProgramStartTime:h}=useEpgHelpers(),{currentSourceId:f}=useVod(),g=computed(()=>selectors.player.isArchiveSelector(t)),p=computed(()=>selectors.player.playingTitleIdSelector(t)),m=computed(()=>selectors.player.isPlayingSelector(t)),v=async()=>{actions.player.releaseOverlay(t),actions.player.setIsPlaying(t,!1),actions.player.setIsPrerollVisible(t,!1)},S=async _=>{var H;const I=_.channelId,P=_.slug||"",R=getChannelWatchPath(I,P);if(r.value){actions.notifications.showAuthAndRegNotification(t,R);return}const D=((H=s.params.channelId)==null?void 0:H.toString())||"",O=l(I),N=selectors.appInfo.serverTimeSelector(t);c.value!==N&&actions.player.updatePlayingTime(t,N),t.player.playing.program=null,m.value&&o.value!==I&&i.emit(EVENTS.player.pause),actions.player.setPlayingChannelId(t,I),actions.seo.setMetaTitle(t,actions.tvChannels.buildChannelMetaTitle(t,I)),await a(),isDvrDisabled(O)&&(log$g.info("cannot start playing a program in a dvrRestricted channel"),actions.player.exitFullscreen(t)),hasWatchInRoutePath(s.path)&&D===I?(t.player.isLive=!0,i.emit(EVENTS.player.reloadStream)):await n.push(R),actions.player.expandPlayer(t),actions.player.lockScroll(t),scrollEverythingToTop(document.documentElement.clientWidth<600),actions.tvChannels.updateRecentlyWatched(t,I)},y=async({channelId:_,programId:I,hasAnyNotification:P})=>{var H;const R=getChannelWatchPath(_);if(r.value){actions.notifications.showAuthAndRegNotification(t,R);return}const D=((H=s.params.channelId)==null?void 0:H.toString())||"",O=l(_),N=d.findProgramById(O,I);if(!O){log$g.warn("channel was not selected");return}if(!N){log$g.warn("program was not found"),actions.notifications.showDvrRestrictionWithButtonVisibleSelector(t);return}if(isDvrRestricted(O)){if(!u(N)){actions.notifications.showDvrRestrictionWithButtonVisibleSelector(t);return}actions.notifications.showDvrRestrictionNotification(t)}if(isDvrDisabled(O)&&(log$g.info("cannot start playing a program in a dvrRestricted channel"),actions.player.exitFullscreen(t)),actions.player.setIsLive(t,!1),t.player.playing.program=null,hasWatchInRoutePath(s.path)&&D===_)actions.player.updatePlayingTime(t,h(N).unix()),i.emit(EVENTS.player.reloadStream);else{m.value&&i.emit(EVENTS.player.pause),actions.player.setPlayingChannelId(t,_),actions.seo.setMetaTitle(t,actions.tvChannels.buildChannelMetaTitle(t,_));
5try{await actions.tvChannels.loadPlaybackInfoDetails(t,e,O,P)}catch(W){log$g.info(W)}actions.player.updatePlayingTime(t,h(N).unix()),await n.push(R)}await a(),actions.playerPlayingChannel.unmarkPlayingLanguageAsUnavailable(t),scrollEverythingToTop(document.documentElement.clientWidth<600),log$g.info("playProgram",N)},C=async({channelId:_,timestamp:I})=>{const P=l(_),R=d.findProgramByTimestamp(P,I);R&&(await y({channelId:_,programId:R.id}),actions.player.updatePlayingTime(t,I))},E=async _=>{const I=_.sourceId,P=_.titleId,R=_.episodeId||"",D=!!_.withPreroll,O=getTitleWatchPath(I,P,R);if(r.value){actions.notifications.showAuthAndRegNotification(t,O);return}D||actions.player.setIsPrerollVisible(t,!1),await n.push(O),scrollEverythingToTop(document.documentElement.clientWidth<600)},L=async _=>{const I=_.titleId,P=_.episodeId||"",R=_.mediaItemId||"",D=!!_.withPreroll,O=getTitleWatchPath("archive",I,P,R);if(r.value){actions.notifications.showAuthAndRegNotification(t,O);return}D||actions.player.setIsPrerollVisible(t,!1),await n.push(O),scrollEverythingToTop(document.documentElement.clientWidth<600)};return{playChannel:S,playProgram:y,playTvPause:C,playVodTitle:E,playArchiveTitle:L,playPreviousEpisode:async()=>{var P,R,D;await v();const _=selectors.vod.prevEpisodeSelector(t),I=(P=_==null?void 0:_.preview)==null?void 0:P.id;if(I)try{g.value?await L({titleId:p.value,episodeId:I,mediaItemId:(D=(R=_==null?void 0:_.details)==null?void 0:R.mediaItems[0])==null?void 0:D.id}):await E({sourceId:f.value,titleId:p.value,episodeId:I})}catch{}useGaEvent({category:"player_controls",action:"Клик по кнопке - Предыдущий эпизод",vod_name:f.value})},playNextEpisode:async()=>{var P,R,D;await v();const _=selectors.vod.nextEpisodeSelector(t),I=(P=_==null?void 0:_.preview)==null?void 0:P.id;if(I)try{g.value?await L({titleId:p.value,episodeId:I,mediaItemId:(D=(R=_==null?void 0:_.details)==null?void 0:R.mediaItems[0])==null?void 0:D.id}):await E({sourceId:f.value,titleId:p.value,episodeId:I})}catch{}useGaEvent({category:"player_controls",action:"Клик по кнопке - Следующий эпизод",vod_name:f.value})},resetOverlayAndPrerollAndPlaybackSession:v}},currentStep$1=ref("Welcome"),isLoading$1=ref(!1),pinCode=ref(""),log$f=logger$1("welcome-screen"),useWelcomeScreen=()=>{const t=useStore(),e=useRoute(),s=useSSRContext(),{t:n}=useTranslation(),i=computed(()=>!selectors.account.isAnonymousSelector(t)&&selectors.modals.isWelcomeScreenOpenSelector(t)&&e.name!=="reg"&&e.name!=="login"&&e.name!=="qr-success"),r=d=>{isLoading$1.value=d},o=d=>{currentStep$1.value=d},a=(d="")=>{setTimeout(()=>{var u,h;d==="selectProfile"&&(h=(u=t.siteConfig)==null?void 0:u.profileConfirmation)!=null&&h.showProfileConfirmation&&(t.common.isProfileConfirmationOverlayVisible=!0)},200),actions.modals.hideWelcomeScreen(t),actions.common.unlockBodyScroll(t)};return{currentStep:currentStep$1,isLoading:isLoading$1,pinCode,isWelcomeScreenVisible:i,setLoading:r,changeStep:o,close:a,goToView:async()=>{var d;a(),cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,"1"),e.path==="/adult"&&((d=t.account.profile)==null?void 0:d.restriction)!=="adult"&&actions.modals.showAdultOnboarding(t),await managingLogout({ctx:s,languageCode:t.languageCode}).catch(u=>{log$f.error(u)})},afterSetPinCode:async()=>{var d,u;await actions.authAndReg.getAccount(t,s),cookieStore.set(COOKIE_NAMES.welcomeScreenConfirmed,"1"),(u=(d=t.siteConfig)==null?void 0:d.welcomeScreen)!=null&&u.isPinRequired?o(WELCOME_SCREEN_STEPS.SuccessPin):(a(),actions.notifications.showProfileNotification(t,n("welcome_screen_success_set_pin_code")),await managingLogout({languageCode:t.languageCode,ctx:s}))}}},currentStep=ref("Start"),isLoading=ref(!1),disableProtection=ref(!1),log$e=logger$1("profile-protected"),useProfileProtected=()=>{const t=useStore(),e=useSSRContext(),{t:s}=useTranslation(),n=computed(()=>selectors.modals.isProfileProtectedOpenSelector(t));return{currentStep,isLoading,disableProtection,isProfileProtectedModalVisible:n,changeStep:a=>{currentStep.value=a},setLoading:a=>{isLoading.value=a},updatePinCode:async a=>{var l,c,d;try{(c=(l=t.account)==null?void 0:l.profile)!=null&&c.id&&(await actions.profiles.update(t,e,t.account.profile.id,{data:{Name:t.account.profile.name,Pin:a}}),await actions.authAndReg.getAccount(t,e),actions.notifications.showProfileNotification(t,s(a?"profile_protection_success_set_pin_code":"profile_protection_disabled_set_pin_code").replace("%profile%",((d=t.account.profile)==null?void 0:d.name)||"")),actions.modals.hideProfileProtected(t))}catch(u){throw log$e.error(u),u}}}},months={ru:["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"]},minutesInHour=60,fullDigitsCount=2;class DateTime{static timestamp(){return Math.round(convertToSeconds(Date.now(),"millisecond"))}static getHM(e=new Date){const s=`${e.getHours()}`,n=`${e.getMinutes()}`;return s.padStart(fullDigitsCount,"0")+":"+n.padStart(fullDigitsCount,"0")}
5static getUTCHMFromEpoch(e=DateTime.timestamp()){return DateTime.getHM(new Date(convertToMilliseconds(e,"second")))}static getDMonth(e=new Date){const s=String(e.getDate()),n=`${e.getMonth()+1}`;return`${s.padStart(fullDigitsCount,"0")}.${n.padStart(fullDigitsCount,"0")}`}static getDFullMonth(e=new Date){return`${e.getDate()} ${months.ru[e.getMonth()]}`}static getEpochDay(){return Math.floor(convertToDays(Date.now(),"millisecond"))}static fromEpochDay(e=DateTime.getEpochDay()){const s=new Date(convertToMilliseconds(e,"day"));return s.setHours(0),s}static prettyTimeHMS(e,s){const n=Math.floor(Math.max(e,0)),i=Math.floor(convertToHours(n,"second")),r=Math.floor(n/minutesInHour)%minutesInHour,o=n%minutesInHour;return(s||i?`${String(i).padStart(fullDigitsCount,"0")}:`:"")+`${String(r).padStart(fullDigitsCount,"0")}:${String(o).padStart(fullDigitsCount,"0")}`}static prettifyPlayerTime(e,s){return DateTime.prettyTimeHMS(e,s>convertToSeconds(1,"hour"))+" / "+DateTime.prettyTimeHMS(s)}}const dateAfterNDays=t=>dayjs().add(t,"day").format("DD.MM.YYYY"),expireDate=t=>{if(!t)return"";const e=new Date(t*THRESHOLDS.subscribes.dateUTCMultiplier);return t>0?`${DateTime.getDMonth(e)}.${e.getFullYear()}`:`${DateTime.getDMonth(new Date)}.${new Date().getFullYear()}`},popupCenter=(t,e="yakassaPopup",s=500,n=600)=>{const i=window.screenLeft!==void 0?window.screenLeft:window.screenX,r=window.screenTop!==void 0?window.screenTop:window.screenY,o=window.innerWidth?window.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width,a=window.innerHeight?window.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,l=o/window.screen.availWidth,c=(o-s)/2/l+i,d=(a-n)/2/l+r,u=window.open(t,e,`
6      popup
7      scrollbars=yes,
8      width=${s/l},
9      height=${n/l},
10      top=${d},
11      left=${c}
12      `);return u==null||u.focus(),u},useSubscriptions=()=>{const t=useSSRContext(),e=logger$1("subscription-hook"),s=useRoute(),n=useRouter(),i=useStore(),{t:r}=useTranslation(),{changeStep:o}=useAuthAndReg(),a=ref(!1),l=ref(0),c=computed(()=>{var A,w,k;return((k=(w=(A=i.payment)==null?void 0:A.method)==null?void 0:w.card)==null?void 0:k.last4)||""}),d=computed(()=>i.payment.yakassaSubscriptions),u=computed(()=>{var A;return((A=s.query.token)==null?void 0:A.toString())||""}),h=computed(()=>JSON.stringify(i.gaParams)),f=A=>{actions.notifications.showProfileNotification(i,A.resStatus===HTTP_CODES.NOT_FOUND?r("something_went_wrong"):A.message,"error-circle")},g=(A=0,w=[])=>[...A>0?["archive"]:[],...w].filter(k=>i.vod.sources[k]).map(k=>i.vod.sources[k].title).join(", "),p=A=>{var k;const w=(k=A==null?void 0:A.cancellation_details)==null?void 0:k.reason;i.qs.qrPayment.isError=!!u.value,i.qs.serverError.message=r(w?`qs_${w}`:"something_went_wrong"),v()},m=A=>{if(i.qs.qrPayment.isError=!!u.value,i.qs.serverError.code=A.code,s.name==="reg"||s.name==="login"){o(AUTH_STEPS.subscriptionFailed);return}A.code?A.message?i.qs.serverError.message=A.message:i.qs.serverError.message=r("something_went_wrong"):i.qs.serverError.message=r("error_server_unavailable"),v()},v=()=>{u.value||(actions.modals.hideQs(i),actions.player.hidePlayer(i),actions.player.resetVideoData(i),n.replace(`/acquiring-status?subscribed=false&source_url=${encodeURIComponent(s.fullPath)}`).then(()=>{}))},S=async()=>{var F,B;const A=await managingMethods({ctx:t,languageCode:i.languageCode});if(!A)return;const w=A.find(K=>K.name==="password"),k=A.find(K=>K.name==="with-verified-contacts")&&((B=(F=i.account)==null?void 0:F.user)==null?void 0:B.phone);return k&&w?QS_VERIFICATION_SUBSCRIPTION_STEPS.selectVerification:k?QS_VERIFICATION_SUBSCRIPTION_STEPS.phoneVerification:QS_VERIFICATION_SUBSCRIPTION_STEPS.passwordVerification},y=async()=>{try{const A=selectors.payment.subscriptionsInRetrySelector(i),w=[];A.forEach(k=>{w.push(cancelSubscription(k==null?void 0:k.id,{params:{token:u.value},ctx:t,languageCode:i.languageCode}))}),await Promise.all(w)}catch(A){m(A)}},C=async(A,w,k=!1,F="")=>{var K,G,U,Y;const B=s.name==="reg"||s.name==="login";if(k&&F){const J=popupCenter(w);if(localStore.set(LOCAL_STORAGE_NAMES.unsubscriptionRetention,{currentSubscription:i.unsubscriptionRetention.currentSubscription,settings:i.unsubscriptionRetention.settings,subscriptionOptions:i.unsubscriptionRetention.subscriptionOptions,yakassaSubscriptionId:F}),!J){location.href=w;return}await n.push(`/acquiring-status?unsub_retention=true&subscription_id=${F}`)}else A!=null&&A.trialAvailable&&((K=A==null?void 0:A.trial)!=null&&K.channels)&&(A!=null&&A.channels)&&((U=(G=A==null?void 0:A.trial)==null?void 0:G.channels)==null?void 0:U.length)>((Y=A==null?void 0:A.channels)==null?void 0:Y.length)&&!B?(i.qs.confirmationUrl=w,actions.modals.hideQs(i),actions.modals.showTrialGift(i)):location.href=w},E=()=>{const A={};return u.value&&(A.token=u.value),i.qs.qsTransactionId&&(A.qs_transaction_id=i.qs.qsTransactionId),A},L=A=>{var k;let w=location.origin;if(s.name==="qr-payment")w+=makePath(i,"/qr-payment"),w+="?",w+=new URLSearchParams({token:u.value,expires_at:((k=s.query.expires_at)==null?void 0:k.toString())||"",utm_source:"qr_purchase",ga_params:h.value});else if(s.name==="reg"||s.name==="login"){const F=new URLSearchParams(window.location.search);F.append("acquiring-status","1"),w+=makePath(i,`${window.location.pathname}?${F.toString()}`)}else{const F={utm_source:"blocked_content",source_url:encodeURIComponent(s.fullPath),ga_params:h.value};w+=makePath(i,"/acquiring-status"),w+="?",A!=null&&A.hasSubscriptionShop&&(F.sub_shop="true"),A!=null&&A.hasUnsubscriptionRetention&&(F.unsub_retention="true"),w+=new URLSearchParams(F)}return w.toString()},T=A=>{const w={subscribed:"true",utm_source:"blocked_content"};let k="/acquiring-status";return k+="?",A!=null&&A.hasUnsubscriptionRetention?w.unsub_retention="true":A!=null&&A.hasSubscriptionShop||(w.source_url=encodeURIComponent(s.fullPath)),k+=new URLSearchParams(w),k.toString()},b=async(A,w)=>{var Y;let k;const F=A.offerId,B=((Y=A.subscriptionMethod)==null?void 0:Y.name)||A.subscriptionMethods[0].name,K=i.qs.usePm&&paymentMethodAvailableSelector(i);let G;const U={ctx:t,languageCode:i.languageCode,params:E()};switch(B){case SUBSCRIPTION_METHOD_NAMES.UPSALE:G={Id:F},k=await createSubscriptionUpsale$1({...U,data:G});break;case SUBSCRIPTION_METHOD_NAMES.UPSALE_V2:case SUBSCRIPTION_METHOD_NAMES.UPSALE_V21:G={Id:F,CreateSubscriptionToken:A==null?void 0:A.createSubscriptionToken},k=await createSubscriptionUpsaleV2$1({...U,data:G});break;case SUBSCRIPTION_METHOD_NAMES.AUTHENTICATED:G={Id:F},k=await createSubscription$2({...U,data:G});break;case SUBSCRIPTION_METHOD_NAMES.PHONE_COLLECT_INSTANT:case SUBSCRIPTION_METHOD_NAMES.PHONE_COLLECT_DELAYED:G={Id:F},k=await createSubscriptionWithVerifiedPhone$1({...U,data:G});break;default:G={offer_id:F,use_pm:K,return_url:L(w),create_subscription_token:A.createSubscriptionToken},A.trialAvailable?(G.create_subscription_token=A.createSubscriptionToken,k=await createYakassaSubscriptionV2$1({...U,data:G})):k=await createYakassaSubscription$1({...U,data:G});break}return k},_=async(A,w,k)=>{var B,K,G,U,Y,J,z,le,ae,ue;if(!A){e.error("Subscription was not provided");return}i.qs.tempSubscription||(i.qs.tempSubscription=A),actions.qs.startLoading(i),actions.utmLabels.resetUtmLabels(i),await y();const F=((B=A.subscriptionMethod)==null?void 0:B.name)||A.subscriptionMethods[0].name;try{actions.tokensV2.removeAssetTokens(i);const ne=await b(A,w);if(YAKASSA_SUBSCRIPTION_METHODS.includes(F)){await actions.payment.loadYakassaSubscriptions(i,t,u.value).cat
12ch(()=>{});const Q=(K=d.value)==null?void 0:K.find(se=>(se==null?void 0:se.offer.id)===(A==null?void 0:A.offerId)),q=(G=ne==null?void 0:ne.last_payment)==null?void 0:G.paid,te=(Y=(U=ne==null?void 0:ne.last_payment)==null?void 0:U.confirmation)==null?void 0:Y.confirmation_url;if(q&&u.value){i.qs.qrPayment.isPaid=!0,i.qs.qrPayment.title=A.title,i.qs.qrPayment.expiresAt=expireDate((Q==null?void 0:Q.expires_at)||0);return}if(te){await C(A,te,w==null?void 0:w.hasUnsubscriptionRetention,(Q==null?void 0:Q.id)||"");return}if(!q){k&&(w!=null&&w.hasUnsubscriptionRetention)&&k(),p(ne==null?void 0:ne.last_payment);return}}if(s.name==="reg"||s.name==="login"){o(AUTH_STEPS.subscriptionSuccess);return}actions.modals.hideQs(i),actions.player.hidePlayer(i),actions.player.resetVideoData(i),await n.replace(T(w))}catch(ne){const Q=(z=(J=ne.response)==null?void 0:J.data)==null?void 0:z.code,q=(le=ne.response)==null?void 0:le.status;if(Q===YAKASSA_RESPONSE_CODES.SUBSCRIPTION_ALREADY_EXISTS){await actions.payment.loadYakassaSubscriptions(i,t,u.value).catch(()=>{});const te=(ae=d.value)==null?void 0:ae.find(me=>{var ce;return((ce=me==null?void 0:me.offer)==null?void 0:ce.id)===A.offerId}),se=te==null?void 0:te.last_payment,re=(ue=se==null?void 0:se.confirmation)==null?void 0:ue.confirmation_url;(se==null?void 0:se.status)===SUBSCRIPTION_STATUSES.PENDING&&re?await C(A,re,w==null?void 0:w.hasUnsubscriptionRetention,(te==null?void 0:te.id)||""):(actions.registration.disableTrials(i),m(ne),k&&k())}else if(Q===YAKASSA_RESPONSE_CODES.NO_VERIFIED_PHONE||q===HTTP_CODES.FORBIDDEN&&Q===SUBSCRIPTION_FORBIDDEN_ERROR_CODE)u.value||actions.modals.hideQs(i),actions.modals.showPhoneVerification(i);else if(Q===CONTACT_VERIFICATION_OUTDATED_ERROR_CODE){actions.qs.startLoading(i);const te=await S();te&&(u.value||actions.modals.hideQs(i),actions.qs.additionalActionsGoToStepByName(i,te),actions.modals.showVerificationSubscription(i))}else m(ne)}finally{actions.qs.stopLoading(i)}},I=(A,w)=>{var U;const k=selectors.payment.yakassaSubscriptionsSelector(i),{dateUTCMultiplier:F}=THRESHOLDS.subscribes,B=k.find(Y=>Y.id===A.id),K=A.yakassa?((B==null?void 0:B.expires_at)||0)*F:Date.parse(((U=A.autoRenewInfo)==null?void 0:U.currentPeriodExpiresAt)||"");if(!K)return"";const G=new Date(K);return r(w).replace("%expire%",DateTime.getDMonth(G))},P=computed(()=>selectors.payment.currentSubscriptionsSelectorV2(i)),R=ref(null),D=ref(0),O=()=>{R.value=setTimeout(async()=>{var A;await actions.payment.loadCurrentSubscriptions(i,t),D.value++,(A=P.value)!=null&&A[0].suspensionInfo&&D.value<3&&O()},1e4)};return{createSubscription:_,getSubscriptionVodSourcesList:g,getTextWithExpireDate:I,handleError:m,renewWithExistingPm:async A=>{var k;const w=(k=i.payment.method)==null?void 0:k.id;if(!(A&&w)){e.error("subscriptionOptionId or paymentMethodId are not defined",A,w);return}actions.qs.startLoading(i);try{await renewSubscriptionWithExistedPm(A,{data:{payment_method_id:w},ctx:t,languageCode:i.languageCode});const F=await getLastPayment(A,{ctx:t,languageCode:i.languageCode}).catch(B=>(e.error(B),null));isPaymentSuccessful((F==null?void 0:F.status)||"")?(await actions.tvChannels.loadTvData(i,t),await actions.payment.loadYakassaSubscriptions(i,t)):(l.value++,actions.notifications.showProfileNotification(i,r("retry_unable_to_renew_with_current_card"),"error-circle"),l.value>=3&&(cookieStore.set(COOKIE_NAMES.retryBlockForCard,c.value,{expires:new Date(Date.now()+convertToMilliseconds(1,"hour"))}),l.value=0,a.value=!0))}catch(F){f(F)}finally{actions.qs.stopLoading(i)}},renewWithNewPm:async A=>{var G,U,Y,J;if(!A){e.error("subscriptionOptionId is not defined");return}const w=d.value.find(z=>z.id===A),k=(U=(G=w==null?void 0:w.last_payment)==null?void 0:G.confirmation)==null?void 0:U.confirmation_url;if(k)return window.location.href=k;actions.qs.startLoading(i);const F=`${location.origin}${makePath(i,"/acquiring-status")}?subscription_id=${A}&utm_source=retry`,B=await renewSubscriptionWithNewPm(A||"",{data:{return_url:F},ctx:t,languageCode:i.languageCode}).catch(z=>{f(z)}).finally(()=>{actions.qs.stopLoading(i)}),K=(J=(Y=B==null?void 0:B.last_payment)==null?void 0:Y.confirmation)==null?void 0:J.confirmation_url;if(K)return window.location.href=K;actions.notifications.showProfileNotification(i,r("retry_unable_to_renew_with_new_card"),"error-circle")},switchAutoRenew:async(A,w,k,F)=>{var G;if(!A)return;const B=A.managementMethods[0].name,K={ctx:t,languageCode:i.languageCode};try{if(B===MANAGEMENT_METHOD_NAMES.YAKASSA){const U=yakassaSubscriptionsSelector(i).find(Y=>Y.id===A.id);if(!U)return;w==="enable"?await activateSubscription(U.id,K):await cancelSubscription(U.id,K)}else if(B===MANAGEMENT_METHOD_NAMES.AUTO_RENEWABLE)w==="enable"?await enableAutoRenewSubscription((A==null?void 0:A.id)||"",K):await disableAutoRenewSubscription((A==null?void 0:A.id)||"",K);else return;F&&F(),showAutoRenewNotification(i,replaceByNotEmpty(r(`auto_renew_${w}d_notification`),"%subscription%",((G=A.renderingData)==null?void 0:G.t
12itle)||""),w),actions.qs.startLoading(i),await actions.payment.loadCurrentSubscriptions(i,t),O()}catch(U){k&&k(),f(U)}finally{actions.qs.stopLoading(i)}},startTimerCheckRenewSubscription:O,checkSubscriptionPaymentStatus:async(A,w=!1)=>{var F;let k;try{const B=await getLastPayment(A,{ctx:t,languageCode:i.languageCode},w);(B==null?void 0:B.status)===SUBSCRIPTION_STATUSES.CANCELED&&((F=B==null?void 0:B.cancellation_details)==null?void 0:F.reason)===SUBSCRIPTION_STATUSES_REASONS.CANCELED_BY_MERCHANT?k=await checkPaymentStatusTrials(t,i.languageCode,A):(B==null?void 0:B.status)===SUBSCRIPTION_STATUSES.PENDING?k=!1:k=isPaymentSuccessful((B==null?void 0:B.status)||"")}catch(B){k=!1,e.error(B)}return k}}},log$d=logger$1("utils"),inBrowser=typeof window<"u",noop$1=()=>{},isPassiveSupported=()=>{if(!inBrowser)return;let t=!1;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("test",noop$1,e),window.removeEventListener("test",noop$1)}catch(e){log$d.error(e)}return t},getStyle=(t,e)=>typeof getComputedStyle<"u"?getComputedStyle(t,null).getPropertyValue(e):t.style[e],getOverflow=t=>getStyle(t,"overflow")+getStyle(t,"overflow-y")+getStyle(t,"overflow-x"),findScrollableParent=t=>{if(!inBrowser)return;if(!(t instanceof HTMLElement))return window;let e=t;for(;e&&!(e===document.body||e===document.documentElement||!e.parentNode);){if(/(scroll|auto)/.test(getOverflow(e)))return e;e=e.parentNode}return window},LISTENING_EVENTS=["scroll","wheel","mousewheel","resize","animationend","transitionend","touchmove"];class Lazy{constructor(){$(this,"images",[]);$(this,"cached",reactive(new Set));$(this,"findVisibleImagesToLoad");$(this,"listeningTargets",[]);$(this,"listeningTargetsIndex",0);this.findVisibleImagesToLoad=throttle(this._findVisibleImagesToRender.bind(this),200)}findImageByEl(e){return this.images.find(s=>s.el===e)}addToQueue(e){this.images.push(e),this.addListenerTarget(window),e.parent&&this.addListenerTarget(e.parent),this.findVisibleImagesToLoad()}removeFromQueue(e){const s=this.images.findIndex(n=>n.el===e);if(s>-1){const n=this.images[s];n.parent&&this.removeListenerTarget(n.parent),this.removeListenerTarget(window),this.images.splice(s,1)}}addListenerTarget(e){if(!e)return;let s=this.listeningTargets.find(n=>n.el===e);return s?s.childrenCount++:(s={el:e,id:++this.listeningTargetsIndex,childrenCount:1,listened:!0},this.bindEvents(s.el),this.listeningTargets.push(s)),this.listeningTargetsIndex}removeListenerTarget(e){this.listeningTargets.forEach((s,n)=>{s.el===e&&(s.childrenCount--,s.childrenCount||(this.unbindEvents(s.el),this.listeningTargets.splice(n,1)))})}bindEvents(e){LISTENING_EVENTS.forEach(s=>{const n=isPassiveSupported()?{passive:!0}:void 0;e.addEventListener(s,this.findVisibleImagesToLoad,n)})}unbindEvents(e){LISTENING_EVENTS.forEach(s=>{e.removeEventListener(s,this.findVisibleImagesToLoad)})}_findVisibleImagesToRender(){const e=[];this.images.forEach(s=>{if(!s.el||!s.el.parentNode){e.push(s.el);return}s.checkInView()&&(this.cached.add(s.src),e.push(s.el))}),e.forEach(s=>{const n=this.images.findIndex(i=>i.el===s);n>-1&&this.images.splice(n,1)})}}const lazy=new Lazy,PRELOAD=1,PRELOAD_TOP=0;let LazyImage$1=class{constructor({el:e,src:s}){$(this,"el");$(this,"src","");$(this,"parent");this.src=s,this.el=e}setParent(e){this.parent=e}checkInView(){const e=this.el.getBoundingClientRect();return e.top<window.innerHeight*PRELOAD&&e.bottom>PRELOAD_TOP&&e.left<window.innerWidth*PRELOAD&&e.right>0}update(e){this.src=e}};const getScrollPosition=(t=DOM_SCROLL_CONTAINER_ID)=>{var e;return((e=document.getElementById(t))==null?void 0:e.scrollTop)||document.documentElement.scrollTop||0},setScrollPosition=(t,e=DOM_SCROLL_CONTAINER_ID)=>{const s=document.getElementById(e);s&&(s.scrollTop=t)},bindScrollEvents=(t,e=DOM_SCROLL_CONTAINER_ID)=>{var s;document.addEventListener("scroll",t),(s=document.getElementById(e))==null||s.addEventListener("scroll",t)},unbindScrollEvents=(t,e=DOM_SCROLL_CONTAINER_ID)=>{var s;document.removeEventListener("scroll",t),(s=document.getElementById(e))==null||s.removeEventListener("scroll",t)},useScrollWatcher=()=>
12({setOnScrollHandler:(e,s)=>{onMounted(()=>{bindScrollEvents(s,e)}),onUnmounted(()=>{unbindScrollEvents(s,e)})},getScrollPosition:e=>getScrollPosition(e),setScrollPosition:(e,s)=>setScrollPosition(s,e)}),log$c=logger$1("popup-notices-hook"),usePopupNotices=()=>{const t=getCurrentInstance(),e=useStore(),s=useRouter(),n=useSSRContext(),{setGaParams:i}=useMetrics(),r=computed(()=>selectors.popupNotices.currentElementSelector(e)),o=computed(()=>{var p,m;return((m=(p=r.value)==null?void 0:p.renderingData)==null?void 0:m.title)||""}),a=computed(()=>{var p,m;return((m=(p=r.value)==null?void 0:p.renderingData)==null?void 0:m.subTitle)||""}),l=computed(()=>{var p,m;return((m=(p=r.value)==null?void 0:p.renderingData)==null?void 0:m.description)||""}),c=computed(()=>{var p,m;return((m=(p=r.value)==null?void 0:p.renderingData)==null?void 0:m.ctaButtonText)||""}),d=computed(()=>{var p,m;return((m=(p=r.value)==null?void 0:p.renderingData)==null?void 0:m.footerText)||""}),u=computed(()=>{var p;return((p=r.value)==null?void 0:p.images)||[]}),h=computed(()=>{var p;return((p=r.value)==null?void 0:p.externalUrl)||""}),f=computed(()=>selectors.popupNotices.currentElementActionMethodSelector(e)),g=async()=>{var p;if(!r.value){log$c.error("Current element is not set");return}if(!f.value){log$c.error("No action method was set although popup notice have CTA button, element:",JSON.parse(JSON.stringify(r.value)));return}i({popup_id:r.value.id}),r.value.utmLabels&&actions.utmLabels.setUtmLabels(e,r.value.utmLabels),f.value===PROMO_ELEMENTS_ACTION_METHODS.qsOffersSetV1&&((p=r.value)!=null&&p.offersSetId)?await handleOffersSet(e,n,r.value.offersSetId):f.value===PROMO_ELEMENTS_ACTION_METHODS.externalUrl?(window.open(h.value,"_blank"),actions.utmLabels.resetUtmLabels(e)):INTERNAL_REF_PROMO_ELEMENTS_ACTION_METHODS.includes(f.value)?await actions.popupNotices.handleInternalRef(e,n,s,t==null?void 0:t.appContext.config.globalProperties.$events,r.value):log$c.error("Unsupported action method: ",f.value),await actions.popupNotices.reportAction(e,n,"action"),actions.popupNotices.close(e)};return onMounted(()=>actions.popupNotices.setShowTimeMs(e,Date.now())),{title:o,subTitle:a,description:l,buttonText:c,footerText:d,images:u,onClickActionButton:g}},useWindowWidth=()=>{const t=ref(document.documentElement.clientWidth),s=debounce(()=>t.value=document.documentElement.clientWidth,200);return onMounted(()=>{window.addEventListener("resize",s)}),onUnmounted(()=>{window.removeEventListener("resize",s)}),{windowWidth:t}},store=useStore(),useNotification=()=>{const t=ref(!1),{windowWidth:e}=useWindowWidth();watch(e,s=>{s<TABLET_WINDOW_WIDTH_MIN&&!t.value?(t.value=!0,actions.common.lockBodyScroll(store)):s>=TABLET_WINDOW_WIDTH_MIN&&t&&(t.value=!1,actions.common.unlockBodyScroll(store))}),onBeforeUnmount(()=>{actions.common.unlockBodyScroll(store)})},log$b=logger$1("search-history"),searchContextToken=ref(""),searchContextTokenV2=ref(""),searchStringSource=ref(SEARCH_STRING_SOURCE.SEARCH_HISTORY),useSearchHistory=()=>{var P;const t=useSSRContext(),e=ref(SEARCH_STRING_SOURCE.MANUAL),s=ref([]),n=ref(null),i=useRoute(),r=useRouter(),o=useStore(),{sendUnifiedEvents:a}=useClientAnalytics(),l=ref(null),{t:c}=useTranslation(),d=ref(!!((P=i.query)!=null&&P.q)),u=ref(""),h=computed(()=>{var R,D,O,N,H;return((O=(D=(R=o.siteConfig)==null?void 0:R.globalSearch)==null?void 0:D.searchV2)==null?void 0:O.enabled)&&((H=(N=o.siteConfig)==null?void 0:N.tokens)==null?void 0:H.hasTokensV2)}),f=computed(()=>{var R,D,O;return(O=(D=(R=o.siteConfig)==null?void 0:R.globalSearch)==null?void 0:D.searchHistoryV1)==null?void 0:O.enabled}),g=computed(()=>selectors.tvChannels.favoritesSelector(o)),p=computed(()=>selectors.tokensV2.analyticsTokenSelector(o)),m=computed(()=>{var R,D;return((D=(R=i.query)==null?void 0:R.q)==null?void 0:D.toString())||""}),v=async R=>{if(f.value!==!1)try{const D=await postSearchHistoryStarted({ctx:t,languageCode:o.languageCode},{searchString:R,analyticsToken:p.value,searchStringSource:searchStringSource.value});searchStringSource.value=SEARCH_STRING_SOURCE.SEARCH_HISTORY,D&&(searchContextToken.value=D.searchContextToken,u.value=D.normalizedSearchString)}catch(D){log$b.error(D)}},S=async R=>{if(f.value!==!1)try{await postSearchHistoryFinished({ctx:t,languageCode:o.languageCode},{searchContextToken:searchContextToken.value,...R})}catch(D){log$b.error(D)}},y=async R=>{try{await postSearchHistoryUseTvChannel({ctx:t,languageCode:o.languageCode},{searchContextToken:searchContextToken.value,tvChannel:{id:R.id,title:R.name,keyNumber:R.keyNumber}})}catch(D){log$b.error(D)}useGaEvent({category:"global_search",action:"Клик по каналу в стрипе",channel_name:R.name,query:m.value})},C=async(R,D,O)=>{if(R.channel){try{await postSearchHistoryV2UseTvChannel({ctx:t,languageCode:o.languageCode},{analyticsToken:p.value,resultsGroupContext:{groupId:D.groupId,groupRenderingMethod:D.renderingMethods[0],relevanceScore:R.relevanceScore,itemPosition:O+1,displayedItemsCnt:D.itemsCount||0},searchContextTokenV2:searchContextTokenV2.value,tvChannel:{id:R.channel.i
12d,title:R.channel.name,keyNumber:R.channel.keyNumber}})}catch(N){log$b.error(N)}useGaEvent({category:"global_search",action:"Клик по каналу в стрипе",channel_name:R.channel.name,query:m.value})}},E=async(R,D)=>{try{await postSearchHistoryUseVodTitle({ctx:t,languageCode:o.languageCode},{searchContextToken:searchContextToken.value,vodTitle:{sourceId:D,titleId:R.id,title:R.title,originalTitle:R.originalTitle,hasSeries:R.hasSeries}})}catch(O){log$b.error(O)}useGaEvent({category:"global_search",action:"Клик по тайтлу в стрипе",vod_name:D,title_id:R.id,query:m.value})},L=async(R,D,O)=>{if(R.titlePreview&&R.sourceId){try{await postSearchHistoryV2UseVodTitle({ctx:t,languageCode:o.languageCode},{analyticsToken:p.value,resultsGroupContext:{groupId:D.groupId,groupRenderingMethod:D.renderingMethods[0],relevanceScore:R.relevanceScore,itemPosition:O+1,displayedItemsCnt:D.itemsCount||0},searchContextTokenV2:searchContextTokenV2.value,vodTitle:{sourceId:R.sourceId,titleId:R.titlePreview.id,title:R.titlePreview.title,originalTitle:R.titlePreview.originalTitle,hasSeries:R.titlePreview.hasSeries}})}catch(N){log$b.error(N)}useGaEvent({category:"global_search",action:"Клик по тайтлу в стрипе",vod_name:R.sourceId,title_id:R.titlePreview.id,query:m.value})}},T=async()=>{if((f.value||h.value)&&!selectors.account.isAnonymousSelector(o))try{const R=await getSearchHistory({ctx:t,languageCode:o.languageCode});R&&(s.value=(R==null?void 0:R.searchStrings)||[])}catch(R){log$b.error(R)}else s.value=localStore.get("gsearch_recent_queries")||[]},b=debounce(async R=>{var D,O,N,H,W,M;if(!R){n.value=null,await r.push({path:"/search",query:{}}),await T();return}await r.push({path:"/search",query:{q:R}});try{d.value=!0,l.value=null;const A=await getSearchV2({ctx:t,languageCode:o.languageCode,params:{queryString:R,queryStringSource:e.value,searchAssetToken:(D=o.tokensV2.assetTokens)==null?void 0:D.searchAssetToken}});if(A){const k=[...((O=A.searchResults)==null?void 0:O.resultsGroups)||[]].filter(B=>intersection$1(B.renderingMethods,SUPPORTED_SEARCH_GROUP_RENDERING_METHODS).length).reduce((B,K)=>(B[K.groupId]={...K,items:[]},B),{});(H=(N=A.searchResults)==null?void 0:N.tvChannels)==null||H.forEach(B=>{B.groupsMapping.forEach(K=>{var U;const G=selectors.tvChannels.channelByIdSelector(o,B.channelId);(U=k[K.groupId])==null||U.items.push({...B,channel:{id:B.channelId,name:getChannelTitle(G)||`ID ${B.channelId}`,image:{src:getChannelLogo(G),width:205,height:115},inFavorites:!!g.value[G==null?void 0:G.id],keyNumber:(G==null?void 0:G.keyNumber)||Number(G==null?void 0:G.strNumber)||0,program:selectors.tvEpgV2.onAirLiveProgramSelector(o,G)},relevanceScore:K.relevanceScore})})}),(M=(W=A.searchResults)==null?void 0:W.vodTitles)==null||M.forEach(B=>{B.groupsMapping.forEach(K=>{var G;return(G=k[K.groupId])==null?void 0:G.items.push({...B,relevanceScore:K.relevanceScore})})});for(const B in k){const K=k[B],G=[...K.items];K.itemsCount=G.length,K.hasMixedContent=!!(G!=null&&G.find(U=>U.channelId||U.sourceId==="archive")&&(G!=null&&G.find(U=>U.sourceId))),K.items=G.sort((U,Y)=>Y.relevanceScore-U.relevanceScore)}n.value=Object.values(k).filter(B=>B.items.length||B.showIfEmpty),searchContextTokenV2.value=A.searchContextTokenV2;const F={ui:{event:TClientAnalyticsUiEvent.pageUpdate,flow:"search-v2",page:"search_results",item:"",block:""},searchContext:{normalizedSearchString:A.searchStringNormalized}};n.value.length?(F.ui.item="search_strip_upsection_results",F.ui.block="strip_content"):F.ui.item="search_nothing_found",await a(F)}}catch(A){const w=A.response.status;return l.value={message:A.message||c("search_error_message"),code:A.response.status},w>=HTTP_CODES.BAD_REQUEST&&await a({ui:{event:TClientAnalyticsUiEvent.pageUpdate,flow:"search-v2",page:"search_results",item:"search_error"}}),log$b.error(A),[]}finally{d.value=!1}},THRESHOLDS.searchDelay),_=async()=>{var R;if(n.value){p.value||await actions.tokensV2.loadAssetTokens(o,t);const D=(R=n.value)==null?void 0:R.map(O=>({groupId:O.groupId,renderingMethod:O.renderingMethods[0],displayedItemsCnt:O.items.length}));try{await postReportSearch({ctx:t,languageCode:o.languageCode},{searchContextTokenV2:searchContextTokenV2.value,analyticsToken:p.value,groupsToDisplay:D})}catch(O){log$b.error(O)}}},I=R=>{if(R){const D=s.value.indexOf(R);D>-1&&s.value.splice(D,1),s.value.unshift(R),s.value.length>5&&s.value.pop(),localStore.set("gsearch_recent_queries",s.value)}};return onMounted(async()=>{await T(),p.value||await actions.tokensV2.loadAssetTokens(o,t),scrollEverythingToTop()}),{clickChannel:y,clickChannelV2:C,clickVodTitle:E,clickVodTitleV2:L,error:l,finish:S,isLoading:d,isSearchHistoryV1Enabled:f,isSearchV2Enabled:h,loadSearchHistory:T,normalizedSearchString:u,queryStringSource:e,recentQueries:s,report:_,resultGroups:n,saveQueryToLocalStore:I,search:b,searchContextToken,searchStringSource,start:v}},currentStepIndex=ref(0),useUnsubscriptionRetention=()=>{const t=useStore(),e=useSSRContext(),{switchAutoRenew:s,createSubscription:n}=useSubscriptions(),i=[UNSUBSCRIPTION_RETENTION_STEPS.advantages,UNSUBSCRIPTION_RETENTION_STEPS.question,UNSUBSCRIPTION_RETENTION_STEPS.offer],r=computed(()=>i[currentStepIndex.value]),o=computed(()=>{var p;return(p=t.unsubscriptionRetention.settings)==null?void 0:p.unsubscriptionReasons}),a=computed(()=>{var p,m;return(m=(p=t.unsubscriptionRetention.settings)==null?void 0:p.retentionMethods)==null?void 0:m[0]}),l=computed(()=>{var p;return(p=t.unsubscriptionRetention.subscriptionOptions)==null?void 0:p[0]}),c=async()=>{r.value===UNSUBSCRIPTION_RETENTION_STEPS.advantages&&await actions.unsubscriptionRetention.end(t,e,UNSUBSCRIPTION_RESULTS.retained,RETENTION_OFFER_RESULT.unoffered),currentStepIndex.value===0?t.unsubscriptionRetention.isOverlayVisible=!1:currentStepIndex.value--},d=async()=>{currentStepIndex.value!==i.length-1?currentStepIndex.value++:await f({unsubscriptionResult:UNSUBSCRIPTION_RESULTS.completed,retentionOfferResult:RETENTION_OFFER_RESULT.unoffered})},u=()=>{currentStepIndex.value=0},h=p=>n(p,{hasUnsubscriptionRetention:!0}
12,()=>actions.unsubscriptionRetention.end(t,e,UNSUBSCRIPTION_RESULTS.error,RETENTION_OFFER_RESULT.error)),f=async p=>{await s(t.unsubscriptionRetention.currentSubscription,"disable",async()=>await actions.unsubscriptionRetention.end(t,e,UNSUBSCRIPTION_RESULTS.error,RETENTION_OFFER_RESULT.unoffered),async()=>await actions.unsubscriptionRetention.end(t,e,p.unsubscriptionResult,p.retentionOfferResult)),currentStepIndex.value=0,t.unsubscriptionRetention.isOverlayVisible=!1};return{currentStep:r,reasons:o,retentionMethod:a,subscription:l,cancelSubscription:f,cancelUnsubscriptionRetention:async()=>{t.unsubscriptionRetention.isOverlayVisible=!1,currentStepIndex.value=0,await actions.unsubscriptionRetention.end(t,e,UNSUBSCRIPTION_RESULTS.retained,RETENTION_OFFER_RESULT.unoffered),useGaEvent({category:"unsubscription_retention",action:"Клик по кнопке - Остаться подписчиком",acquiring_type:"unsub"})},goToNextStep:d,goToPrevStep:c,goToStartStep:u,unsubscriptionRetentionCreateSubscription:h}};var __getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$6(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let ScrollWatcher=class extends Vue{constructor(){super(...arguments);$(this,"scrollElId",DOM_SCROLL_CONTAINER_ID)}getScrollPosition(){return getScrollPosition(this.scrollElId)}setScrollPosition(e){setScrollPosition(e,this.scrollElId)}async mounted(){bindScrollEvents(this.onScroll.bind(this),this.scrollElId)}beforeUnmount(){unbindScrollEvents(this.onScroll.bind(this),this.scrollElId)}onScroll(e){}};ScrollWatcher=__decorateClass$6([ComponentBase],ScrollWatcher);var __getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$5(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};const log$a=logger$1("vod");let Vod=class extends mixins(SequoiaComponent){constructor(){super(...arguments);$(this,"seasonIndex",-1);$(this,"refreshKey",0);$(this,"getTitlePath",getTitlePath)}get isSeoBot(){return selectors.seo.isSeoBotSelector(this.$store,this.$ssrContext)}get sources(){return selectors.vod.sourcesSelector(this.$store)}get currentSourceId(){var e;return((e=this.$route.params.sourceId)==null?void 0:e.toString())||"archive"}get currentSource(){return this.sources[this.currentSourceId]}get type(){return this.currentSourceId==="archive"?"archive":"vod"}get isArchive(){return this.type==="archive"}get isCurrentSourceAvailable(){return!!this.currentSource}get vodSourcesLoaded(){return selectors.vod.sourcesLoadedSelector(this.$store)}get vodSourcesLoading(){return selectors.vod.sourcesLoadingSelector(this.$store)}get isProfileLoading(){return selectors.profiles.isProfileLoadingSelector(this.$store)}get isProfileLoaded(){return selectors.profiles.isProfileLoadedSelector(this.$store)}get isTitleLoading(){return selectors.vod.titleEnhancedLoadingSelector(this.$store,this.currentSourceId,this.currentTitleId)}get isTitleLoaded(){return selectors.vod.titleEnhancedLoadedSelector(this.$store,this.currentSourceId,this.currentTitleId)}get isDataLoaded(){return!this.vodSourcesLoading&&!this.isProfileLoading&&this.isProfileLoaded&&(this.$store.vod.sources[this.currentSourceId]&&this.isTitleLoaded&&!this.isTitleLoading||!this.$store.vod.sources[this.currentSourceId])}get isTitleUnavailable(){return this.isDataLoaded&&(!this.vodSourcesLoading&&!this.isCurrentTitleAvailable||this.seasonNumRoute>=0&&this.hasSeasons&&!this.isSeasonAvailable)}get seasonNumRoute(){var s;const e=(s=this.$route.params.seasonNum)==null?void 0:s.toString();return e?parseInt(e):-1}get seasonIndexFromRoute(){const e=this.seasons.findIndex(s=>s.number===this.seasonNumRoute);return e>=0?e:0}get isSeasonAvailable(){return!!this.seasons.find(e=>e.number===this.seasonNumRoute)}get is404(){return!(this.isCurrentTitleAvailable&&this.isCurrentSourceAvailable)&&this.isAnonymous&&!this.isTitleLoading||this.seasonNumRoute>=0&&this.hasSeasons&&!this.isSeasonAvailable}get playingMediaItemId(){return selectors.player.playingMediaItemIdSelector(this.$store)}getCategoryIdFromTitle(e){return selectors.vod.categoryIdFromTitleSelector(this.$store,e,this.currentSourceId)}get currentCategoryId(){return selectors.vod.currentCategoryIdSelector(this.$store,this.currentSourceId)}get currentCategory(){return selectors.vod.currentCategorySelector(this.$store,this.currentSourceId)}get categories(){var e;return((e=this.currentSource)==null?void 0:e.categories)||{}}get sortedCategories(){return Object.values(this.categories).sort((e,s)=>e.priority-s.priority)}get playingTitle(){return selectors.vod.playingTitleSelector(this.$store)}get playingTitleId(){return selectors.player.playingTitleIdSelector(this.$store)}get currentTitle(){return selectors.vod.titleEnhancedSelector(this.$store,this.currentSourceId,this.currentTitleId)}get currentTitleId(){var e;return(e=this.$route.params.titleId)==null?void 0:e.toString()}get title(){return this.currentTitle||this.playingTitle}get currentTitleCategoryId(){return this.getCategoryIdFromTitle(this.currentTitle)}get isCurrentTitleAvailable(){var e;return!!((e=this.currentTitle)!=null&&e.preview)}get titles(){var e;return((e=this.currentCategory)==null?void 0:e.titles)||[]}get seasons(){var e,s;return((s=(e=this.title)==null?void 0:e.details)==null?void 0:s.seasons)||[]}get hasSeasons(){var e;return((e=this.seasons)==null?void 0:e.length)||0}get itemsForSelectorSingle(){var e;return(e=this.seasons)==null?void 0:e.map((s,n)=>({href:getTitlePathWithSeason(this.currentSourceId,this.currentTitleId,String(s.number)),index:n,number:s.number,text:s.title?s.title:`${this.getTranslation("season")} ${s.number}`}))}get selectedSeasonIndex(){return selectors.vod.selectedSeasonIndexSelector(this.$store,this.currentSourceId,this.currentTitleId,this.seasonNumRoute,this.seasonIndex)}get episodes(){var e,s;return((s=(e=this.title)==null?void 0:e.details)==null?void 0:s.episodes
12)||[]}getEpisodesForSeasonIndex(e=0){return getEpisodesForSeasonIndex(this.title,e)}get currentEpisodeId(){var e;return(e=this.$route.params.episodeId)==null?void 0:e.toString()}get episodesForNav(){return this.getEpisodesForSeasonIndex(this.selectedSeasonIndex)}get episodesForNavLength(){var e;return((e=this.episodesForNav)==null?void 0:e.length)||0}get playingEpisodeId(){return selectors.player.playingEpisodeIdSelector(this.$store)}get previousEpisode(){return selectors.vod.prevEpisodeSelector(this.$store)}get previousEpisodeId(){var e,s;return(s=(e=this.previousEpisode)==null?void 0:e.preview)==null?void 0:s.id}get nextEpisode(){return selectors.vod.nextEpisodeSelector(this.$store)}get nextEpisodeId(){var e,s,n,i;return((s=(e=this.nextEpisode)==null?void 0:e.preview)==null?void 0:s.id)||((i=(n=this.nextEpisode)==null?void 0:n.preview)==null?void 0:i.id)}get playingEpisodeTitle(){return selectors.vod.playingEpisodeTitleSelector(this.$store)}get posterWidthProportionForArchive(){return selectors.vod.archivePosterWidthProportionSelector(this.$store)}get posterHeightProportionForArchive(){return selectors.vod.archivePosterHeightProportionSelector(this.$store)}posterWidthProportion(e){return selectors.vod.posterWidthProportionSelector(this.$store,e)}posterHeightProportion(e){return selectors.vod.posterHeightProportionSelector(this.$store,e)}posterAspectRatio(e){return this.posterHeightProportion(e)/this.posterWidthProportion(e)}async loadCurrentTitle(){this.isCurrentTitleAvailable||(this.isArchive?await actions.tvChannels.loadChannelsAndGenres(this.$store,this.$ssrContext):await actions.vod.loadSourceCategories(this.$store,this.$ssrContext,this.currentSourceId));try{await actions.vod.loadTitleVod(this.$store,this.$ssrContext,this.currentSourceId,this.currentTitleId,this.$route)}catch(e){e instanceof ApiError?log$a.error(e.reqInfo):log$a.error(e)}}};Vod=__decorateClass$5([ComponentBase],Vod);const getEnvironment=t=>{const[e]=(t==null?void 0:t.split(":"))||[],{wlAppId:s}=getEnvVars();if(e){if(e.includes("localhost")||e.includes("127.0.0.1")||isPrivateIp(e))return"development";if(e.includes("test.seq.lfstrm.tv"))return"staging"}else return"unknown";return`production-${s}`},isPrivateIp=t=>{const e=t.split(".");return e[0]==="10"||e[0]==="172"&&parseInt(e[1],10)>=16&&parseInt(e[1],10)<=31||e[0]==="192"&&e[1]==="168"},registrationPath=()=>{const t=wlDetector().isSmotreshka||wlDetector().isN3||wlDetector().isRzd?"/reg":"/login";return wlDetector().isKt?`${t}?type=reg`:t};var __getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$4(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let Channel=class extends mixins(SequoiaComponent){get channels(){return selectors.tvChannels.filteredChannelsSelector(this.$store)}get favoriteChannels(){return selectors.tvChannels.favoritesSelector(this.$store)}get currentGenre(){return selectors.tvChannels.currentGenreSelector(this.$store)}get isCurrentGenreFavorites(){return this.currentGenre===TV_SPECIAL_GENRES.favourite}getLiveProgram(t){return selectors.tvEpgV2.onAirLiveProgramSelector(this.$store,t)}getNextProgram(t){return selectors.tvEpgV2.onAirNextProgramSelector(this.$store,t)}getChannelById(t){return selectors.tvChannels.channelByIdSelector(this.$store,t)}getChannelLogo(t){return getChannelLogo(t)}getLiveProgramSrc(t){var e;return((e=this.getLiveProgram(t))==null?void 0:e.logoUrl)||""}getLiveProgramTitle(t){var e;return((e=this.getLiveProgram(t))==null?void 0:e.title)||""}getLiveProgramStartTimeHM(t){var e;return formatTimeHM((e=this.getLiveProgram(t))==null?void 0:e.scheduledFor.begin)}getNextProgramTitle(t){var e;return((e=this.getNextProgram(t))==null?void 0:e.title)||""}getNextProgramStartTimeHM(t){var e;return formatTimeHM((e=this.getNextProgram(t))==null?void 0:e.scheduledFor.begin)}getNextProgramStartsIn(t){var e;return(e=this.getNextProgram(t))==null?void 0:e.startsIn}};Channel=__decorateClass$4([ComponentBase],Channel);var __defProp=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$3(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=(n?o(e,s,i):o(i))||i);return n&&i&&__defProp(e,s,i),i};let PopupNotices=class extends Vue{async onIsAnyModelOpenChange(t){t||await actions.popupNotices.tryToShow(this.$store,this.$ssrContext)}async onIsProfileLoadedChange(t){t&&await actions.popupNotices.tryToShow(this.$store,this.$ssrContext)}async onIsReviewVisibleChange(t){t||await actions.popupNotices.tryToShow(this.$store,this.$ssrContext)}get isAnyModelOpen(){return selectors.modals.isAnyModalOpenSelector(this.$store)}get isPlayerMinimized(){return selectors.player.isMinimizedSelector(this.$store)}get isReviewVisible(){return selectors.notifications.isReviewVisibleSelector(this.$store)&&selectors.notifications.isReviewFromQueueVisible(this.$store)}async mounted(){window.addEventListener("visibilitychange",this.sendStatisticsOnSessionEnd),await actions.popupNotices.tryToShow(this.$store,this.$ssrContext)}unmounted(){window.removeEventListener("visibilitychange",this.sendStatisticsOnSessionEnd)}sendStatisticsOnSessionEnd(){this.$store.popupNotices.currentElement&&(actions.popupNotices.reportExitAction(this.$store,this.$ssrContext),actions.popupNotices.close(this.$store))}};__decorateClass$3([decorator("isAnyModelOpen")],PopupNotices.prototype,"onIsAnyModelOpenChange",1);__decorateClass$3([decorator("$store.profiles.isProfileLoaded")],PopupNotices.prototype,"onIsProfileLoadedChange",1);__decorateClass$3([decorator("isReviewVisible")],PopupNotices.prototype,"onIsReviewVisibleChange",1);PopupNotices=__decorateClass$3([ComponentBase],PopupNotices);var __getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$2(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let WithModalRoutes=class extends Vue{constructor(){super(...arguments);$(this,"listWithModalsRouteName","")}async mounted(){this.listWithModalsRouteName=parseListRouteName(this.$route.name),this.$store.returnRoute={name:this.listWithModalsRouteName},prioritizeRelatedRoutes(this.$router,this.listWithModalsRouteName)}updated(){const e=parseListRouteName(this.$route.name);this.listWithModalsRouteName!==e&&(deprioritizeRelatedRoutes(this.$router,this.listWithModalsRouteName),this.listWithModalsRouteName=e,this.$store.returnRoute={name:this.listWithModalsRouteName},prioritizeRelatedRoutes(this.$router,this.listWithModalsRouteName))}beforeUnmount(){this.$store.returnRoute="",deprioritizeRelatedRoutes(this.$router,this.listWithModalsRouteName)}};WithModalRoutes=__decorateClass$2([ComponentBase],WithModalRoutes);var __getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc$1(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let GetAndSetWindowWidth=class extends Vue{constructor(){super(...arguments);$(this,"windowWidth",document.documentElement.clientWidth);$(this,"isLoaded",!1)}actualizeWindowWidth(){debounce(()=>{this.windowWidth=document.documentElement.clientWidth,this.isLoaded=!0},200)()}};GetAndSetWindowWidth=__decorateClass$1([ComponentBase],GetAndSetWindowWidth);var __getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(t,e,s,n)=>{for(var i=n>1?void 0:n?__getOwnPropDesc(e,s):e,r=t.length-1,o;r>=0;r--)(o=t[r])&&(i=o(i)||i);return i};let WithResizeListener=class extends mixins(GetAndSetWindowWidth){async mounted(){this.actualizeWindowWidth(),window.addEventListener("resize",this.actualizeWindowWidth)}beforeUnmount(){window.removeEventListener("resize",this.actualizeWindowWidth)}};WithResizeListener=__decorateClass([ComponentBase],WithResizeListener);class LethargyService{constructor(e={}){$(this,"opts",{stability:8,sensitivity:50,tolerance:1.1,delay:50});$(this,"lastUpDeltas");$(this,"lastDownDeltas");$(this,"deltasTimestamp");this.opts={...this.opts,...e},this.lastUpDeltas=new Array(this.opts.stability*2).fill(null),this.lastDownDeltas=new Array(this.opts.stability*2).fill(null),this.deltasTimestamp=new Array(this.opts.stability*2).fill(null)}static extractWheelDelta(e){let s=0;
12return e.deltaY!=null?s=e.deltaY*-40:(e.detail!=null||e.detail===0)&&(s=e.detail*-40),s}handleEvent(e){const s=LethargyService.extractWheelDelta(e);return this.deltasTimestamp.push(Date.now()),this.deltasTimestamp.shift(),s>0?(this.lastUpDeltas.push(s),this.lastUpDeltas.shift(),this.isInertia(1)):(this.lastDownDeltas.push(s),this.lastDownDeltas.shift(),this.isInertia(-1))}isInertia(e){const s=e===-1?this.lastDownDeltas:this.lastUpDeltas;if(s[0]===null)return e;if(this.deltasTimestamp[this.opts.stability*2-2]+this.opts.delay>Date.now()&&s[0]===s[this.opts.stability*2-1])return!1;const n=s.slice(0,this.opts.stability),i=s.slice(this.opts.stability,this.opts.stability*2),r=n.reduce((c,d)=>c+d),o=i.reduce((c,d)=>c+d),a=r/n.length,l=o/i.length;return Math.abs(a)<Math.abs(l*this.opts.tolerance)&&this.opts.sensitivity<Math.abs(l)?e:!1}showLastUpDeltas(){return this.lastUpDeltas}showLastDownDeltas(){return this.lastDownDeltas}}const usePlayerSmokingWarning=()=>{const t=ref(!1),e=useStore(),s=computed(()=>{var o,a;const i=selectors.vod.playingTitleSelector(e),r=parseInt(((o=i==null?void 0:i.preview)==null?void 0:o.ageRating)||"");return i&&((a=e.siteConfig)==null?void 0:a.showSmokingWarning)&&r>=12&&t.value}),n=()=>{t.value=!0};return watch(t,i=>{i&&setTimeout(()=>{t.value=!1},5e3)}),{isSmokingWarningVisible:s,showSmokingWarning:n}};function getDefaultExportFromCjs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var urlToolkit={exports:{}};(function(t,e){(function(s){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,c,d){if(d=d||{},l=l.trim(),c=c.trim(),!c){if(!d.alwaysNormalize)return l;var u=a.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=a.normalizePath(u.path),a.buildURLFromParts(u)}var h=a.parseURL(c);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return d.alwaysNormalize?(h.path=a.normalizePath(h.path),a.buildURLFromParts(h)):c;var f=a.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var m=f.path,v=m.substring(0,m.lastIndexOf("/")+1)+h.path;p.path=a.normalizePath(v)}return p.path===null&&(p.path=d.alwaysNormalize?a.normalizePath(h.path):h.path),a.buildURLFromParts(p)},parseURL:function(l){var c=n.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(o,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};t.exports=a})()})(urlToolkit);var urlToolkitExports=urlToolkit.exports;function ownKeys(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),s.push.apply(s,n)}return s}function _objectSpread2(t){for(var e=1;e<arguments.length;e++){var s=arguments[e]!=null?arguments[e]:{};e%2?ownKeys(Object(s),!0).forEach(function(n){_defineProperty(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):ownKeys(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function _defineProperty(t,e,s){return e=_toPropertyKey(e),e in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},_extends.apply(this,arguments)}function _toPrimitive(t,e){if(typeof t!="object"||t===null)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return typeof e=="symbol"?e:String(e)}const isFiniteNumber=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)}
vendor: 4,924 bytes, line 12
12;let Events=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t}({}),ErrorTypes=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),ErrorDetails=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const noop=function(){},fakeLogger={trace:noop,debug:noop,log:noop,warn:noop,info:noop,error:noop};let exportedLogger=fakeLogger;function consolePrintFn(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):noop}function exportLoggerFunctions(t,...e){e.forEach(function(s){exportedLogger[s]=t[s]?t[s].bind(t):consolePrintFn(s)})}function enableLogs(t,e){if(self.console&&t===!0||typeof t=="object"){exportLoggerFunctions(t,"debug","log","info","warn","error");try{exportedLogger.log(`Debug logs enabled for "${e}
12" in hls.js version 1.4.10`)}catch{exportedLogger=fakeLogger}}else exportedLogger=fakeLogger}const logger=exportedLogger,DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(e){typeof e=="string"&&(e=AttrList.parseAttrList(e));for(const s in e)e.hasOwnProperty(s)&&(s.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(s)),this[s]=e[s])}decimalInteger(e){const s=parseInt(this[e],10);return s>Number.MAX_SAFE_INTEGER?1/0:s}hexadecimalInteger(e){if(this[e]){let s=(this[e]||"0x").slice(2);s=(s.length&1?"0":"")+s;const n=new Uint8Array(s.length/2);for(let i=0;i<s.length/2;i++)n[i]=parseInt(s.slice(i*2,i*2+2),16);return n}else return null}hexadecimalIntegerAsNumber(e){const s=parseInt(this[e],16);return s>Number.MAX_SAFE_INTEGER?1/0:s}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,s){const n=this[e];return n?parseFloat(n):s}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const s=DECIMAL_RESOLUTION_REGEX.exec(this[e]);if(s!==null)return{width:parseInt(s[1],10),height:parseInt(s[2],10)}}static parseAttrList(e){let s;const n={},i='"';for(ATTR_LIST_REGEX.lastIndex=0;(s=ATTR_LIST_REGEX.exec(e))!==null;){let r=s[2];r.indexOf(i)===0&&r.lastIndexOf(i)===r.length-1&&(r=r.slice(1,-1));const o=s[1].trim();n[o]=r}return n}}function isDateRangeCueAttribute(t){return t!=="ID"&&t!=="CLASS"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function isSCTE35Attribute(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"}class DateRange{constructor(e,s){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,s){const n=s.attr;for(const i in n)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==n[i]){logger.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=_extends(new AttrList({}),n,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=new Date(this.attr["END-DATE"]);isFiniteNumber(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(isFiniteNumber(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class LoadStats{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ElementaryStreamTypes={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class BaseSegment{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[ElementaryStreamTypes.AUDIO]:null,[ElementaryStreamTypes.VIDEO]:null,[ElementaryStreamTypes.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,s){const n=e.split("@",2),i=[];n.length===1?i[0]=s?s.byteRangeEndOffset:0:i[0]=parseInt(n[1]),i[1]=parseInt(n[0])+i[0],this._byteRange=i}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=urlToolkitExports.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Fragment extends BaseSegment{constructor(e,s){super(s),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new LoadStats,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const s=this.levelkeys.identity;if(s)this._decryptdata=s.getDecryptData(this.sn);else{const n=Object.keys(this.levelkeys);if(n.length===1)return this._decryptdata=this.levelkeys[n[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!isFiniteNumber(this.programDateTime))return null;const e=isFiniteNumber(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;
vendor: 6,743 bytes, line 12
12if(this.levelkeys){const s=Object.keys(this.levelkeys),n=s.length;if(n>1||n===1&&this.levelkeys[s[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const s=this.levelkeys[e];s&&!this._decryptdata&&(this._decryptdata=s.getDecryptData(this.sn))}}abortRequests(){var e,s;(e=this.loader)==null||e.abort(),(s=this.keyLoader)==null||s.abort()}setElementaryStreamInfo(e,s,n,i,r,o=!1){const{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:s,endPTS:n,startDTS:i,endDTS:r,partial:o};return}l.startPTS=Math.min(l.startPTS,s),l.endPTS=Math.max(l.endPTS,n),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ElementaryStreamTypes.AUDIO]=null,e[ElementaryStreamTypes.VIDEO]=null,e[ElementaryStreamTypes.AUDIOVIDEO]=null}}class Part extends BaseSegment{constructor(e,s,n,i,r){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new LoadStats,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=s,this.index=i;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const DEFAULT_TARGET_DURATION=10;class LevelDetails{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const s=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!s,this.advanced=this.endSN>e.endSN||s>0||s===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?isFiniteNumber(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||DEFAULT_TARGET_DURATION}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function base64Decode(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function getKeyIdBytes(t){const e=strToUtf8array(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}function changeEndianness(t){const e=function(n,i,r){const o=n[i];n[i]=n[r],n[r]=o};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function convertDataUriToArrayBytes(t){const e=t.split(":");let s=null;if(e[0]==="data"&&e.length===2){const n=e[1].split(";"),i=n[n.length-1].split(",");if(i.length===2){const r=i[0]==="base64",o=i[1];r?(n.splice(-1,1),s=base64Decode(o)):s=getKeyIdBytes(o)}}return s}function strToUtf8array(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}var KeySystems={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},KeySystemFormats={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function keySystemFormatToKeySystemDomain(t){switch(t){case KeySystemFormats.FAIRPLAY:return KeySystems.FAIRPLAY;case KeySystemFormats.PLAYREADY:return KeySystems.PLAYREADY;case KeySystemFormats.WIDEVINE:return KeySystems.WIDEVINE;case KeySystemFormats.CLEARKEY:return KeySystems.CLEARKEY}}var KeySystemIds={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function keySystemIdToKeySystemDomain(t){if(t===KeySystemIds.WIDEVINE)return KeySystems.WIDEVINE}function keySystemDomainToKeySystemFormat(t){switch(t){case KeySystems.FAIRPLAY:return KeySystemFormats.FAIRPLAY;case KeySystems.PLAYREADY:return KeySystemFormats.PLAYREADY;case KeySystems.WIDEVINE:return KeySystemFormats.WIDEVINE;case KeySystems.CLEARKEY:return KeySystemFormats.CLEARKEY}}function getKeySystemsForConfig(t){const{drmSystems:e,widevineLicenseUrl:s}=t,n=e?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter(i=>!!e[i]):[];return!n[KeySystems.WIDEVINE]&&s&&n.push(KeySystems.WIDEVINE),n}const requestMediaKeySystemAccess=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function getSupportedMediaKeySystemConfigurations(t,e,s,n){let i;switch(t){case KeySystems.FAIRPLAY:i=["cenc","sinf"];break;case KeySystems.WIDEVINE:case KeySystems.PLAYREADY:i=["cenc"];break;case KeySystems.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return createMediaKeySystemConfigurations(i,e,s,n)}function createMediaKeySystemConfigurations(t,e,s,n){return[{initDataTypes:t,persistentState:n.persistentState||"not-allowed",distinctiveIdentifier:n.distinctiveIdentifier||"not-allowed",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}
12"`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:s.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function sliceUint8(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const isHeader$2=(t,e)=>e+10<=t.length&&t[e]===73&&t[e+1]===68&&t[e+2]===51&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,isFooter=(t,e)=>e+10<=t.length&&t[e]===51&&t[e+1]===68&&t[e+2]===73&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,getID3Data=(t,e)=>{const s=e;let n=0;for(;isHeader$2(t,e);){n+=10;const i=readSize(t,e+6);n+=i,isFooter(t,e+10)&&(n+=10),e+=n}if(n>0)return t.subarray(s,s+n)},readSize=(t,e)=>{let s=0;return s=(t[e]&127)<<21,s|=(t[e+1]&127)<<14,s|=(t[e+2]&127)<<7,s|=t[e+3]&127,s},canParse$2=(t,e)=>isHeader$2(t,e)&&readSize(t,e+6)+10<=t.length-e,getTimeStamp=t=>{const e=getID3Frames(t);for(let s=0;s<e.length;s++){const n=e[s];if(isTimeStampFrame(n))return readTimeStamp(n)}},isTimeStampFrame=t=>t&&t.key==="PRIV"&&t.info==="com.apple.streaming.transportStreamTimestamp",getFrameData=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=readSize(t,4),n=10;return{type:e,size:s,data:t.subarray(n,n+s)}},getID3Frames=t=>{let e=0;const s=[];for(;isHeader$2(t,e);){const n=readSize(t,e+6);e+=10;const i=e+n;for(;e+8<i;){const r=getFrameData(t.subarray(e)),o=decodeFrame(r);o&&s.push(o),e+=r.size+10}isFooter(t,e)&&(e+=10)}return s},decodeFrame=t=>t.type==="PRIV"?decodePrivFrame(t):t.type[0]==="W"?decodeURLFrame(t):decodeTextFrame(t),decodePrivFrame=t=>{if(t.size<2)return;const e=utf8ArrayToStr(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},decodeTextFrame=t=>{if(t.size<2)return;if(t.type==="TXXX"){let s=1;const n=utf8ArrayToStr(t.data.subarray(s),!0);s+=n.length+1;const i=utf8ArrayToStr(t.data.subarray(s));return{key:t.type,info:n,data:i}}const e=utf8ArrayToStr(t.data.subarray(1));return{key:t.type,data:e}},decodeURLFrame=t=>{if(t.type==="WXXX"){if(t.size<2)return;let s=1;const n=utf8ArrayToStr(t.data.subarray(s),!0);s+=n.length+1;const i=utf8ArrayToStr(t.data.subarray(s));return{key:t.type,info:n,data:i}}const e=utf8ArrayToStr(t.data);return{key:t.type,data:e}},readTimeStamp=t=>{if(t.data.byteLength===8){const e=new Uint8Array(t.data),s=e[3]&1;let n=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return n/=45,s&&(n+=4772185884e-2),Math.round(n)}},utf8ArrayToStr=(t,e=!1)=>{const s=getTextDecoder();if(s){const c=s.decode(t);if(e){const d=c.indexOf("\0");return d!==-1?c.substring(0,d):c}return c.replace(/\0/g,"")}const n=t.length;let i,r,o,a="",l=0;for(;l<n;){if(i=t[l++],i===0&&e)return a;
12if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=t[l++],a+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=t[l++],o=t[l++],a+=String.fromCharCode((i&15)<<12|(r&63)<<6|(o&63)<<0);break}}return a};let decoder;function getTextDecoder(){return!decoder&&typeof self.TextDecoder<"u"&&(decoder=new self.TextDecoder("utf-8")),decoder}const Hex={hexDump:function(t){let e="";for(let s=0;s<t.length;s++){let n=t[s].toString(16);n.length<2&&(n="0"+n),e+=n}return e}},UINT32_MAX$1=Math.pow(2,32)-1,push=[].push,RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4};function bin2str(t){return String.fromCharCode.apply(null,t)}function readUint16(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function readUint32(t,e){const s=readSint32(t,e);return s<0?4294967296+s:s}function readSint32(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function writeUint32(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=s&255}function findBox(t,e){const s=[];if(!e.length)return s;const n=t.byteLength;for(let i=0;i<n;){const r=readUint32(t,i),o=bin2str(t.subarray(i+4,i+8)),a=r>1?i+r:n;if(o===e[0])if(e.length===1)s.push(t.subarray(i+8,a));else{const l=findBox(t.subarray(i+8,a),e.slice(1));l.length&&push.apply(s,l)}i=a}return s}function parseSegmentIndex(t){const e=[],s=t[0];let n=8;const i=readUint32(t,n);n+=4;const r=0,o=0;s===0?n+=8:n+=16,n+=2;let a=t.length+o;const l=readUint16(t,n);n+=2;for(let c=0;c<l;c++){let d=n;const u=readUint32(t,d);d+=4;const h=u&2147483647;if((u&2147483648)>>>31===1)return logger.warn("SIDX has hierarchical references (not supported)"),null;const g=readUint32(t,d);d+=4,e.push({referenceSize:h,subsegmentDuration:g,info:{duration:g/i,start:a,end:a+h-1}}),a+=h,d+=4,n=d}return{earliestPresentationTime:r,timescale:i,version:s,referencesCount:l,references:e}}function parseInitSegment(t){const e=[],s=findBox(t,["moov","trak"]);for(let i=0;i<s.length;i++){const r=s[i],o=findBox(r,["tkhd"])[0];if(o){let a=o[0],l=a===0?12:20;const c=readUint32(o,l),d=findBox(r,["mdia","mdhd"])[0];if(d){a=d[0],l=a===0?12:20;const u=readUint32(d,l),h=findBox(r,["mdia","hdlr"])[0];if(h){const f=bin2str(h.subarray(8,12)),g={soun:ElementaryStreamTypes.AUDIO,vide:ElementaryStreamTypes.VIDEO}[f];if(g){const p=findBox(r,["mdia","minf","stbl","stsd"])[0];let m;p&&(m=bin2str(p.subarray(12,16))),e[c]={timescale:u,type:g},e[g]={timescale:u,id:c,codec:m}}}}}}return findBox(t,["moov","mvex","trex"]).forEach(i=>{const r=readUint32(i,4),o=e[r];o&&(o.default={duration:readUint32(i,12),flags:readUint32(i,20)})}),e}function patchEncyptionData(t,e){if(!t||!e)return t;const s=e.keyId;return s&&e.isCommonEncryption&&findBox(t,["moov","trak"]).forEach(i=>{const o=findBox(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let a=findBox(o,["enca"]);const l=a.length>0;l||(a=findBox(o,["encv"])),a.forEach(c=>{const d=l?c.subarray(28):c.subarray(78);findBox(d,["sinf"]).forEach(h=>{const f=parseSinf(h);if(f){const g=f.subarray(8,24);g.some(p=>p!==0)||(logger.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Hex.hexDump(g)} -> ${Hex.hexDump(s)}`),f.set(s,8))}})})}),t}function parseSinf(t){const e=findBox(t,["schm"])[0];if(e){const s=bin2str(e.subarray(4,8));if(s==="cbcs"||s==="cenc")return findBox(t,["schi","tenc"])[0]}return logger.error("[eme] missing 'schm' box"),null}function getStartDTS(t,e){return findBox(e,["moof","traf"]).reduce((s,n)=>{const i=findBox(n,["tfdt"])[0],r=i[0],o=findBox(n,["tfhd"]).reduce((a,l)=>{const c=readUint32(l,4),d=t[c];if(d){let u=readUint32(i,4);if(r===1){if(u===UINT32_MAX$1)return logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),a;u*=UINT32_MAX$1+1,u+=readUint32(i,8)}const h=d.timescale||9e4,f=u/h;if(isFinite(f)&&(a===null||f<a))return f}return a},null);return o!==null&&isFinite(o)&&(s===null||o<s)?o:s},null)}function getDuration(t,e){let s=0,n=0,i=0;const r=findBox(t,["moof","traf"]);for(let o=0;o<r.length;o++){const a=r[o],l=findBox(a,["tfhd"])[0],c=readUint32(l,4),d=e[c];if(!d)continue;const u=d.default,h=readUint32(l,0)|(u==null?void 0:u.flags);let f=u==null?void 0:u.duration;h&8&&(h&2?f=readUint32(l,12):f=readUint32(l,8));const g=d.timescale||9e4,p=findBox(a,["trun"]);for(let m=0;m<p.length;m++){if(s=computeRawDurationFromSamples(p[m]),!s&&f){const v=readUint32(p[m],4);s=f*v}d.type===ElementaryStreamTypes.VIDEO?n+=s/g:d.type===ElementaryStreamTypes.AUDIO&&(i+=s/g)}}if(n===0&&i===0){let o=0;const a=findBox(t,["sidx"]);for(let l=0;l<a.length;
12l++){const c=parseSegmentIndex(a[l]);c!=null&&c.references&&(o+=c.references.reduce((d,u)=>d+u.info.duration||0,0))}return o}return n||i}function computeRawDurationFromSamples(t){const e=readUint32(t,0);let s=8;e&1&&(s+=4),e&4&&(s+=4);let n=0;const i=readUint32(t,4);for(let r=0;r<i;r++){if(e&256){const o=readUint32(t,s);n+=o,s+=4}e&512&&(s+=4),e&1024&&(s+=4),e&2048&&(s+=4)}return n}function offsetStartDTS(t,e,s){findBox(e,["moof","traf"]).forEach(n=>{findBox(n,["tfhd"]).forEach(i=>{const r=readUint32(i,4),o=t[r];if(!o)return;const a=o.timescale||9e4;findBox(n,["tfdt"]).forEach(l=>{const c=l[0];let d=readUint32(l,4);if(c===0)d-=s*a,d=Math.max(d,0),writeUint32(l,4,d);else{d*=Math.pow(2,32),d+=readUint32(l,8),d-=s*a,d=Math.max(d,0);const u=Math.floor(d/(UINT32_MAX$1+1)),h=Math.floor(d%(UINT32_MAX$1+1));writeUint32(l,4,u),writeUint32(l,8,h)}})})})}function segmentValidRange(t){const e={valid:null,remainder:null},s=findBox(t,["moof"]);if(s){if(s.length<2)return e.remainder=t,e}else return e;const n=s[s.length-1];return e.valid=sliceUint8(t,0,n.byteOffset-8),e.remainder=sliceUint8(t,n.byteOffset-8),e}function appendUint8Array(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function parseSamples(t,e){const s=[],n=e.samples,i=e.timescale,r=e.id;let o=!1;
vendor: 5,623 bytes, line 12
12return findBox(n,["moof"]).map(l=>{const c=l.byteOffset-8;findBox(l,["traf"]).map(u=>{const h=findBox(u,["tfdt"]).map(f=>{const g=f[0];let p=readUint32(f,4);return g===1&&(p*=Math.pow(2,32),p+=readUint32(f,8)),p/i})[0];return h!==void 0&&(t=h),findBox(u,["tfhd"]).map(f=>{const g=readUint32(f,4),p=readUint32(f,0)&16777215,m=(p&1)!==0,v=(p&2)!==0,S=(p&8)!==0;let y=0;const C=(p&16)!==0;let E=0;const L=(p&32)!==0;let T=8;g===r&&(m&&(T+=8),v&&(T+=4),S&&(y=readUint32(f,T),T+=4),C&&(E=readUint32(f,T),T+=4),L&&(T+=4),e.type==="video"&&(o=isHEVC(e.codec)),findBox(u,["trun"]).map(b=>{const _=b[0],I=readUint32(b,0)&16777215,P=(I&1)!==0;let R=0;const D=(I&4)!==0,O=(I&256)!==0;let N=0;const H=(I&512)!==0;let W=0;const M=(I&1024)!==0,A=(I&2048)!==0;let w=0;const k=readUint32(b,4);let F=8;P&&(R=readUint32(b,F),F+=4),D&&(F+=4);let B=R+c;for(let K=0;K<k;K++){if(O?(N=readUint32(b,F),F+=4):N=y,H?(W=readUint32(b,F),F+=4):W=E,M&&(F+=4),A&&(_===0?w=readUint32(b,F):w=readSint32(b,F),F+=4),e.type===ElementaryStreamTypes.VIDEO){let G=0;for(;G<W;){const U=readUint32(n,B);if(B+=4,isSEIMessage(o,n[B])){const Y=n.subarray(B,B+U);parseSEIMessageFromNALu(Y,o?2:1,t+w/i,s)}B+=U,G+=U+4}}t+=N/i}}))})})}),s}function isHEVC(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return s==="hvc1"||s==="hev1"||s==="dvh1"||s==="dvhe"}function isSEIMessage(t,e){if(t){const s=e>>1&63;return s===39||s===40}else return(e&31)===6}function parseSEIMessageFromNALu(t,e,s,n){const i=discardEPB(t);let r=0;r+=e;let o=0,a=0,l=!1,c=0;for(;r<i.length;){o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);a=0;do{if(r>=i.length)break;c=i[r++],a+=c}while(c===255);const d=i.length-r;if(!l&&o===4&&r<i.length){if(l=!0,i[r++]===181){const h=readUint16(i,r);if(r+=2,h===49){const f=readUint32(i,r);if(r+=4,f===1195456820){const g=i[r++];if(g===3){const p=i[r++],m=31&p,v=64&p,S=v?2+m*3:0,y=new Uint8Array(S);if(v){y[0]=p;for(let C=1;C<S;C++)y[C]=i[r++]}n.push({type:g,payloadType:o,pts:s,bytes:y})}}}}}else if(o===5&&a<d){if(l=!0,a>16){const u=[];for(let g=0;g<16;g++){const p=i[r++].toString(16);u.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&u.push("-")}const h=a-16,f=new Uint8Array(h);for(let g=0;g<h;g++)f[g]=i[r++];n.push({payloadType:o,pts:s,uuid:u.join(""),userData:utf8ArrayToStr(f),userDataBytes:f})}}else if(a<d)r+=a;else if(a>d)break}}function discardEPB(t){const e=t.byteLength,s=[];let n=1;for(;n<e-2;)t[n]===0&&t[n+1]===0&&t[n+2]===3?(s.push(n+2),n+=2):n++;if(s.length===0)return t;const i=e-s.length,r=new Uint8Array(i);let o=0;for(n=0;n<i;o++,n++)o===s[0]&&(o++,s.shift()),r[n]=t[o];return r}function parseEmsg(t){const e=t[0];let s="",n="",i=0,r=0,o=0,a=0,l=0,c=0;if(e===0){for(;bin2str(t.subarray(c,c+1))!=="\0";)s+=bin2str(t.subarray(c,c+1)),c+=1;for(s+=bin2str(t.subarray(c,c+1)),c+=1;bin2str(t.subarray(c,c+1))!=="\0";)n+=bin2str(t.subarray(c,c+1)),c+=1;n+=bin2str(t.subarray(c,c+1)),c+=1,i=readUint32(t,12),r=readUint32(t,16),a=readUint32(t,20),l=readUint32(t,24),c=28}else if(e===1){c+=4,i=readUint32(t,c),c+=4;const u=readUint32(t,c);c+=4;const h=readUint32(t,c);for(c+=4,o=2**32*u+h,Number.isSafeInteger(o)||(o=Number.MAX_SAFE_INTEGER,logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=readUint32(t,c),c+=4,l=readUint32(t,c),c+=4;bin2str(t.subarray(c,c+1))!=="\0";)s+=bin2str(t.subarray(c,c+1)),c+=1;for(s+=bin2str(t.subarray(c,c+1)),c+=1;bin2str(t.subarray(c,c+1))!=="\0";)n+=bin2str(t.subarray(c,c+1)),c+=1;n+=bin2str(t.subarray(c,c+1)),c+=1}const d=t.subarray(c,t.byteLength);return{schemeIdUri:s,value:n,timeScale:i,presentationTime:o,presentationTimeDelta:r,eventDuration:a,id:l,payload:d}}function mp4Box(t,...e){const s=e.length;let n=8,i=s;for(;i--;)n+=e[i].byteLength;const r=new Uint8Array(n);for(r[0]=n>>24&255,r[1]=n>>16&255,r[2]=n>>8&255,r[3]=n&255,r.set(t,4),i=0,n=8;i<s;i++)r.set(e[i],n),n+=e[i].byteLength;return r}function mp4pssh(t,e,s){if(t.byteLength!==16)throw new RangeError("Invalid system id");let n,i;n=0,i=new Uint8Array;let r;n>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const o=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(o.buffer).setUint32(0,s.byteLength,!1),mp4Box([112,115,115,104],new Uint8Array([n,0,0,0]),t,r,i,o,s||new Uint8Array)}function parsePssh(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},s=new DataView(t),n=s.getUint32(0);if(t.byteLength!==n&&n>44||s.getUint32(4)!==1886614376||(e.version=s.getUint32(8)>>>24,e.version>1))return null;e.systemId=Hex.hexDump(new Uint8Array(t,12,16));const r=s.getUint32(28);if(e.version===0){if(n-32<r)return null;e.data=new Uint8Array(t,32,r)}else if(e.version===1){e.kids=[];for(let o=0;o<r;o++)e.kids.push(new Uint8Array(t,32+o*16,16))}return e}let keyUriToKeyIdMap={};class LevelKey{static clearKeyUriToKeyIdMap(){keyUriToKeyIdMap={}}constructor(e,s,n,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=s,this.keyFormat=n,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case KeySystemFormats.FAIRPLAY:case KeySystemFormats.WIDEVINE:case KeySystemFormats.PLAYREADY:case KeySystemFormats.
12CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const n=createInitializationVector(e);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,n)}const s=convertDataUriToArrayBytes(this.uri);if(s)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:this.pssh=s,s.length>=22&&(this.keyId=s.subarray(s.length-22,s.length-6));break;case KeySystemFormats.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(n,null,s);const i=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),o=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(c){const d=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(d){const u=base64Decode(d).subarray(0,16);changeEndianness(u),this.keyId=u}}break}default:{let n=s.subarray(0,16);if(n.length!==16){const i=new Uint8Array(16);i.set(n,16-n.length),n=i}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n=keyUriToKeyIdMap[this.uri];if(!n){const i=Object.keys(keyUriToKeyIdMap).length%Number.MAX_SAFE_INTEGER;n=new Uint8Array(16),new DataView(n.buffer,12,4).setUint32(0,i),keyUriToKeyIdMap[this.uri]=n}this.keyId=n}return this}}function createInitializationVector(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}const VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(t){return VARIABLE_REPLACEMENT_REGEX.test(t)}function substituteVariablesInAttributes(t,e,s){if(t.variableList!==null||t.hasVariableRefs)for(let n=s.length;n--;){const i=s[n],r=e[i];r&&(e[i]=substituteVariables(t,r))}}function substituteVariables(t,e){if(t.variableList!==null||t.hasVariableRefs){const s=t.variableList;return e.replace(VARIABLE_REPLACEMENT_REGEX,n=>{const i=n.substring(2,n.length-1),r=s==null?void 0:s[i];return r===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),n):r})}return e}function addVariableDefinition(t,e,s){let n=t.variableList;n||(t.variableList=n={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const o=new self.URL(s).searchParams;if(o.has(i))r=o.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`)}catch(o){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function importVariableDefinition(t,e,s){const n=e.IMPORT;if(s&&n in s){let i=t.variableList;i||(t.variableList=i={}),i[n]=s[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}function getMediaSource(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const sampleEntryCodesISO={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},MediaSource$2=getMediaSource();function isCodecType(t,e){const s=sampleEntryCodesISO[e];return!!s&&s[t.slice(0,4)]===!0}function isCodecSupportedInMp4(t,e){var s;
12return(s=MediaSource$2==null?void 0:MediaSource$2.isTypeSupported(`${e||"video"}/mp4;codecs="${t}"`))!=null?s:!1}const MASTER_PLAYLIST_REGEX=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,IS_MEDIA_PLAYLIST=/^#EXT(?:INF|-X-TARGETDURATION):/m,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),LEVEL_PLAYLIST_REGEX_SLOW=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class M3U8Parser{static findGroup(e,s){for(let n=0;n<e.length;n++){const i=e[n];if(i.id===s)return i}}static convertAVC1ToAVCOTI(e){const s=e.split(".");if(s.length>2){let n=s.shift()+".";return n+=parseInt(s.shift()).toString(16),n+=("000"+parseInt(s.shift()).toString(16)).slice(-4),n}return e}static resolve(e,s){return urlToolkitExports.buildAbsoluteURL(s,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return IS_MEDIA_PLAYLIST.test(e)}static parseMasterPlaylist(e,s){const n=hasVariableReferences(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:n},r=[];MASTER_PLAYLIST_REGEX.lastIndex=0;let o;for(;(o=MASTER_PLAYLIST_REGEX.exec(e))!=null;)if(o[1]){var a;const c=new AttrList(o[1]);substituteVariablesInAttributes(i,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const d=substituteVariables(i,o[2]),u={attrs:c,bitrate:c.decimalInteger("AVERAGE-BANDWIDTH")||c.decimalInteger("BANDWIDTH"),name:c.NAME,url:M3U8Parser.resolve(d,s)},h=c.decimalResolution("RESOLUTION");h&&(u.width=h.width,u.height=h.height),setCodecs((c.CODECS||"").split(/[ ,]+/).filter(f=>f),u),u.videoCodec&&u.videoCodec.indexOf("avc1")!==-1&&(u.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(u.videoCodec)),(a=u.unknownCodecs)!=null&&a.length||r.push(u),i.levels.push(u)}else if(o[3]){const c=o[3],d=o[4];switch(c){case"SESSION-DATA":{const u=new AttrList(d);substituteVariablesInAttributes(i,u,["DATA-ID","LANGUAGE","VALUE","URI"]);const h=u["DATA-ID"];h&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[h]=u);break}case"SESSION-KEY":{const u=parseKey(d,s,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const u=new AttrList(d);substituteVariablesInAttributes(i,u,["NAME","VALUE","QUERYPARAM"]),addVariableDefinition(i,u,s)}break}case"CONTENT-STEERING":{const u=new AttrList(d);substituteVariablesInAttributes(i,u,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:M3U8Parser.resolve(u["SERVER-URI"],s),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=parseStartTimeOffset(d);break}}}const l=r.length>0&&r.length<i.levels.length;return i.levels=l?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,s,n){let i;const r={},o=n.levels,a={AUDIO:o.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:o.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;(i=MASTER_PLAYLIST_MEDIA_REGEX.exec(e))!==null;){const c=new AttrList(i[1]),d=c.TYPE;if(d){const u=a[d],h=r[d]||[];r[d]=h,substituteVariablesInAttributes(n,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",instreamId:c["INSTREAM-ID"],name:c.NAME||c.LANGUAGE||"",type:d,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:c.LANGUAGE,url:c.URI?M3U8Parser.resolve(c.URI,s):""};if(u!=null&&u.length){const g=M3U8Parser.findGroup(u,f.groupId)||u[0];assignCodec(f,g,"audioCodec"),assignCodec(f,g,"textCodec")}h.push(f)}}return r}static parseLevelPlaylist(e,s,n,i,r,o){const a=new LevelDetails(s),l=a.fragments;let c=null,d=0,u=0,h=0,f=0,g=null,p=new Fragment(i,s),m,v,S,y=-1,C=!1;for(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0,a.m3u8=e,a.hasVariableRefs=hasVariableReferences(e);(m=LEVEL_PLAYLIST_REGEX_FAST.exec(e))!==null;){C&&(C=!1,p=new Fragment(i,s),p.start=h,p.sn=d,p.cc=f,p.level=n,c&&(p.initSegment=c,p.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null));const b=m[1];if(b){p.duration=parseFloat(b);const _=(" "+m[2]).slice(1);p.title=_||null,p.tagList.push(_?["INF",b,_]:["INF",b])}else if(m[3]){if(isFiniteNumber(p.duration)){p.start=h,S&&setFragLevelKeys(p,S,a),p.sn=d,p.level=n,p.cc=f,p.urlId=r,l.push(p);const _=(" "+m[3]).slice(1);p.relurl=substituteVariables(a,_),assignProgramDateTime(p,g),g=p,h+=p.duration,d++,u=0,C=!0}}else if(m[4]){const _=(" "+m[4]).slice(1);g?p.setByteRange(_,g):p.setByteRange(_)}else if(m[5])p.rawProgramDateTime=(" "+m[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),y===-1&&(y=l.length);else{if(m=m[0].match(LEVEL_PLAYLIST_REGEX_SLOW),!m){logger.warn("No matches on 
12slow regex match for level playlist!");continue}for(v=1;v<m.length&&!(typeof m[v]<"u");v++);const _=(" "+m[v]).slice(1),I=(" "+m[v+1]).slice(1),P=m[v+2]?(" "+m[v+2]).slice(1):"";switch(_){case"PLAYLIST-TYPE":a.type=I.toUpperCase();break;case"MEDIA-SEQUENCE":d=a.startSN=parseInt(I);break;case"SKIP":{const R=new AttrList(I);substituteVariablesInAttributes(a,R,["RECENTLY-REMOVED-DATERANGES"]);const D=R.decimalInteger("SKIPPED-SEGMENTS");if(isFiniteNumber(D)){a.skippedSegments=D;for(let N=D;N--;)l.unshift(null);d+=D}const O=R.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(a.recentlyRemovedDateranges=O.split("	"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(I),1);break;case"VERSION":a.version=parseInt(I);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(I||P)&&p.tagList.push(P?[I,P]:[I]);break;case"DISCONTINUITY":f++,p.tagList.push(["DIS"]);break;case"GAP":p.gap=!0,p.tagList.push([_]);break;case"BITRATE":p.tagList.push([_,I]);break;case"DATERANGE":{const R=new AttrList(I);substituteVariablesInAttributes(a,R,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),substituteVariablesInAttributes(a,R,R.clientAttrs);const D=new DateRange(R,a.dateRanges[R.ID]);D.isValid||a.skippedSegments?a.dateRanges[D.id]=D:logger.warn(`Ignoring invalid DATERANGE tag: "${I}"`),p.tagList.push(["EXT-X-DATERANGE",I]);break}case"DEFINE":{{const R=new AttrList(I);substituteVariablesInAttributes(a,R,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in R?importVariableDefinition(a,R,o):addVariableDefinition(a,R,s)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(I);break;case"KEY":{const R=parseKey(I,s,a);if(R.isSupported()){if(R.method==="NONE"){S=void 0;break}S||(S={}),S[R.keyFormat]&&(S=_extends({},S)),S[R.keyFormat]=R}else logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${I}"`);break}case"START":a.startTimeOffset=parseStartTimeOffset(I);break;case"MAP":{const R=new AttrList(I);if(substituteVariablesInAttributes(a,R,["BYTERANGE","URI"]),p.duration){const D=new Fragment(i,s);setInitSegment(D,R,n,S),c=D,p.initSegment=c,c.rawProgramDateTime&&!p.rawProgramDateTime&&(p.rawProgramDateTime=c.rawProgramDateTime)}else setInitSegment(p,R,n,S),c=p,C=!0;break}case"SERVER-CONTROL":{const R=new AttrList(I);a.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),a.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const R=new AttrList(I);a.partTarget=R.decimalFloatingPoint("PART-TARGET");break}case"PART":{let R=a.partList;R||(R=a.partList=[]);const D=u>0?R[R.length-1]:void 0,O=u++,N=new AttrList(I);substituteVariablesInAttributes(a,N,["BYTERANGE","URI"]);const H=new Part(N,p,s,O,D);R.push(H),p.duration+=H.duration;break}case"PRELOAD-HINT":{const R=new AttrList(I);substituteVariablesInAttributes(a,R,["URI"]),a.preloadHint=R;break}case"RENDITION-REPORT":{const R=new AttrList(I);substituteVariablesInAttributes(a,R,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(R);break}default:logger.warn(`line parsed but not handled: ${m}`);break}}}g&&!g.relurl?(l.pop(),h-=g.duration,a.partList&&(a.fragmentHint=g)):a.partList&&(assignProgramDateTime(p,g),p.cc=f,a.fragmentHint=p,S&&setFragLevelKeys(p,S,a));const E=l.length,L=l[0],T=l[E-1];if(h+=a.skippedSegments*a.targetduration,h>0&&E&&T){a.averagetargetduration=h/E;const b=T.sn;a.endSN=b!=="initSegment"?b:0,a.live||(T.endList=!0),L&&(a.startCC=L.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(h+=a.fragmentHint.duration),a.totalduration=h,a.endCC=f,y>0&&backfillProgramDateTimes(l,y),a}}function parseKey(t,e,s){var n,i;const r=new AttrList(t);substituteVariablesInAttributes(s,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=(n=r.METHOD)!=null?n:"",a=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,d=(i=r.KEYFORMAT)!=null?i:"identity";a&&r.IV&&!l&&logger.error(`Invalid IV: ${r.IV}`);const u=a?M3U8Parser.resolve(a,e):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(o,u,d,h,l)}function parseStartTimeOffset(t){const s=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return isFiniteNumber(s)?s:null}function setCodecs(t,e){["video","audio","text"].forEach(s=>{const n=t.filter(i=>isCodecType(i,s));if(n.length){const i=n.filter(r=>r.lastIndexOf("avc1",0)===0||r.lastIndexOf("mp4a",0)===0);e[`${s}Codec`]=i.length>0?i[0]:n[0],t=t.filter(r=>n.indexOf(r)===-1)}}),e.unknownCodecs=t}function assignCodec(t,e,s){const n=e[s];n&&(t[s]=n)}function backfillProgramDateTimes(t,e){let s=t[e];for(let n=e;n--;){const i=t[n];if(!i)return;i.programDateTime=s.programDateTime-i.duration*1e3,s=i}}function assignProgramDateTime(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),isFiniteNumber(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function setInitSegment(t,e,s,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function setFragLevelKeys(t,e,s){t.levelkeys=e;const{encryptedFragments:n}=s;(!n.length||n[n.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&n.push(t)}var PlaylistContextType={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},PlaylistLevelType={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function mapContextToLevelType(t){const{type:e}=t;switch(e){case PlaylistContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case PlaylistContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(t,e){let s=t.url;return(s===void 0||s.indexOf("data:")===0)&&(s=e.url),s}class PlaylistLoader{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}
vendor: 10,463 bytes, line 12
12startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const s=this.hls.config,n=s.pLoader,i=s.loader,r=n||i,o=new r(s);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const s=this.loaders[e];s&&s.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,s){const{url:n}=s;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType.MANIFEST,url:n,deliveryDirectives:null})}onLevelLoading(e,s){const{id:n,level:i,url:r,deliveryDirectives:o}=s;this.load({id:n,level:i,responseType:"text",type:PlaylistContextType.LEVEL,url:r,deliveryDirectives:o})}onAudioTrackLoading(e,s){const{id:n,groupId:i,url:r,deliveryDirectives:o}=s;this.load({id:n,groupId:i,level:null,responseType:"text",type:PlaylistContextType.AUDIO_TRACK,url:r,deliveryDirectives:o})}onSubtitleTrackLoading(e,s){const{id:n,groupId:i,url:r,deliveryDirectives:o}=s;this.load({id:n,groupId:i,level:null,responseType:"text",type:PlaylistContextType.SUBTITLE_TRACK,url:r,deliveryDirectives:o})}load(e){var s;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=i.context;if(c&&c.url===e.url){logger.trace("[playlist-loader]: playlist request ongoing");return}logger.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===PlaylistContextType.MANIFEST?r=n.manifestLoadPolicy.default:r=_extends({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),(s=e.deliveryDirectives)!=null&&s.part){let c;if(e.type===PlaylistContextType.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===PlaylistContextType.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===PlaylistContextType.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const d=c.partTarget,u=c.targetduration;if(d&&u){const h=Math.max(d*3,u*.8)*1e3;r=_extends({},r,{maxTimeToFirstByteMs:Math.min(h,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,r.maxTimeToFirstByteMs)})}}}const o=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(c,d,u,h)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=c.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,u,new Error("no EXTM3U delimiter"),h||null,d);return}d.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(c,d,u,h||null,f):this.handleMasterPlaylist(c,d,u,h)},onError:(c,d,u,h)=>{this.handleNetworkError(d,u,!1,c,h)},onTimeout:(c,d,u)=>{this.handleNetworkError(d,u,!0,void 0,c)}};i.load(e,a,l)}handleMasterPlaylist(e,s,n,i){const r=this.hls,o=e.data,a=getResponseUrl(e,n),l=M3U8Parser.parseMasterPlaylist(o,a);if(l.playlistParsingError){this.handleManifestParsingError(e,n,l.playlistParsingError,i,s);return}const{contentSteering:c,levels:d,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=M3U8Parser.parseMasterPlaylistMedia(o,a,l);p.length&&!p.some(y=>!y.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""})),r.trigger(Events.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:m,captions:v,contentSteering:c,url:a,stats:s,networkDetails:i,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,s,n,i,r){const o=this.hls,{id:a,level:l,type:c}=n,d=getResponseUrl(e,n),u=isFiniteNumber(a)?a:0,h=isFiniteNumber(l)?l:u,f=mapContextToLevelType(n),g=M3U8Parser.parseLevelPlaylist(e.data,d,h,f,u,this.variableList);if(c===PlaylistContextType.MANIFEST){const p={attrs:new AttrList({}),bitrate:0,details:g,name:"",url:d};o.trigger(Events.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:d,stats:s,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}s.parsing.end=performance.now(),n.levelDetails=g,this.handlePlaylistLoaded(g,e,s,n,i,r)}handleManifestParsingError(e,s,n,i,r){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:s.type===PlaylistContextType.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:s,networkDetails:i,stats:r})}handleNetworkError(e,s,n=!1,i,r){let o=`A network ${n?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===PlaylistContextType.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===PlaylistContextType.AUDIO_TRACK||e.type===PlaylistContextType.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);logger.warn(`[playlist-loader]: ${o}`);let l=ErrorDetails.UNKNOWN,c=!1;const d=this.getInternalLoader(e);switch(e.type){case PlaylistContextType.MANIFEST:l=n?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,c=!0;break;case PlaylistContextType.LEVEL:l=n?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,c=!1;break;case PlaylistContextType.AUDIO_TRACK:l=n?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case PlaylistContextType.SUBTITLE_TRACK:l=n?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,c=!1;break}d&&this.resetInternalLoader(e.type);const u={type:ErrorTypes.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:d,context:e,error:a,networkDetails:s,stats:r};if(i){const h=(s==null?void 0:s.url)||e.url;u.response=_objectSpread2({url:h,data:void 0},i)}this.hls.trigger(Events.ERROR,u)}handlePlaylistLoaded(e,s,n,i,r,o){const a=this.hls,{type:l,level:c,id:d,groupId:u,deliveryDirectives:h}=i,f=getResponseUrl(s,i),g=mapContextToLevelType(i),p=typeof i.level=="number"&&g===PlaylistLevelType.MAIN?c:void 0;if(!e.fragments.length){const v=new Error("No Segments found in Playlist");a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:s,context:i,level:p,parent:g,networkDetails:r,stats:n});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m){a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:s,context:i,level:p,parent:g,networkDetails:r,stats:n});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case PlaylistContextType.MANIFEST:case PlaylistContextType.LEVEL:a.trigger(Events.LEVEL_LOADED,{details:e,level:p||0,id:d||0,stats:n,networkDetails:r,deliveryDirectives:h});break;case PlaylistContextType.AUDIO_TRACK:a.trigger(Events.AUDIO_TRACK_LOADED,{details:e,id:d||0,groupId:u||"",stats:n,networkDetails:r,deliveryDirectives:h});break;case PlaylistContextType.SUBTITLE_TRACK:a.trigger(Events.SUBTITLE_TRACK_LOADED,{details:e,id:d||0,groupId:u||"",stats:n,networkDetails:r,deliveryDirectives:h});break}}}function sendAddTrackEvent(t,e){let s;try{s=new Event("addtrack")}catch{s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function addCueToTrack(t,e){const s=t.mode;if(s==="disabled"&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(n){logger.debug(`[texttrack-utils]: ${n}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(i){logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}s==="disabled"&&(t.mode=s)}function clearCurrentCues(t){const e=t.mode;if(e==="disabled"&&(t.mode="hidden"),t.cues)for(let s=t.cues.length;s--;)t.removeCue(t.cues[s]);e==="disabled"&&(t.mode=e)}function removeCuesInRange(t,e,s,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=getCuesInRange(t.cues,e,s);for(let o=0;o<r.length;o++)(!n||n(r[o]))&&t.removeCue(r[o])}i==="disabled"&&(t.mode=i)}function getFirstCueIndexAfterTime(t,e){if(e<t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let n=0,i=s;for(;n<=i;){const r=Math.floor((i+n)/2);if(e<t[r].startTime)i=r-1;else if(e>t[r].startTime&&n<s)n=r+1;else return r}return t[n].startTime-e<e-t[i].startTime?n:i}function getCuesInRange(t,e,s){const n=[],i=getFirstCueIndexAfterTime(t,e);if(i>-1)for(let r=i,o=t.length;r<o;r++){const a=t[r];if(a.startTime>=e&&a.endTime<=s)n.push(a);else if(a.startTime>s)return n}return n}var MetadataSchema={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const MIN_CUE_DURATION=.25;function getCueClass(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const MAX_CUE_ENDTIME=(()=>{const t=getCueClass();try{new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function dateRangeDateToTimelineSeconds(t,e){return t.getTime()/1e3-e}function hexToArrayBuffer(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class ID3TrackController{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;
12e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,s){this.media=s.media}onMediaDetaching(){this.id3Track&&(clearCurrentCues(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const s=this.getID3Track(e.textTracks);return s.mode="hidden",s}getID3Track(e){if(this.media){for(let s=0;s<e.length;s++){const n=e[s];if(n.kind==="metadata"&&n.label==="id3")return sendAddTrackEvent(n,this.media),n}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,s){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:i}}}=this;if(!n&&!i)return;const{samples:r}=s;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=getCueClass();for(let a=0;a<r.length;a++){const l=r[a].type;if(l===MetadataSchema.emsg&&!n||!i)continue;const c=getID3Frames(r[a].data);if(c){const d=r[a].pts;let u=d+r[a].duration;u>MAX_CUE_ENDTIME&&(u=MAX_CUE_ENDTIME),u-d<=0&&(u=d+MIN_CUE_DURATION);for(let f=0;f<c.length;f++){const g=c[f];if(!isTimeStampFrame(g)){this.updateId3CueEnds(d,l);const p=new o(d,u,"");p.value=g,l&&(p.type=l),this.id3Track.addCue(p)}}}}}updateId3CueEnds(e,s){var n;const i=(n=this.id3Track)==null?void 0:n.cues;if(i)for(let r=i.length;r--;){const o=i[r];o.type===s&&o.startTime<e&&o.endTime===MAX_CUE_ENDTIME&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:s,endOffset:n,type:i}){const{id3Track:r,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=o;if(r&&(a||l)){let c;i==="audio"?c=d=>d.type===MetadataSchema.audioId3&&l:i==="video"?c=d=>d.type===MetadataSchema.emsg&&a:c=d=>d.type===MetadataSchema.audioId3&&l||d.type===MetadataSchema.emsg&&a,removeCuesInRange(r,s,n,c)}}onLevelUpdated(e,{details:s}){if(!this.media||!s.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:n,id3Track:i}=this,{dateRanges:r}=s,o=Object.keys(r);if(i){const d=Object.keys(n).filter(u=>!o.includes(u));for(let u=d.length;u--;){const h=d[u];Object.keys(n[h].cues).forEach(f=>{i.removeCue(n[h].cues[f])}),delete n[h]}}const a=s.fragments[s.fragments.length-1];if(o.length===0||!isFiniteNumber(a==null?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=a.programDateTime/1e3-a.start,c=getCueClass();for(let d=0;d<o.length;d++){const u=o[d],h=r[u],f=n[u],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1;const m=dateRangeDateToTimelineSeconds(h.startDate,l);let v=MAX_CUE_ENDTIME;const S=h.endDate;if(S)v=dateRangeDateToTimelineSeconds(S,l),p=!0;else if(h.endOnNext&&!p){const C=o.reduce((E,L)=>{const T=r[L];return T.class===h.class&&T.id!==L&&T.startDate>h.startDate&&E.push(T),E},[]).sort((E,L)=>E.startDate.getTime()-L.startDate.getTime())[0];C&&(v=dateRangeDateToTimelineSeconds(C.startDate,l),p=!0)}const y=Object.keys(h.attr);for(let C=0;C<y.length;C++){const E=y[C];if(!isDateRangeCueAttribute(E))continue;let L=g[E];if(L)p&&!f.durationKnown&&(L.endTime=v);else{let T=h.attr[E];L=new c(m,v,""),isSCTE35Attribute(E)&&(T=hexToArrayBuffer(T)),L.value={key:E,data:T},L.type=MetadataSchema.dateRange,L.id=u,this.id3Track.addCue(L),g[E]=L}}n[u]={cues:g,dateRange:h,durationKnown:p}}}}class LatencyController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:s}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:s?e.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:s,partHoldBack:n,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,l=this.hls.userConfig;let c=a&&n||s;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:o*i);const d=i;return c+Math.min(this.stallCount*1,d)}get liveSyncPosition(){const e=this.estimateLiveEdge(),s=this.targetLatency,n=this.levelDetails;if(e===null||s===null||n===null)return null;const i=n.edge,r=e-s-this.edgeStalled,o=i-n.totalduration,a=i-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(o,r),a)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const s=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-s,0)}get forwardBufferLength(){const{media:e,levelDetails:s}=this;if(!e||!s)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):s.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}
12registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Events.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Events.ERROR,this.onError,this)}onMediaAttached(e,s){this.media=s.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:s}){this.levelDetails=s,s.advanced&&this.timeupdate(),!s.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,s){var n;s.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,(n=this.levelDetails)!=null&&n.live&&logger.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:s}=this;if(!e||!s)return;this.currentTime=e.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||r===1)return;const o=this.targetLatency;if(o===null)return;const a=n-o,l=Math.min(this.maxLatency,o+s.targetduration),c=a<l;if(s.live&&c&&a>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,r)),u=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(d,Math.max(1,u))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const HdcpLevels=["NONE","TYPE-0","TYPE-1",null];var HlsSkip={No:"",Yes:"YES",v2:"v2"};function getSkipValue(t,e){const{canSkipUntil:s,canSkipDateRanges:n,endSN:i}=t,r=e!==void 0?e-i:0;return s&&r<s?n?HlsSkip.v2:HlsSkip.Yes:HlsSkip.No}class HlsUrlParameters{constructor(e,s,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=s,this.skip=n}addDirectives(e){const s=new self.URL(e);return this.msn!==void 0&&s.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&s.searchParams.set("_HLS_part",this.part.toString()),this.skip&&s.searchParams.set("_HLS_skip",this.skip),s.href}}class Level{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>s).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const s=e%this.url.length;this._urlId!==s&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=s)}get audioGroupId(){var e;return(e=this.audioGroupIds)==null?void 0:e[this.urlId]}get textGroupId(){var e;return(e=this.textGroupIds)==null?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function updateFromToPTS(t,e){const s=e.startPTS;if(isFiniteNumber(s)){let n=0,i;e.sn>t.sn?(n=s-t.start,i=t):(n=t.start-s,i=e),i.duration!==n&&(i.duration=n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function updateFragPTSDTS(t,e,s,n,i,r){n-s<=0&&(logger.warn("Fragment should have a positive duration",e),n=s+e.duration,r=i+e.duration);let a=s,l=n;const c=e.startPTS,d=e.endPTS;if(isFiniteNumber(c)){const m=Math.abs(c-s);isFiniteNumber(e.deltaPTS)?e.deltaPTS=Math.max(m,e.deltaPTS):e.deltaPTS=m,a=Math.max(s,c),s=Math.min(s,c),i=Math.min(i,e.startDTS),l=Math.min(n,d),n=Math.max(n,d),r=Math.max(r,e.endDTS)}const u=s-e.start;e.start!==0&&(e.start=s),e.duration=n-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=i,e.endPTS=n,e.minEndPTS=l,e.endDTS=r;const h=e.sn;if(!t||h<t.startSN||h>t.endSN)return 0;let f;const g=h-t.startSN,p=t.fragments;for(p[g]=e,f=g;f>0;f--)updateFromToPTS(p[f],p[f-1]);for(f=g;f<p.length-1;f++)updateFromToPTS(p[f],p[f+1]);return t.fragmentHint&&updateFromToPTS(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function mergeDetails(t,e){let s=null;const n=t.fragments;for(let l=n.length-1;l>=0;l--){const c=n[l].initSegment;if(c){s=c;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i=0,r;if(mapFragmentIntersection(t,e,(l,c)=>{l.relurl&&(i=l.cc-c.cc),isFiniteNumber(l.startPTS)&&isFiniteNumber(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(r=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,c.urlId=l.urlId,l.initSegment&&(c.initSegment=l.initSegment,s=l.initSegment)}),s&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEac
vendor: 5,063 bytes, line 12
12h(c=>{var d;(!c.initSegment||c.initSegment.relurl===((d=s)==null?void 0:d.relurl))&&(c.initSegment=s)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=mergeDateRanges(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const o=e.fragments;if(i){logger.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<o.length;l++)o[l].cc+=i}e.skippedSegments&&(e.startCC=e.fragments[0].cc),mapPartIntersection(t.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),r?updateFragPTSDTS(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):adjustSliding(t,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const l=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=l),e.driftEndTime=a,e.driftEnd=l}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function mergeDateRanges(t,e,s){const n=_extends({},t);return s&&s.forEach(i=>{delete n[i]}),Object.keys(e).forEach(i=>{const r=new DateRange(e[i].attr,n[i]);r.isValid?n[i]=r:logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),n}function mapPartIntersection(t,e,s){if(t&&e){let n=0;for(let i=0,r=t.length;i<=r;i++){const o=t[i],a=e[i+n];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?s(o,a):n--}}}function mapFragmentIntersection(t,e,s){const n=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,r=(t.fragmentHint?1:0)+(n?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let c=i;c<=r;c++){const d=l[o+c];let u=a[c];n&&!u&&c<n&&(u=e.fragments[c]=d),d&&u&&s(d,u)}}function adjustSliding(t,e){const s=e.startSN+e.skippedSegments-t.startSN,n=t.fragments;s<0||s>=n.length||addSliding(e,n[s].start)}function addSliding(t,e){if(e){const s=t.fragments;for(let n=t.skippedSegments;n<s.length;n++)s[n].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function computeReloadInterval(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const n=t.fragments;if(n.length&&s*4>e){const r=n[n.length-1].duration*1e3;r<s&&(s=r)}}else s/=2;return Math.round(s)}function getFragmentWithSN(t,e,s){if(!(t!=null&&t.details))return null;const n=t.details;let i=n.fragments[e-n.startSN];return i||(i=n.fragmentHint,i&&i.sn===e)?i:e<n.startSN&&s&&s.sn===e?s:null}function getPartWith(t,e,s){var n;return t!=null&&t.details?findPart((n=t.details)==null?void 0:n.partList,e,s):null}function findPart(t,e,s){if(t)for(let n=t.length;n--;){const i=t[n];if(i.index===s&&i.fragment.sn===e)return i}return null}function isTimeoutError(t){switch(t.details){case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_TIMEOUT:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function getRetryConfig(t,e){const s=isTimeoutError(e);return t.default[`${s?"timeout":"error"}Retry`]}function getRetryDelay(t,e){const s=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function getLoaderConfigWithoutReties(t){return _objectSpread2(_objectSpread2({},t),{errorRetry:null,timeoutRetry:null})}function shouldRetry(t,e,s,n){return!!t&&e<t.maxNumRetry&&(retryForHttpStatus(n)||!!s)}function retryForHttpStatus(t){return t===0&&navigator.onLine===!1||!!t&&(t<400||t>499)}const BinarySearch={search:function(t,e){let s=0,n=t.length-1,i=null,r=null;for(;s<=n;){i=(s+n)/2|0,r=t[i];const o=e(r);if(o>0)s=i+1;else if(o<0)n=i-1;else return r}return null}};function findFragmentByPDT(t,e,s){if(e===null||!Array.isArray(t)||!t.length||!isFiniteNumber(e))return null;const n=t[0].programDateTime;if(e<(n||0))return null;const i=t[t.length-1].endProgramDateTime;if(e>=(i||0))return null;s=s||0;for(let r=0;r<t.length;++r){const o=t[r];if(pdtWithinToleranceTest(e,s,o))return o}return null}function findFragmentByPTS(t,e,s=0,n=0){let i=null;if(t?i=e[t.sn-e[0].sn+1]||null:s===0&&e[0].start===0&&(i=e[0]),i&&fragmentWithinToleranceTest(s,n,i)===0)return i;const r=BinarySearch.search(e,fragmentWithinToleranceTest.bind(null,s,n));return r&&(r!==t||!i)?r:i}function fragmentWithinToleranceTest(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const n=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-n<=t?1:s.start-n>t&&s.start?-1:0}function pdtWithinToleranceTest(t,e,s){const n=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0))*1e3;return(s.endProgramDateTime||0)-n>t}function findFragWithCC(t,e){return BinarySearch.search(t,s=>s.cc<e?1:s.cc>e?-1:0)}const RENDITION_PENALTY_DURATION_MS=3e5;var NetworkErrorAction={DoNothing:0,SendAlternateToPenaltyBox:2,Retry
12Request:5},ErrorActionFlags={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class ErrorController{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=logger.log.bind(logger,"[info]:"),this.warn=logger.warn.bind(logger,"[warning]:"),this.error=logger.error.bind(logger,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.ERROR,this.onError,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.ERROR,this.onError,this),e.off(Events.ERROR,this.onErrorOut,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(e==null?void 0:e.type)===PlaylistLevelType.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,s){var n,i;if(s.fatal)return;const r=this.hls,o=s.context;switch(s.details){case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:s.errorAction=this.getFragRetryOrSwitchAction(s);return;case ErrorDetails.FRAG_PARSING_ERROR:if((n=s.frag)!=null&&n.gap){s.errorAction={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None};return}case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_DECRYPT_ERROR:{s.errorAction=this.getFragRetryOrSwitchAction(s),s.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox;return}case ErrorDetails.LEVEL_EMPTY_ERROR:case ErrorDetails.LEVEL_PARSING_ERROR:{var a,l;const c=s.parent===PlaylistLevelType.MAIN?s.level:r.loadLevel;s.details===ErrorDetails.LEVEL_EMPTY_ERROR&&((a=s.context)!=null&&(l=a.levelDetails)!=null&&l.live)?s.errorAction=this.getPlaylistRetryOrSwitchAction(s,c):(s.levelRetry=!1,s.errorAction=this.getLevelSwitchAction(s,c))}return;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:typeof(o==null?void 0:o.level)=="number"&&(s.errorAction=this.getPlaylistRetryOrSwitchAction(s,o.level));return;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_LOAD_ERROR:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){const c=r.levels[r.loadLevel];if(c&&(o.type===PlaylistContextType.AUDIO_TRACK&&o.groupId===c.audioGroupId||o.type===PlaylistContextType.SUBTITLE_TRACK&&o.groupId===c.textGroupId)){s.errorAction=this.getPlaylistRetryOrSwitchAction(s,r.loadLevel),s.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox,s.errorAction.flags=ErrorActionFlags.MoveAllAlternatesMatchingHost;return}}return;case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],d=c==null?void 0:c.attrs["HDCP-LEVEL"];d&&(s.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHDCP,hdcpLevel:d})}return;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:s.errorAction=this.getLevelSwitchAction(s,(i=s.level)!=null?i:r.loadLevel);return;case ErrorDetails.INTERNAL_EXCEPTION:case ErrorDetails.BUFFER_APPENDING_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:case ErrorDetails.LEVEL_SWITCH_ERROR:case ErrorDetails.BUFFER_STALLED_ERROR:case ErrorDetails.BUFFER_SEEK_OVER_HOLE:case ErrorDetails.BUFFER_NUDGE_ON_STALL:s.errorAction={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None};return}if(s.type===ErrorTypes.KEY_SYSTEM_ERROR){const c=this.getVariantLevelIndex(s.frag);s.levelRetry=!1,s.errorAction=this.getLevelSwitchAction(s,c);return}}getPlaylistRetryOrSwitchAction(e,s){var n;const i=this.hls,r=getRetryConfig(i.config.playlistLoadPolicy,e),o=this.playlistError++,a=(n=e.response)==null?void 0:n.code;if(shouldRetry(r,o,isTimeoutError(e),a))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:r,retryCount:o};const c=this.getLevelSwitchAction(e,s);return r&&(c.retryConfig=r,c.retryCount=o),c}getFragRetryOrSwitchAction(e){const s=this.hls,n=this.getVariantLevelIndex(e.frag),i=s.levels[n],{fragLoadPolicy:r,keyLoadPolicy:o}=s.config,a=getRetryConfig(e.details.startsWith("key")?o:r,e),l=s.levels.reduce((u,h)=>u+h.fragmentError,0);if(i){var c;e.details!==ErrorDetails.FRAG_GAP&&i.fragmentError++;const u=(c=e.response)==null?void 0:c.code;if(shouldRetry(a,l,isTimeoutError(e),u))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:a,retryCount:l}}const d=this.getLevelSwitchAction(e,n);return a&&(d.retryConfig=a,d.retryCount=l),d}getLevelSwitchAction(e,s){const n=this.hls;s==null&&(s=n.loadLevel);const i=this.hls.levels[s];if(i&&(i.loadError++,n.autoLevelEnabled)){var r,o;let a=-1;const{levels:l,loadLevel:c,minAutoLevel:d,maxAutoLevel:u}=n,h=(r=e.frag)==null?void 0:r.type,{type:f,groupId:g}=(o=e.context)!=null?o:{};for(let p=l.length;p--;){const m=(p+c)%l.length;if(m!==c&&m>=d&&m<=u&&l[m].loadError===0){const v=l[m];if(e.details===ErrorDetails.FRAG_GAP&&e.frag){const S=l[m].details;if(S){const y=findFragmentByPTS(e.frag,S.fragments,e.frag.start);if(y!=null&&y.gap)continue}}else{if(f===PlaylistContextType.AUDIO_TRACK&&g===v.audioGroupId||f===PlaylistContextType.SUBTITLE_TRACK&&g===v.textGroupId)continue;if(h===PlaylistLevelType.AUDIO&&i.audioGroupId===v.audioGroupId||h===PlaylistLevelType.SUBTITLE&&i.textGroupId===v.textGroupId)continue}a=m;break}}if(a>-1&&n.loadLevel!==a)return e.levelRetry=!0,this.playlistError=0,{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.None,nextAutoLevel:a}}return{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHost}}onErrorOut(e,s){var n;switch((n=s.errorAction)==null?void 0:n.action){case NetworkErrorAction.DoNothing:break;case NetworkErrorAction.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(s),!s.errorAction.resolved&&s.details!==ErrorDetails.FRAG_GAP&&(s.fatal=!0);break}if(s.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const s=this.hls,n=e.errorAction;if(!n)return;const{flags:i,hdcpLevel:r,nextAutoLevel:o}=n;switch(i){case ErrorActionFlags.None:this.switchLevel(e,o);break;case ErrorActionFlags.MoveAllAlternatesMatchingHost:n.resolved||(n.resolved=this.redundantFailover(e));break;case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:r&&(s.maxHdcpLevel=HdcpLevels[HdcpLevels.indexOf(r)-1],n.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${s.maxHdcpLevel}" or lower`);break}n.resolved||this.switchLevel(e,o)}switchLevel(e,s){s!==void 0&&e.errorAction&&(this.warn(`switching to level ${s} after ${e.details}`),this.hls.nextAutoLevel=s,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:s,penalizedRenditions:n}=this,i=e.parent===PlaylistLevelType.MAIN?e.level:s.loadLevel,r=s.levels[i],o=r.url.length,a=e.frag?e.frag.urlId:r.urlId;r.urlId===a&&(!e.frag||r.details)&&this.penalizeRendition(r,e);for(let l=1;l<o;l++){const c=(a+l)%o,d=n[c];if(!d||checkExpired(d,e,n[a]))return this.warn(`Switching to Redundant Stream ${c+1}/${o}: "${r.url[c]}" after ${e.details}
12`),this.playlistError=0,s.levels.forEach(u=>{u.urlId=c}),s.nextLoadLevel=i,!0}return!1}penalizeRendition(e,s){const{penalizedRenditions:n}=this,i=n[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};i.lastErrorPerfMs=performance.now(),i.errors.push(s),i.details=e.details,n[e.urlId]=i}}function checkExpired(t,e,s){if(performance.now()-t.lastErrorPerfMs>RENDITION_PENALTY_DURATION_MS)return!0;const n=t.details;if(e.details===ErrorDetails.FRAG_GAP&&n&&e.frag){const i=e.frag.start,r=findFragmentByPTS(null,n.fragments,i);if(r&&!r.gap)return!0}if(s&&t.errors.length<s.errors.length){const i=t.errors[t.errors.length-1];if(n&&i.frag&&e.frag&&Math.abs(i.frag.start-e.frag.start)>n.targetduration*3)return!0}return!1}class BasePlaylistController{constructor(e,s){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=logger.log.bind(logger,`${s}:`),this.warn=logger.warn.bind(logger,`${s}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,s){const n=s==null?void 0:s.renditionReports;if(n){let i=-1;for(let r=0;r<n.length;r++){const o=n[r];let a;try{a=new self.URL(o.URI,s.url).href}catch(l){logger.warn(`Could not construct new URL for Rendition Report: ${l}`),a=o.URI||""}if(a===e){i=r;break}else a===e.substring(0,a.length)&&(i=r)}if(i!==-1){const r=n[i],o=parseInt(r["LAST-MSN"])||(s==null?void 0:s.lastPartSn);let a=parseInt(r["LAST-PART"])||(s==null?void 0:s.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(s.age-s.partTarget,s.targetduration);a>=0&&l>s.partTarget&&(a+=1)}return new HlsUrlParameters(o,a>=0?a:void 0,HlsSkip.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,s,n){const{details:i,stats:r}=s,o=self.performance.now(),a=r.loading.first?Math.max(0,o-r.loading.first):0;if(i.advancedDateTime=Date.now()-a,i.live||n!=null&&n.live){if(i.reloaded(n),n&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:"MISSED"}`),n&&i.fragments.length>0&&mergeDetails(n,i),!this.canLoad||!i.live)return;let l,c,d;if(i.canBlockReload&&i.endSN&&i.advanced){const m=this.hls.config.lowLatencyMode,v=i.lastPartSn,S=i.endSN,y=i.lastPartIndex,C=y!==-1,E=v===S,L=m?0:y;C?(c=E?S+1:v,d=E?L:y+1):c=S+1;const T=i.age,b=T+i.ageHeader;let _=Math.min(b-i.partTarget,i.targetduration*1.5);if(_>0){if(n&&_>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${_} with playlist age: ${i.age}`),_=0;else{const I=Math.floor(_/i.targetduration);if(c+=I,d!==void 0){const P=Math.round(_%i.targetduration/i.partTarget);d+=P}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${T.toFixed(2)}s goal: ${_} skip sn ${I} to part ${d}`)}i.tuneInGoal=_}if(l=this.getDeliveryDirectives(i,s.deliveryDirectives,c,d),m||!E){this.loadPlaylist(l);return}}else i.canBlockReload&&(l=this.getDeliveryDirectives(i,s.deliveryDirectives,c,d));const u=this.hls.mainForwardBufferInfo,h=u?u.end-u.len:0,f=(i.edge-h)*1e3,g=computeReloadInterval(i,f);i.updated&&o>this.requestScheduled+g&&(this.requestScheduled=r.loading.start),c!==void 0&&i.canBlockReload?this.requestScheduled=r.loading.first+g-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=g);let p=this.requestScheduled-o;p=Math.max(0,p),this.log(`reload live playlist ${e} in ${Math.round(p)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),p)}else this.clearTimer()}getDeliveryDirectives(e,s,n,i){let r=getSkipValue(e,n);return s!=null&&s.skip&&e.deltaUpdateFailed&&(n=s.msn,i=s.part,r=HlsSkip.No),new HlsUrlParameters(n,i,r)}checkRetry(e){const s=e.details,n=isTimeoutError(e),i=e.errorAction,{action:r,retryCount:o=0,retryConfig:a}=i||{},l=!!i&&!!a&&(r===NetworkErrorAction.RetryRequest||!i.resolved&&r===NetworkErrorAction.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,o>=a.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${s}" without delivery-directives`),this.loadPlaylist();else{const d=getRetryDelay(a,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${s}" in ${d}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}let chromeOrFirefox;class LevelController extends BasePlaylistController{constructor(e,s){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=s,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
12startLoad(){this._levels.forEach(s=>{s.loadError=0,s.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,s){this.resetLevels()}onManifestLoaded(e,s){const n=[],i={};let r;s.levels.forEach(o=>{var a;const l=o.attrs;((a=o.audioCodec)==null?void 0:a.indexOf("mp4a.40.34"))!==-1&&(chromeOrFirefox||(chromeOrFirefox=/chrome|firefox/i.test(navigator.userAgent)),chromeOrFirefox&&(o.audioCodec=void 0));const{AUDIO:c,CODECS:d,"FRAME-RATE":u,"PATHWAY-ID":h,RESOLUTION:f,SUBTITLES:g}=l,m=`${`${h||"."}-`}${o.bitrate}-${f}-${u}-${d}`;r=i[m],r?r.addFallback(o):(r=new Level(o),i[m]=r,n.push(r)),addGroupId(r,"audio",c),addGroupId(r,"text",g)}),this.filterAndSortMediaOptions(n,s)}filterAndSortMediaOptions(e,s){let n=[],i=[],r=!1,o=!1,a=!1,l=e.filter(({audioCodec:f,videoCodec:g,width:p,height:m,unknownCodecs:v})=>(r||(r=!!(p&&m)),o||(o=!!g),a||(a=!!f),!(v!=null&&v.length)&&(!f||isCodecSupportedInMp4(f,"audio"))&&(!g||isCodecSupportedInMp4(g,"video"))));if((r||o)&&a&&(l=l.filter(({videoCodec:f,width:g,height:p})=>!!f||!!(g&&p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:s.url,error:f,reason:f.message})}});return}s.audioTracks&&(n=s.audioTracks.filter(f=>!f.audioCodec||isCodecSupportedInMp4(f.audioCodec,"audio")),assignTrackIdsByGroup(n)),s.subtitles&&(i=s.subtitles,assignTrackIdsByGroup(i));const c=l.slice(0);l.sort((f,g)=>f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==g.bitrate?f.bitrate-g.bitrate:f.attrs["FRAME-RATE"]!==g.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-g.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==g.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-g.attrs.decimalFloatingPoint("SCORE"):r&&f.height!==g.height?f.height-g.height:0);let d=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;f<c.length;f++)if(c[f].pathwayId===l[0].pathwayId){d=c[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===d){this._firstLevel=f,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${d.bitrate}`);break}const u=a&&!o,h={levels:l,audioTracks:n,subtitleTracks:i,sessionData:s.sessionData,sessionKeys:s.sessionKeys,firstLevel:this._firstLevel,stats:s.stats,audio:a,video:o,altAudio:!u&&n.some(f=>!!f.url)};this.hls.trigger(Events.MANIFEST_PARSED,h),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const s=this._levels;if(s.length===0)return;if(e<0||e>=s.length){const d=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:d,reason:d.message}),u)return;e=Math.min(e,s.length-1)}const n=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,o=s[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n===e&&o.details&&i&&r===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${n}${r?" with Pathway "+r:""}`);const l=_extends({},o,{level:e,maxBitrate:o.maxBitrate,attrs:o.attrs,uri:o.uri,urlId:o.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(Events.LEVEL_SWITCHING,l);const c=o.details;if(!c||c.live){const d=this.switchParams(o.uri,i==null?void 0:i.details);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this._firstLevel}else return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,s){s.fatal||!s.context||s.context.type===PlaylistContextType.LEVEL&&s.context.level===this.level&&this.checkRetry(s)}onFragLoaded(e,{frag:s}){if(s!==void 0&&s.type===PlaylistLevelType.MAIN){const n=this._levels[s.level];n!==void 0&&(n.loadError=0)}}onLevelLoaded(e,s){var n;const{level:i,details:r}=s,o=this._levels[i];if(!o){var a;this.warn(`Invalid level index ${i}`),(a=s.deliveryDirectives)!=null&&a.skip&&(r.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(o.fragmentError===0&&(o.loadError=0),this.playlistLoaded(i,s,o.details)):(n=s.deliveryDirectives)!=null&&n.skip&&(r.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,s){const n=this.currentLevel;if(!n)return;const i=this.hls.audioTracks[s.id].groupId;if(n.audioGroupIds&&n.audioGroupId!==i){let r=-1;for(let o=0;o<n.audioGroupIds.length;o++)if(n.audioGroupIds[o]===i){r=o;break}r!==-1&&r!==n.urlId&&(n.urlId=r,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const s=this.currentLevelIndex,n=this.currentLevel;if(n&&this.shouldLoadPlaylist(n)){const i=n.urlId;let r=n.uri;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const o=n.attrs["PATHWAY-ID"];this.log(`Loading level index ${s}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${o?" Pathway "+o:""} URI ${i+1}/${n.url.length} ${r}`),this.clearTimer(),this.hls.trigger(Events.LEVEL_LOADING,{url:r,level:s,id:i,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e,s){const n=(r,o)=>o!==s,i=this._levels.filter((r,o)=>o!==e?!0:r.url.length>1&&s!==void 0?(r.url=r.url.filter(n),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(n)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(n)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1));this.hls.trigger(Events.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:s}
12){s.forEach((n,i)=>{const{details:r}=n;r!=null&&r.fragments&&r.fragments.forEach(o=>{o.level=i})}),this._levels=s}}function addGroupId(t,e,s){s&&(e==="audio"?(t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds[t.url.length-1]=s):e==="text"&&(t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds[t.url.length-1]=s))}function assignTrackIdsByGroup(t){const e={};t.forEach(s=>{const n=s.groupId||"";s.id=e[n]=e[n]||0,e[n]++})}var FragmentState={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class FragmentTracker{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,s){const n=this.activePartLists[s];if(n)for(let i=n.length;i--;){const r=n[i];if(!r)break;const o=r.end;if(r.start<=e&&o!==null&&e<=o)return r}return this.getBufferedFrag(e,s)}getBufferedFrag(e,s){const{fragments:n}=this,i=Object.keys(n);for(let r=i.length;r--;){const o=n[i[r]];if((o==null?void 0:o.body.type)===s&&o.buffered){const a=o.body;if(a.start<=e&&e<=a.end)return a}}return null}detectEvictedFragments(e,s,n,i){this.timeRanges&&(this.timeRanges[e]=s);const r=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a||r>=a.body.sn)return;if(!a.buffered&&!a.loaded){a.body.type===n&&this.removeFragment(a.body);return}const l=a.range[e];l&&l.time.some(c=>{const d=!this.isTimeBuffered(c.startPTS,c.endPTS,s);return d&&this.removeFragment(a.body),d})})}detectPartialFragments(e){const s=this.timeRanges,{frag:n,part:i}=e;if(!s||n.sn==="initSegment")return;const r=getFragmentKey(n),o=this.fragments[r];if(!o||o.buffered&&n.gap)return;const a=!n.relurl;Object.keys(s).forEach(l=>{const c=n.elementaryStreams[l];if(!c)return;const d=s[l],u=a||c.partial===!0;o.range[l]=this.getBufferedTimes(n,i,u,d)}),o.loaded=null,Object.keys(o.range).length?(o.buffered=!0,o.body.endList&&(this.endListFragments[o.body.type]=o),isPartial(o)||this.removeParts(n.sn-1,n.type)):this.removeFragment(o.body)}removeParts(e,s){const n=this.activePartLists[s];n&&(this.activePartLists[s]=n.filter(i=>i.fragment.sn>=e))}fragBuffered(e,s){const n=getFragmentKey(e);let i=this.fragments[n];!i&&s&&(i=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,s,n,i){const r={time:[],partial:n},o=e.start,a=e.end,l=e.minEndPTS||a,c=e.maxStartPTS||o;for(let d=0;d<i.length;d++){const u=i.start(d)-this.bufferPadding,h=i.end(d)+this.bufferPadding;if(c>=u&&l<=h){r.time.push({startPTS:Math.max(o,i.start(d)),endPTS:Math.min(a,i.end(d))});break}else if(o<h&&a>u)r.partial=!0,r.time.push({startPTS:Math.max(o,i.start(d)),endPTS:Math.min(a,i.end(d))});else if(a<=u)break}return r}getPartialFragment(e){let s=null,n,i,r,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(c=>{const d=l[c];d&&isPartial(d)&&(i=d.body.start-a,r=d.body.end+a,e>=i&&e<=r&&(n=Math.min(e-i,r-e),o<=n&&(s=d.body,o=n)))}),s}isEndListAppended(e){const s=this.endListFragments[e];return s!==void 0&&(s.buffered||isPartial(s))}getState(e){const s=getFragmentKey(e),n=this.fragments[s];return n?n.buffered?isPartial(n)?FragmentState.PARTIAL:FragmentState.OK:FragmentState.APPENDING:FragmentState.NOT_LOADED}isTimeBuffered(e,s,n){let i,r;for(let o=0;o<n.length;o++){if(i=n.start(o)-this.bufferPadding,r=n.end(o)+this.bufferPadding,e>=i&&s<=r)return!0;
vendor: 4,292 bytes, line 12
12if(s<=i)return!1}return!1}onFragLoaded(e,s){const{frag:n,part:i}=s;if(n.sn==="initSegment"||n.bitrateTest)return;const r=i?null:s,o=getFragmentKey(n);this.fragments[o]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,s){const{frag:n,part:i,timeRanges:r}=s;if(n.sn==="initSegment")return;const o=n.type;if(i){let a=this.activePartLists[o];a||(this.activePartLists[o]=a=[]),a.push(i)}this.timeRanges=r,Object.keys(r).forEach(a=>{const l=r[a];this.detectEvictedFragments(a,l,o,i)})}onFragBuffered(e,s){this.detectPartialFragments(s)}hasFragment(e){const s=getFragmentKey(e);return!!this.fragments[s]}hasParts(e){var s;return!!((s=this.activePartLists[e])!=null&&s.length)}removeFragmentsInRange(e,s,n,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==n||i&&!l.gap||l.start<s&&l.end>e&&(a.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const s=getFragmentKey(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=n.filter(r=>r.fragment.sn!==i)}delete this.fragments[s],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function isPartial(t){var e,s,n;return t.buffered&&(t.body.gap||((e=t.range.video)==null?void 0:e.partial)||((s=t.range.audio)==null?void 0:s.partial)||((n=t.range.audiovideo)==null?void 0:n.partial))}function getFragmentKey(t){return`${t.type}_${t.level}_${t.urlId}_${t.sn}`}const MIN_CHUNK_SIZE=Math.pow(2,17);class FragmentLoader{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,s){const n=e.url;if(!n)return Promise.reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,o=i.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(createGapLoadError(e));return}else e.gap=!1;const c=this.loader=e.loader=r?new r(i):new o(i),d=createLoaderContext(e),u=getLoaderConfigWithoutReties(i.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:MIN_CHUNK_SIZE};e.stats=c.stats,c.load(d,h,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,c);let v=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),a({frag:e,part:null,payload:v,networkDetails:m})},onError:(f,g,p,m)=>{this.resetLoader(e,c),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_objectSpread2({url:n,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{this.resetLoader(e,c),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))},onProgress:(f,g,p,m)=>{s&&s({frag:e,part:null,payload:p,networkDetails:m})}})})}loadPart(e,s,n){this.abort();const i=this.config,r=i.fLoader,o=i.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||s.gap){l(createGapLoadError(e,s));return}const c=this.loader=e.loader=r?new r(i):new o(i),d=createLoaderContext(e,s),u=getLoaderConfigWithoutReties(i.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:MIN_CHUNK_SIZE};s.stats=c.stats,c.load(d,h,{onSuccess:(f,g,p,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,s);const v={frag:e,part:s,payload:f.data,networkDetails:m};n(v),a(v)},onError:(f,g,p,m)=>{this.resetLoader(e,c),l(new LoadError({type:ErrorTypes.NETWORK_E
vendor: 4,514 bytes, line 12
12RROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:s,response:_objectSpread2({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{e.stats.aborted=s.stats.aborted,this.resetLoader(e,c),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:s,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:s,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,s){const n=e.stats,i=s.stats,r=i.total;if(n.loaded+=i.loaded,r){const l=Math.round(e.duration/s.duration),c=Math.min(Math.round(n.loaded/r),l),u=(l-c)*Math.round(n.loaded/c);n.total=n.loaded+u}else n.total=Math.max(n.loaded,n.total);const o=n.loading,a=i.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end}resetLoader(e,s){e.loader=null,this.loader===s&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),s.destroy()}}function createLoaderContext(t,e=null){const s=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},i=s.byteRangeStartOffset,r=s.byteRangeEndOffset;if(isFiniteNumber(i)&&isFiniteNumber(r)){var o;let a=i,l=r;if(t.sn==="initSegment"&&((o=t.decryptdata)==null?void 0:o.method)==="AES-128"){const c=r-i;c%16&&(l=r+(16-c%16)),i!==0&&(n.resetIV=!0,a=i-16)}n.rangeStart=a,n.rangeEnd=l}return n}function createGapLoadError(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new LoadError(n)}class LoadError extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class KeyLoader{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[s].loader;if(n){if(e&&e!==n.context.frag.type)return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[e];(s.mediaKeySessionContext||s.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[e].loader;s&&s.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,s=ErrorDetails.KEY_LOAD_ERROR,n,i,r){return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:s,fatal:!1,frag:e,response:r,error:n,networkDetails:i})}loadClear(e,s){if(this.emeController&&this.config.emeEnabled){const{sn:n,cc:i}=e;for(let r=0;r<s.length;r++){const o=s[r];if(i<=o.cc&&(n==="initSegment"||o.sn==="initSegment"||n<o.sn)){this.emeController.selectKeySystemFormat(o).then(a=>{o.setKeyFormat(a)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,s)):this.loadInternal(e)}loadInternal(e,s){var n,i;s&&e.setKeyFormat(s);const r=e.decryptdata;if(!r){const c=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,c))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=this.keyUriToKeyInfo[o];if((n=a)!=null&&n.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});if((i=a)!=null&&i.keyLoadPromise){var l;switch((l=a.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:a}))}}switch(a=this.keyUriToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,s){const n={frag:s,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(n);
12if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,n))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(n)}loadKeyHTTP(e,s){const n=this.config,i=n.loader,r=new i(n);return s.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((o,a)=>{const l={keyInfo:e,frag:s,responseType:"arraybuffer",url:e.decryptdata.uri},c=n.keyLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,g,p)=>{const{frag:m,keyInfo:v,url:S}=g;if(!m.decryptdata||v!==this.keyUriToKeyInfo[S])return a(this.createKeyLoadError(m,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=m.decryptdata.key=new Uint8Array(h.data),m.keyLoader=null,v.loader=null,o({frag:m,keyInfo:v})},onError:(h,f,g,p)=>{this.resetLoader(f),a(this.createKeyLoadError(s,ErrorDetails.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),g,_objectSpread2({url:l.url,data:void 0},h)))},onTimeout:(h,f,g)=>{this.resetLoader(f),a(this.createKeyLoadError(s,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(h,f,g)=>{this.resetLoader(f),a(this.createKeyLoadError(s,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(l,d,u)})}resetLoader(e){const{frag:s,keyInfo:n,url:i}=e,r=n.loader;s.keyLoader===r&&(s.keyLoader=null,n.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}class TaskLoop{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}const noopBuffered={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(e,s){try{if(e){const n=BufferHelper.getBuffered(e);for(let i=0;i<n.length;i++)if(s>=n.start(i)&&s<=n.end(i))return!0}}catch{}return!1}static bufferInfo(e,s,n){try{if(e){const i=BufferHelper.getBuffered(e),r=[];let o;for(o=0;o<i.length;o++)r.push({start:i.start(o),end:i.end(o)});return this.bufferedInfo(r,s,n)}}catch{}return{len:0,start:s,end:s,nextStart:void 0}}static bufferedInfo(e,s,n){s=Math.max(0,s),e.sort(function(c,d){const u=c.start-d.start;return u||d.end-c.end});let i=[];if(n)for(let c=0;c<e.length;c++){const d=i.length;if(d){const u=i[d-1].end;e[c].start-u<n?e[c].end>u&&(i[d-1].end=e[c].end):i.push(e[c])}else i.push(e[c])}else i=e;let r=0,o,a=s,l=s;for(let c=0;c<i.length;c++){const d=i[c].start,u=i[c].end;if(s+n>=d&&s<u)a=d,l=u,r=l-s;else if(s+n<d){o=d;break}}return{len:r,start:a||0,end:l||0,nextStart:o}}static getBuffered(e){try{return e.buffered}catch(s){return logger.log("failed to get media.buffered",s),noopBuffered}}}class ChunkMetadata{constructor(e,s,n,i=0,r=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=getNewPerformanceTiming(),this.buffering={audio:getNewPerformanceTiming(),video:getNewPerformanceTiming(),audiovideo:getNewPerformanceTiming()},this.level=e,this.sn=s,this.id=n,this.size=i,this.part=r,this.partial=o}}function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}function findFirstFragWithCC(t,e){let s=null;for(let n=0,i=t.length;n<i;n++){const r=t[n];if(r&&r.cc===e){s=r;break}}return s}function shouldAlignOnDiscontinuities(t,e,s){return!!(e.details&&(s.endCC>s.startCC||t&&t.cc<s.startCC))}function findDiscontinuousReferenceFrag(t,e,s=0){const n=t.fragments,i=e.fragments;if(!i.length||!n.length){logger.log("No fragments to align");return}const r=findFirstFragWithCC(n,i[0].cc);if(!r||r&&!r.startPTS){logger.log("No frag in previous level to align on");return}return r}function adjustFragmentStart(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function adjustSlidingStart(t,e){const s=e.fragments;for(let n=0,i=s.length;n<i;n++)adjustFragmentStart(s[n],t);e.fragmentHint&&adjustFragmentStart(e.fragmentHint,t),e.alignedSliding=!0}function alignStream(t,e,s){e&&(alignDiscontinuities(t,s,e),!s.alignedSliding&&e.details&&alignPDT(s,e.details),!s.alignedSliding&&e.details&&!s.skippedSegments&&adjustSliding(e.details,s))}function alignDiscontinuities(t,e,s){if(shouldAlignOnDiscontinuities(t,s,e)){const n=find
12DiscontinuousReferenceFrag(s.details,e);n&&isFiniteNumber(n.start)&&(logger.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),adjustSlidingStart(n.start,e))}}function alignPDT(t,e){if(!e.fragments.length||!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=e.fragments[0].programDateTime,n=t.fragments[0].programDateTime,i=(n-s)/1e3+e.fragments[0].start;i&&isFiniteNumber(i)&&(logger.log(`Adjusting PTS using programDateTime delta ${n-s}ms, sliding:${i.toFixed(3)} ${t.url} `),adjustSlidingStart(i,t))}function alignMediaPlaylistByPDT(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,n=e.fragments;if(!s.length||!n.length)return;const i=Math.round(n.length/2)-1,r=n[i],o=findFirstFragWithCC(s,r.cc)||s[Math.round(s.length/2)-1],a=r.programDateTime,l=o.programDateTime;if(a===null||l===null)return;const c=(l-a)/1e3-(o.start-r.start);adjustSlidingStart(c,t)}class AESCrypto{constructor(e,s){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=s}decrypt(e,s){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},s,e)}}class FastAESKey{constructor(e,s){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=s}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function removePadding(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?sliceUint8(t,0,e-s):t}class AESDecryptor{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const s=new DataView(e),n=new Uint32Array(4);for(let i=0;i<4;i++)n[i]=s.getUint32(i*4);return n}initTable(){const e=this.sBox,s=this.invSBox,n=this.subMix,i=n[0],r=n[1],o=n[2],a=n[3],l=this.invSubMix,c=l[0],d=l[1],u=l[2],h=l[3],f=new Uint32Array(256);let g=0,p=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[g]=v,s[v]=g;const S=f[g],y=f[S],C=f[y];let E=f[v]*257^v*16843008;i[g]=E<<24|E>>>8,r[g]=E<<16|E>>>16,o[g]=E<<8|E>>>24,a[g]=E,E=C*16843009^y*65537^S*257^g*16843008,c[v]=E<<24|E>>>8,d[v]=E<<16|E>>>16,u[v]=E<<8|E>>>24,h[v]=E,g?(g=S^f[f[f[C^S]]],p^=f[f[p]]):g=p=1}}expandKey(e){const s=this.uint8ArrayToUint32Array_(e);let n=!0,i=0;for(;i<s.length&&n;)n=s[i]===this.key[i],i++;if(n)return;this.key=s;const r=this.keySize=s.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const o=this.ksRows=(r+6+1)*4;let a,l;const c=this.keySchedule=new Uint32Array(o),d=this.invKeySchedule=new Uint32Array(o),u=this.sBox,h=this.rcon,f=this.invSubMix,g=f[0],p=f[1],m=f[2],v=f[3];let S,y;for(a=0;a<o;a++){if(a<r){S=c[a]=s[a];continue}y=S,a%r===0?(y=y<<8|y>>>24,y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[y&255],y^=h[a/r|0]<<24):r>6&&a%r===4&&(y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[y&255]),c[a]=S=(c[a-r]^y)>>>0}for(l=0;l<o;l++)a=o-l,l&3?y=c[a]:y=c[a-4],l<4||a<=4?d[l]=y:d[l]=g[u[y>>>24]]^p[u[y>>>16&255]]^m[u[y>>>8&255]]^v[u[y&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,s,n){const i=this.keySize+6,r=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],c=a[1],d=a[2],u=a[3],h=this.uint8ArrayToUint32Array_(n);let f=h[0],g=h[1],p=h[2],m=h[3];const v=new Int32Array(e),S=new Int32Array(v.length);let y,C,E,L,T,b,_,I,P,R,D,O,N,H;const W=this.networkToHostOrderSwap;for(;s<v.length;){for(P=W(v[s]),R=W(v[s+1]),D=W(v[s+2]),O=W(v[s+3]),T=P^r[0],b=O^r[1],_=D^r[2],I=R^r[3],N=4,H=1;H<i;H++)y=l[T>>>24]^c[b>>16&255]^d[_>>8&255]^u[I&255]^r[N],C=l[b>>>24]^c[_>>16&255]^d[I>>8&255]^u[T&255]^r[N+1],E=l[_>>>24]^c[I>>16&255]^d[T>>8&255]^u[b&255]^r[N+2],L=l[I>>>24]^c[T>>16&255]^d[b>>8&255]^u[_&255]^r[N+3],T=y,b=C,_=E,I=L,N=N+4;y=o[T>>
vendor: 23,556 bytes, line 12
12>24]<<24^o[b>>16&255]<<16^o[_>>8&255]<<8^o[I&255]^r[N],C=o[b>>>24]<<24^o[_>>16&255]<<16^o[I>>8&255]<<8^o[T&255]^r[N+1],E=o[_>>>24]<<24^o[I>>16&255]<<16^o[T>>8&255]<<8^o[b&255]^r[N+2],L=o[I>>>24]<<24^o[T>>16&255]<<16^o[b>>8&255]<<8^o[_&255]^r[N+3],S[s]=W(y^f),S[s+1]=W(L^g),S[s+2]=W(E^p),S[s+3]=W(C^m),f=P,g=R,p=D,m=O,s=s+4}return S.buffer}}const CHUNK_SIZE=16;class Decrypter{constructor(e,{removePKCS7Padding:s=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=s,s)try{const n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:s}=this;if(!e||s)return this.reset(),null;const n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?removePadding(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,s,n){return this.useSoftware?new Promise((i,r)=>{this.softwareDecrypt(new Uint8Array(e),s,n);const o=this.flush();o?i(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),s,n)}softwareDecrypt(e,s,n){const{currentIV:i,currentResult:r,remainderData:o}=this;this.logOnce("JS AES decrypt"),o&&(e=appendUint8Array(o,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;i&&(n=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new AESDecryptor),l.expandKey(s);const c=r;return this.currentResult=l.decrypt(a.buffer,0,n),this.currentIV=sliceUint8(a,-16).buffer,c||null}webCryptoDecrypt(e,s,n){const i=this.subtle;return(this.key!==s||!this.fastAesKey)&&(this.key=s,this.fastAesKey=new FastAESKey(i,s)),this.fastAesKey.expandKey().then(r=>i?(this.logOnce("WebCrypto AES decrypt"),new AESCrypto(i,new Uint8Array(n)).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,s,n)))}onWebCryptoError(e,s,n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,s,n);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let s=e;const n=e.length-e.length%CHUNK_SIZE;return n!==e.length&&(s=sliceUint8(e,0,n),this.remainderData=sliceUint8(e,n)),s}logOnce(e){this.logEnabled&&(logger.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const TimeRanges={toString:function(t){let e="";const s=t.length;for(let n=0;n<s;n++)e+=`[${t.start(n).toFixed(3)}-${t.end(n).toFixed(3)}]`;return e}},State={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class BaseStreamController extends TaskLoop{constructor(e,s,n,i,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=State.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=i,this.log=logger.log.bind(logger,`${i}:`),this.warn=logger.warn.bind(logger,`${i}:`),this.hls=e,this.fragmentLoader=new FragmentLoader(e.config),this.keyLoader=n,this.fragmentTracker=s,this.config=e.config,this.decrypter=new Decrypter(e.config),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=State.STOPPED}_streamEnded(e,s){if(s.live||e.nextStart||!e.end||!this.media)return!1;const n=s.partList;if(n!=null&&n.length){const r=n[n.length-1];return BufferHelper.isBuffered(this.media,r.start+r.duration/2)}const i=s.fragments[s.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levels[this.levelLastLoaded])==null?void 0:e.details}}onMediaAttached(e,s){const n=this.media=this.mediaBuffer=s.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),n.addEventListener("seeking",this.onvseeking),n.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===State.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:s,media:n,mediaBuffer:i,state:r}=this,o=n?n.currentTime:0,a=BufferHelper.bufferInfo(i||n,o,e.maxBufferHole);if(this.log(`media seeking to ${isFiniteNumber(o)?o.toFixed(3):o}, state: ${r}`),this.state===State.ENDED)this.resetLoadingState();else if(s){const l=e.maxFragLookUpTolerance,c=s.start-l,d=s.start+s.duration+l;if(!a.len||d<a.start||c>a.end){const u=o>d;(o<c||u)&&(u&&s.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),s.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}n&&(this.fragmentTracker.removeFragmentsInRange(o,1/0,this.playlistType,!0),this.lastCurrentTime=o),!this.loadedmetadata&&!a.len&&(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,s){this.startTimeOffset=s.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=State.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,s,n){this._loadFragForPlayback(e,s,n)}_loadFragForPlayback(e,s,n){const i=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,s,n,i).then(r=>{if(!r)return;const o=this.state;if(this.fragContextChanged(e)){(o===State.FRAG_LOADING||!this.fragCurrent&&o===State.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=State.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(Events.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===State.STOPPED||this.state===State.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var s;const{fragmentTracker:n}=this;if(n.getState(e)===FragmentState.APPENDING){const r=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength);this.reduceMaxBufferLength(a)&&n.removeFragment(e)}else((s=this.mediaBuffer)==null?void 0:s.buffered.length)===0?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===FragmentState.PARTIAL&&n.removeFragment(e))}flushMainBuffer(e,s,n=null){if(!(e-s))return;const i={startOffset:e,endOffset:s,type:n};this.hls.trigger(Events.BUFFER_FLUSHING,i)}_loadInitSegment(e,s){this._doFragLoad(e,s).then(n=>{if(!n||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:i}=this,{payload:r}=n,o=e.decryptdata;if(r&&r.byteLength>0&&o&&o.key&&o.iv&&o.method==="AES-128"){const a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),o.key.buffer,o.iv.buffer).catch(l=>{throw i.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return i.trigger(Events.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:a,tdecrypt:c}}),n.payload=l,n})}return n}).then(n=>{const{fragCurrent:i,hls:r,levels:o}=this;if(!o)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=State.IDLE,s.fragmentError=0,e.data=new Uint8Array(n.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),n.frag===i&&r.trigger(Events.FRAG_BUFFERED,{stats:a,frag:i,part:null,id:e.type}),this.tick()}).catch(n=>{this.state===State.STOPPED||this.state===State.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}fragContextChanged(e){const{fragCurrent:s}=this;return!e||!s||e.level!==s.level||e.sn!==s.sn||e.urlId!==s.urlId}fragBufferedComplete(e,s){var n,i,r,o;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${s?" part: "+s.index:""} of ${this.playlistType===PlaylistLevelType.MAIN?"level":"track"} ${e.level} (frag:[${((n=e.startPTS)!=null?n:NaN).toFixed(3)}-${((i=e.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${a?TimeRanges.toString(BufferHelper.getBuffered(a)):"(detached)"})`),this.state=State.IDLE,a&&(!this.loadedmetadata&&e.type==PlaylistLevelType.MAIN&&a.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((o=this.fragPrevious)==null?void 0:o.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:s}=this;if(!s)return;const{frag:n,part:i,partsLoaded:r}=e,o=!r||r.length===0||r.some(l=>!l),a=new ChunkMetadata(n.level,n.sn,n.stats.chunkCount+1,0,i?i.index:-1,!o);s.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,s,n=null,i){var r;const o=s==null?void 0:s.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=State.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(Events.KEY_LOADED,d),this.state===State.KEY_LOADING&&(this.state=State.IDLE),d}),this.hls.trigger(Events.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(e,o.encryptedFragments),n=Math.max(e.start,n||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const d=o.partList;if(d&&i){n>e.end&&o.fragmentHint&&(e=o.fragmentHint);const u=this.getNextPart(d,e,n);if(u>-1){const h=d[u];this.log(`Loading part sn: ${e.sn} p: ${h.index} cc: ${e.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${u}-${d.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=State.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,h,s,i)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,h,s,i).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(Events.FRAG_LOADING,{frag:e,part:h,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(d,n))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),isFiniteNumber(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=State.FRAG_LOADING;const l=this.config.progressive;let c;return l&&a?c=a.then(d=>!d||this.fragContextChanged(d==null?void 0:d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):c=Promise.all([this.fragmentLoader.load(e,l?i:void 0),a]).then(([d])=>(!l&&d&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(Events.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,s,n,i){return new Promise((r,o)=>{var a;const l=[],c=(a=n.details)==null?void 0:a.partList,d=u=>{this.fragmentLoader.loadPart(e,u,i).then(h=>{l[u.index]=h;const f=h.part;this.hls.trigger(Events.FRAG_LOADED,h);const g=getPartWith(n,e.sn,u.index+1)||findPart(c,e.sn,u.index+1);if(g)d(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(o)};d(s)})}handleFragLoadError(e){if("data"in e){const s=e.data;e.data&&s.details===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(s.frag,s.part):this.hls.trigger(Events.ERROR,s)}else this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const s=this.getCurrentContext(e);if(!s||this.state!==State.PARSING){!this.fragCurrent&&this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.state=State.IDLE);return}const{frag:n,part:i,level:r}=s,o=self.performance.now();n.stats.parsing.end=o,i&&(i.stats.parsing.end=o),this.updateLevelTiming(n,i,r,e.partial)}getCurrentContext(e){const{levels:s,fragCurrent:n}=this,{level:i,sn:r,part:o}=e;if(!(s!=null&&s[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const a=s[i],l=o>-1?getPartWith(a,r,o):null,c=l?l.fragment:getFragmentWithSN(a,r,n);return c?(n&&n!==c&&(c.stats=n.stats),{frag:c,part:l,level:a}):null}bufferFragmentData(e,s,n,i,r){var o;if(!e||this.state!==State.PARSING)return;const{data1:a,data2:l}=e;let c=a;if(a&&l&&(c=appendUint8Array(a,l)),!((o=c)!=null&&o.length))return;const d={type:e.type,frag:s,part:n,chunkMeta:i,parent:s.type,data:c};if(this.hls.trigger(Events.BUFFER_APPENDING,d),e.dropped&&e.independent&&!n){if(r)return;this.flushBufferGap(s)}}flushBufferGap(e){const s=this.media;if(!s)return;if(!BufferHelper.isBuffered(s,s.currentTime)){this.flushMainBuffer(0,e.start);return}const n=s.currentTime,i=BufferHelper.bufferInfo(s,n,0),r=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),a=Math.max(Math.min(e.start-o,i.end-o),n+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,s){const n=this.getLoadPosition();return isFiniteNumber(n)?this.getFwdBufferInfoAtPos(e,n,s):null}getFwdBufferInfoAtPos(e,s,n){const{config:{maxBufferHole:i}}=this,r=BufferHelper.bufferInfo(e,s,i);if(r.len===0&&r.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(s,n);if(o&&r.nextStart<o.end)return BufferHelper.bufferInfo(e,s,Math.max(r.nextStart,i))}return r}getMaxBufferLength(e){const{config:s}=this;let n;return e?n=Math.max(8*s.maxBufferSize/e,s.maxBufferLength):n=s.maxBufferLength,Math.min(n,s.maxMaxBufferLength)}reduceMaxBufferLength(e){const s=this.config,n=e||s.maxBufferLength;return s.maxMaxBufferLength>=n?(s.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${s.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,s=PlaylistLevelType.MAIN){const n=this.fragmentTracker.getAppendedFrag(e,PlaylistLevelType.MAIN);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,s){const n=s.fragments,i=n.length;if(!i)return null;const{config:r}=this,o=n[0].start;let a;if(s.live){const l=r.initialLiveManifestSize;if(i<l)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${l})`),null;!s.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(a=this.getInitialLiveFragment(s,n),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=o&&(a=n[0]);if(!a){const l=r.lowLatencyMode?s.partEnd:s.fragmentEnd;a=this.getFragmentAtPosition(e,l,s)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,s){const n=this.fragmentTracker.getState(e);return(n===FragmentState.OK||n===FragmentState.PARTIAL&&!!e.gap)&&this.nextLoadPosition>s}getNextFragmentLoopLoading(e,s,n,i,r){const o=e.gap,a=this.getNextFragment(this.nextLoadPosition,s);if(a===null)return a;if(e=a,o&&e&&!e.gap&&n.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,i);if(l!==null&&n.len+l.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,s,n){let i=-1,r=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const c=e[a];if(o=o&&!c.independent,i>-1&&n<c.start)break;const d=c.loaded;d?i=-1:(r||c.independent||o)&&c.fragment===s&&(i=a),r=d}return i}loadedEndOfParts(e,s){const n=e[e.length-1];return n&&s>n.start&&n.loaded}getInitialLiveFragment(e,s){const n=this.fragPrevious;let i=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),i=findFragmentByPDT(s,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=n.sn+1;if(r>=e.startSN&&r<=e.endSN){const o=s[r-e.startSN];n.cc===o.cc&&(i=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=findFragWithCC(s,n.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,s,n){const{config:i}=this;let{fragPrevious:r}=this,{fragments:o,endSN:a}=n;const{fragmentHint:l}=n,c=i.maxFragLookUpTolerance,d=n.partList,u=!!(i.lowLatencyMode&&d!=null&&d.length&&l);u&&l&&!this.bitrateTest&&(o=o.concat(l),a=l.sn);let h;if(e<s){const f=e>s-c?0:c;h=findFragmentByPTS(r,o,e,f)}else h=o[o.length-1];if(h){const f=h.sn-n.startSN,g=this.fragmentTracker.getState(h);if((g===FragmentState.OK||g===FragmentState.PARTIAL&&h.gap)&&(r=h),r&&h.sn===r.sn&&(!u||d[0].fragment.sn>h.sn)&&r&&h.level===r.level){const m=o[f+1];h.sn<a&&this.fragmentTracker.getState(m)!==FragmentState.OK?h=m:h=null}}return h}synchronizeToLiveEdge(e){const{config:s,media:n}=this;if(!n)return;const i=this.hls.liveSyncPosition,r=n.currentTime,o=e.fragments[0].start,a=e.edge,l=r>=o-s.maxFragLookUpTolerance&&r<=a;if(i!==null&&n.duration>i&&(r<i||!l)){const c=s.liveMaxLatencyDuration!==void 0?s.liveMaxLatencyDuration:s.liveMaxLatencyDurationCount*e.targetduration;(!l&&n.readyState<4||r<a-c)&&(this.loadedmetadata||(this.nextLoadPosition=i),n.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),n.currentTime=i))}}alignPlaylists(e,s){const{levels:n,levelLastLoaded:i,fragPrevious:r}=this,o=i!==null?n[i]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const l=e.fragments[0].start,c=!s,d=e.alignedSliding&&isFiniteNumber(l);if(c||!d&&!l){alignStream(r,o,e);const u=e.fragments[0].start;return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${s?s.startSN:"na"}->${e.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${a}`),u}return l}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,s){let n=this.startPosition;if(n<s&&(n=-1),n===-1||this.lastCurrentTime===-1){const i=this.startTimeOffset!==null,r=i?this.startTimeOffset:e.startTimeOffset;r!==null&&isFiniteNumber(r)?(n=s+r,r<0&&(n+=e.totalduration),n=Math.min(Math.max(s,n),s+e.totalduration),this.log(`Start time offset ${r} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${n}`),this.startPosition=n):e.live?n=this.hls.liveSyncPosition||s:this.startPosition=n=0,this.lastCurrentTime=n}this.nextLoadPosition=n}getLoadPosition(){const{media:e}=this;let s=0;return this.loadedmetadata&&e?s=e.currentTime:this.nextLoadPosition&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,s){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${s?" part "+s.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==State.FRAG_LOADING_WAITING_RETRY)&&(this.state=State.IDLE)}onFragmentOrKeyLoadError(e,s){if(s.chunkMeta&&!s.frag){const u=this.getCurrentContext(s.chunkMeta);u&&(s.frag=u.frag)}const n=s.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var i;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const r=s.details===ErrorDetails.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(n,!0);const o=s.errorAction,{action:a,retryCount:l=0,retryConfig:c}=o||{};if(o&&a===NetworkErrorAction.RetryRequest&&c){var d;this.resetStartWhenNotLoaded((d=this.levelLastLoaded)!=null?d:n.level);const u=getRetryDelay(c,l);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${s.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${u}ms`),o.resolved=!0,this.retryDate=self.performance.now()+u,this.state=State.FRAG_LOADING_WAITING_RETRY}else c&&o?(this.resetFragmentErrors(e),l<c.maxNumRetry?r||(o.resolved=!0):logger.warn(`${s.details} reached or exceeded max retry (${l})`)):(o==null?void 0:o.action)===NetworkErrorAction.SendAlternateToPenaltyBox?this.state=State.WAITING_LEVEL:this.state=State.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===State.PARSING||this.state===State.PARSED){const s=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,s),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len);const r=!i;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(e){e===PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==State.STOPPED&&(this.state=State.IDLE)}afterBufferFlushed(e,s,n){if(!e)return;const i=BufferHelper.getBuffered(e);this.fragmentTracker.detectEvictedFragments(s,i,n),this.state===State.ENDED&&this.resetLoadingState()}
12resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=State.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const s=this.levels?this.levels[e].details:null;s!=null&&s.live?(this.startPosition=-1,this.setStartPosition(s,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var s;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded((s=this.levelLastLoaded)!=null?s:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,s,n,i){var r;const o=n.details;if(!o){this.warn("level.details undefined");return}if(Object.keys(e.elementaryStreams).reduce((l,c)=>{const d=e.elementaryStreams[c];if(d){const u=d.endPTS-d.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${u})`),l||!1;const h=i?0:updateFragPTSDTS(o,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS);return this.hls.trigger(Events.LEVEL_PTS_UPDATED,{details:o,level:n,drift:h,type:c,frag:e,start:d.startPTS,end:d.endPTS}),!0}return l},!1))n.fragmentError=0;else if(((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(n.fragmentError===0&&(n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=State.PARSED,this.hls.trigger(Events.FRAG_PARSED,{frag:e,part:s})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){if(e.event==="demuxerWorker"){var s,n,i;this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded((s=(n=this.levelLastLoaded)!=null?n:(i=this.fragCurrent)==null?void 0:i.level)!=null?s:0),this.resetLoadingState()}}set state(e){const s=this._state;s!==e&&(this._state=e,this.log(`${s}->${e}`))}get state(){return this._state}}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isSupported(){const t=getMediaSource();if(!t)return!1;const e=getSourceBuffer(),s=t&&typeof t.isTypeSupported=="function"&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),n=!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function";return!!s&&!!n}function changeTypeSupported(){var t;const e=getSourceBuffer();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}function hasUMDWorker(){return typeof __HLS_WORKER_BUNDLE__=="function"}function injectWorker(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}function loadWorker(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function dummyTrack(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class BaseAudioDemuxer{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,s,n,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,s){return!1}appendFrame(e,s,n){}demux(e,s){this.cachedData&&(e=appendUint8Array(this.cachedData,e),this.cachedData=null);let n=getID3Data(e,0),i=n?n.length:0,r;const o=this._audioTrack,a=this._id3Track,l=n?getTimeStamp(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&isFiniteNumber(l))&&(this.basePTS=initPTSFn(l,s,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const d=this.appendFrame(o,e,i);d?(this.frameIndex++,this.lastPTS=d.sample.pts,i+=d.length,r=i):i=c}else canParse$2(e,i)?(n=getID3Data(e,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),i+=n.length,r=i):i++;if(i===c&&r!==c){const d=sliceUint8(e,r);this.cachedData?this.cachedData=appendUint8Array(this.cachedData,d):this.cachedData=d}}return{audioTrack:o,videoTrack:dummyTrack(),id3Track:a,textTrack:dummyTrack()}}demuxSampleAes(e,s,n){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const s=this.cachedData;return s&&(this.cachedData=null,this.demux(s,0)),{audioTrack:this._audioTrack,videoTrack:dummyTrack(),id3Track:this._id3Track,textTrack:dummyTrack()}}destroy(){}}const initPTSFn=(t,e,s)=>{if(isFiniteNumber(t))return t*90;const n=s?s.baseTime*9e4/s.timescale:0;return e*9e4+n};function getAudioConfig(t,e,s,n){let i,r,o,a;const l=navigator.userAgent.toLowerCase(),c=n,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((e[s+2]&192)>>>6)+1;const u=(e[s+2]&60)>>>2;if(u>d.length-1){t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:`invali
12d ADTS sampling index:${u}`});return}return o=(e[s+2]&1)<<2,o|=(e[s+3]&192)>>>6,logger.log(`manifest codec:${n}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,a=new Array(4),r=u-3):(i=2,a=new Array(2),r=u):l.indexOf("android")!==-1?(i=2,a=new Array(2),r=u):(i=5,a=new Array(4),n&&(n.indexOf("mp4a.40.29")!==-1||n.indexOf("mp4a.40.5")!==-1)||!n&&u>=6?r=u-3:((n&&n.indexOf("mp4a.40.2")!==-1&&(u>=6&&o===1||/vivaldi/i.test(l))||!n&&o===1)&&(i=2,a=new Array(2)),r=u)),a[0]=i<<3,a[0]|=(u&14)>>1,a[1]|=(u&1)<<7,a[1]|=o<<3,i===5&&(a[1]|=(r&14)>>1,a[2]=(r&1)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:d[u],channelCount:o,codec:"mp4a.40."+i,manifestCodec:c}}function isHeaderPattern$1(t,e){return t[e]===255&&(t[e+1]&246)===240}function getHeaderLength(t,e){return t[e+1]&1?7:9}function getFullFrameLength(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function canGetFrameLength(t,e){return e+5<t.length}function isHeader$1(t,e){return e+1<t.length&&isHeaderPattern$1(t,e)}function canParse$1(t,e){return canGetFrameLength(t,e)&&isHeaderPattern$1(t,e)&&getFullFrameLength(t,e)<=t.length-e}function probe$1(t,e){if(isHeader$1(t,e)){const s=getHeaderLength(t,e);if(e+s>=t.length)return!1;const n=getFullFrameLength(t,e);if(n<=s)return!1;const i=e+n;return i===t.length||isHeader$1(t,i)}return!1}function initTrackConfig(t,e,s,n,i){if(!t.samplerate){const r=getAudioConfig(e,s,n,i);if(!r)return;t.config=r.config,t.samplerate=r.samplerate,t.channelCount=r.channelCount,t.codec=r.codec,t.manifestCodec=r.manifestCodec,logger.log(`parsed codec:${t.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function getFrameDuration(t){return 1024*9e4/t}function parseFrameHeader(t,e){const s=getHeaderLength(t,e);if(e+s<=t.length){const n=getFullFrameLength(t,e)-s;if(n>0)return{headerLength:s,frameLength:n}}}function appendFrame$1(t,e,s,n,i){const r=getFrameDuration(t.samplerate),o=n+i*r,a=parseFrameHeader(e,s);let l;if(a){const{frameLength:u,headerLength:h}=a,f=h+u,g=Math.max(0,s+f-e.length);g?(l=new Uint8Array(f-h),l.set(e.subarray(s+h,e.length),0)):l=e.subarray(s+h,s+f);const p={unit:l,pts:o};return g||t.samples.push(p),{sample:p,length:f,missing:g}}const c=e.length-s;return l=new Uint8Array(c),l.set(e.subarray(s,e.length),0),{sample:{unit:l,pts:o},length:c,missing:-1}}class AACDemuxer extends BaseAudioDemuxer{constructor(e,s){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=s}resetInitSegment(e,s,n,i){super.resetInitSegment(e,s,n,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:s,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let n=(getID3Data(e,0)||[]).length;for(let i=e.length;n<i;n++)if(probe$1(e,n))return logger.log("ADTS sync word found !"),!0;return!1}canParse(e,s){return canParse$1(e,s)}appendFrame(e,s,n){initTrackConfig(e,this.observer,s,n,e.manifestCodec);const i=appendFrame$1(e,s,n,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const emsgSchemePattern=/\/emsg[-/]ID3/i;class MP4Demuxer{constructor(e,s){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=s}resetTimeStamp(){}resetInitSegment(e,s,n,i){const r=this.videoTrack=dummyTrack("video",1),o=this.audioTrack=dummyTrack("audio",1),a=this.txtTrack=dummyTrack("text",1);if(this.id3Track=dummyTrack("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=parseInitSegment(e);if(l.video){const{id:c,timescale:d,codec:u}=l.video;r.id=c,r.timescale=a.timescale=d,r.codec=u}if(l.audio){const{id:c,timescale:d,codec:u}=l.audio;o.id=c,o.timescale=d,o.codec=u}a.id=RemuxerTrackIdConfig.text,r.sampleDuration=0,r.duration=o.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return e=e.length>16384?e.subarray(0,16384):e,findBox(e,["moof"]).length>0}demux(e,s){this.timeOffset=s;let n=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=appendUint8Array(this.remainderData,e));const a=segmentValidRange(n);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=n;const o=this.extractID3Track(i,s);
vendor: 8,175 bytes, line 12
12return r.samples=parseSamples(s,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,s=this.videoTrack,n=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(s,this.timeOffset);return n.samples=parseSamples(e,s),{videoTrack:s,audioTrack:dummyTrack(),id3Track:i,textTrack:dummyTrack()}}extractID3Track(e,s){const n=this.id3Track;if(e.samples.length){const i=findBox(e.samples,["emsg"]);i&&i.forEach(r=>{const o=parseEmsg(r);if(emsgSchemePattern.test(o.schemeIdUri)){const a=isFiniteNumber(o.presentationTime)?o.presentationTime/o.timeScale:s+o.presentationTimeDelta/o.timeScale;let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=o.payload;n.samples.push({data:c,len:c.byteLength,dts:a,pts:a,type:MetadataSchema.emsg,duration:l})}})}return n}demuxSampleAes(e,s,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let chromeVersion$1=null;const BitratesMap=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],SamplingRateMap=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot=[0,1,1,4];function appendFrame(t,e,s,n,i){if(s+24>e.length)return;const r=parseHeader(e,s);if(r&&s+r.frameLength<=e.length){const o=r.samplesPerFrame*9e4/r.sampleRate,a=n+i*o,l={unit:e.subarray(s,s+r.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=r.channelCount,t.samplerate=r.sampleRate,t.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function parseHeader(t,e){const s=t[e+1]>>3&3,n=t[e+1]>>1&3,i=t[e+2]>>4&15,r=t[e+2]>>2&3;if(s!==1&&i!==0&&i!==15&&r!==3){const o=t[e+2]>>1&1,a=t[e+3]>>6,l=s===3?3-n:n===3?3:4,c=BitratesMap[l*14+i-1]*1e3,u=SamplingRateMap[(s===3?0:s===2?1:2)*3+r],h=a===3?1:2,f=SamplesCoefficients[s][n],g=BytesInSlot[n],p=f*8*g,m=Math.floor(f*c/u+o)*g;if(chromeVersion$1===null){const y=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion$1=y?parseInt(y[1]):0}return!!chromeVersion$1&&chromeVersion$1<=87&&n===2&&c>=224e3&&a===0&&(t[e+3]=t[e+3]|128),{sampleRate:u,channelCount:h,frameLength:m,samplesPerFrame:p}}}function isHeaderPattern(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function isHeader(t,e){return e+1<t.length&&isHeaderPattern(t,e)}function canParse(t,e){return isHeaderPattern(t,e)&&4<=t.length-e}function probe(t,e){if(e+1<t.length&&isHeaderPattern(t,e)){const n=parseHeader(t,e);let i=4;n!=null&&n.frameLength&&(i=n.frameLength);const r=e+i;return r===t.length||isHeader(t,r)}return!1}class ExpGolomb{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,s=this.bytesAvailable,n=e.byteLength-s,i=new Uint8Array(4),r=Math.min(4,s);if(r===0)throw new Error("no bytes available");i.set(e.subarray(n,n+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let s;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,s=e>>3,e-=s<<3,this.bytesAvailable-=s,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let s=Math.min(this.bitsAvailable,e);const n=this.word>>>32-s;if(e>32&&logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=s,this.bitsAvailable>0)this.word<<=s;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return s=e-s,s>0&&this.bitsAvailable?n<<s|this.readBits(s):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let s=8,n=8,i;for(let r=0;r<e;r++)n!==0&&(i=this.readEG(),n=(s+i+256)%256),s=n===0?s:n}readSPS(){let e=0,s=0,n=0,i=0,r,o,a;const l=this.readUByte.bind(this),c=this.readBits.bind(this),d=this.readUEG.bind(this),u=this.readBoolean.bind(this),h=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);l();const m=l();if(c(5),h(3),l(),g(),m===100||m===110||m===122||m===244||m===44||m===83||m===86||m===118||m===128){const L=d();if(L===3&&h(1),g(),g(),h(1),u())for(o=L!==3?8:12,a=0;a<o;a++)u()&&(a<6?p(16):p(64))}g();const v=d();if(v===0)d();else if(v===1)for(h(1),f(),f(),r=d(),a=0;a<r;a++)f();g(),h(1);const S=d(),y=d(),C=c(1);C===0&&h(1),h(1),u()&&(e=d(),s=d(),n=d(),i=d());let E=[1,1];if(u()&&u())switch(l()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:{E=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((S+1)*16-e*2-s*2),height:(2-C)*(y+1)*16-(C?2:4)*(n+i),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class SampleAesDecrypter{constructor(e,s,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Decrypter(s,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,s,n){const i=e[s].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),o=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,s+1,n)})}decryptAacSamples(e,s,n){for(;;s++){if(s>=e.length){n();return}if(!(e[s].unit.length<32)&&(this.decryptAacSample(e,s,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const s=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(s);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)n.set(e.subarray(r,r+16),i);return n}getAvcDecryptedUnit(e,s){const n=new Uint8Array(s);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(n.subarray(i,i+16),r);return e}decryptAvcSample(e,s,n,i,r){const o=discardEPB(r.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,s,n+1,i)})}decryptAvcSamples(e,s,n,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;s++,n=0){if(s>=e.length){i();return}const r=e[s].units;for(;!(n>=r.length);n++){const o=r[n];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,s,n,i,o),!this.decrypter.isSync()))return}}}}const PACKET_LENGTH=188;class TSDemuxer{constructor(e,s,n){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=s,this.typeSupported=n}static probe(e){const s=TSDemuxer.syncOffset(e);return s>0&&logger.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const s=e.length;let n=Math.min(PACKET_LENGTH*5,e.length-PACKET_LENGTH)+1,i=0;for(;i<n;){let r=!1,o=-1,a=0;for(let l=i;l<s;l+=PACKET_LENGTH)if(e[l]===71){if(a++,o===-1&&(o=l,o!==0&&(n=Math.min(o+PA
12CKET_LENGTH*99,e.length-PACKET_LENGTH)+1)),r||(r=parsePID(e,l)===0),r&&a>1&&(o===0&&a>2||l+PACKET_LENGTH>n))return o}else{if(a)return-1;break}i++}return-1}static createTrack(e,s){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:RemuxerTrackIdConfig[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?s:void 0}}resetInitSegment(e,s,n,i){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=TSDemuxer.createTrack("video"),this._audioTrack=TSDemuxer.createTrack("audio",i),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=s,this.videoCodec=n,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:s,_id3Track:n}=this;e&&(e.pesData=null),s&&(s.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,s,n=!1,i=!1){n||(this.sampleAes=null);let r;const o=this._avcTrack,a=this._audioTrack,l=this._id3Track,c=this._txtTrack;let d=o.pid,u=o.pesData,h=a.pid,f=l.pid,g=a.pesData,p=l.pesData,m=null,v=this.pmtParsed,S=this._pmtId,y=e.length;if(this.remainderData&&(e=appendUint8Array(this.remainderData,e),y=e.length,this.remainderData=null),y<PACKET_LENGTH&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};const C=Math.max(0,TSDemuxer.syncOffset(e));y-=(y-C)%PACKET_LENGTH,y<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let E=0;for(let T=C;T<y;T+=PACKET_LENGTH)if(e[T]===71){const b=!!(e[T+1]&64),_=parsePID(e,T),I=(e[T+3]&48)>>4;let P;if(I>1){if(P=T+5+e[T+4],P===T+PACKET_LENGTH)continue}else P=T+4;switch(_){case d:b&&(u&&(r=parsePES(u))&&this.parseAVCPES(o,c,r,!1),u={data:[],size:0}),u&&(u.data.push(e.subarray(P,T+PACKET_LENGTH)),u.size+=T+PACKET_LENGTH-P);break;case h:if(b){if(g&&(r=parsePES(g)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,T+PACKET_LENGTH)),g.size+=T+PACKET_LENGTH-P);break;case f:b&&(p&&(r=parsePES(p))&&this.parseID3PES(l,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(P,T+PACKET_LENGTH)),p.size+=T+PACKET_LENGTH-P);break;case 0:b&&(P+=e[P]+1),S=this._pmtId=parsePAT(e,P);break;case S:{b&&(P+=e[P]+1);const R=parsePMT(e,P,this.typeSupported,n);d=R.avc,d>0&&(o.pid=d),h=R.audio,h>0&&(a.pid=h,a.segmentCodec=R.segmentCodec),f=R.id3,f>0&&(l.pid=f),m!==null&&!v&&(logger.warn(`MPEG-TS PMT found at ${T} after unknown PID '${m}'. Backtracking to sync byte @${C} to parse all TS packets.`),m=null,T=C-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=_;break}}else E++;if(E>0){const T=new Error(`Found ${E} TS packet/s that do not start with 0x47`);this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:T,reason:T.message})}o.pesData=u,a.pesData=g,l.pesData=p;const L={audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(L),L}flush(){const{remainderData:e}=this;this.remainderData=null;let s;return e?s=this.demux(e,-1,!1,!0):s={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(e){const{audioTrack:s,videoTrack:n,id3Track:i,textTrack:r}=e,o=n.pesData,a=s.pesData,l=i.pesData;let c;if(o&&(c=parsePES(o))?(this.parseAVCPES(n,r,c,!0),n.pesData=null):n.pesData=o,a&&(c=parsePES(a))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,c);break;case"mp3":this.parseMPEGPES(s,c);break}s.pesData=null}else a!=null&&a.size&&logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=a;l&&(c=parsePES(l))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l}demuxSampleAes(e,s,n){const i=this.demux(e,n,!0,!this.config.progressive),r=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,s);return this.decrypt(i,r)}decrypt(e,s){return new Promise(n=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?s.decryptAacSamples(i.samples,0,()=>{r.samples?s.decryptAvcSamples(r.samples,0,0,()=>{n(e)}):n(e)}):r.samples&&s.decryptAvcSamples(r.samples,0,0,()=>{n(e)})})}destroy(){this._duration=0}parseAVCPES(e,s,n,i){const r=this.parseAVCNALu(e,n.data);let o=this.avcSample,a,l=!1;n.data=null,o&&r.length&&!e.audFound&&(pushAccessUnit(o,e),o=this.avcSample=createAVCSample(!1,n.pts,n.dts,"")),r.forEach(c=>{var d;switch(c.type){case 1:{let h=!1;a=!0;const f=c.data;if(l&&f.length>4){const g=new ExpGolomb(f).readSliceType();(g===2||g===4||g===7||g===9)&&(h=!0)}if(h){var u;(u=o)!=null&&u.frame&&!o.key&&(pushAccessUnit(o,e),o=this.avcSample=null)}o||(o=this.avcSample=createAVCSample(!0,n.pts,n.dts,"")),o.frame=!0,o.key=h;break}case 5:a=!0,(d=o)!=null&&d.frame&&!o.key&&(pushAccessUnit(o,e),o=this.avcSample=null),o||(o=this.avcSample=createAVCSample(!0,n.pts,n.dts,"")),o.key=!0,o.frame=!0;break;case 6:{a=!0,parseSEIMessageFromNALu(c.data,1,n.pts,s.samples);break}case 7:if(a=!0,l=!0,!e.sps){const h=c.data,g=new ExpGolomb(h).readSPS();e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[h],e.duration=this._duration;const p=h.subarray(1,4);let m="avc1.";for(let v=0;v<3;v++){let S=p[v].toString(16);S.length<2&&(S="0"+S),m+=S}e.codec=m}break;case 8:a=!0,e.pps||(e.pps=[c.data]);break;case 9:a=!1,e.audFound=!0,o&&pushAccessUnit(o,e),o=this.avcSample=createAVCSample(!1,n.pts,n.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+c.type+" ");break}o&&a&&o.units.push(c)}),i&&o&&(pushAccessUnit(o,e),this.avcSample=null)}
12getLastNalUnit(e){var s;let n=this.avcSample,i;if((!n||n.units.length===0)&&(n=e[e.length-1]),(s=n)!=null&&s.units){const r=n.units;i=r[r.length-1]}return i}parseAVCNALu(e,s){const n=s.byteLength;let i=e.naluState||0;const r=i,o=[];let a=0,l,c,d,u=-1,h=0;for(i===-1&&(u=0,h=s[0]&31,i=0,a=1);a<n;){if(l=s[a++],!i){i=l?0:1;continue}if(i===1){i=l?0:2;continue}if(!l)i=3;else if(l===1){if(u>=0){const f={data:s.subarray(u,a-i-1),type:h};o.push(f)}else{const f=this.getLastNalUnit(e.samples);if(f&&(r&&a<=4-r&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-r)),c=a-i-1,c>0)){const g=new Uint8Array(f.data.byteLength+c);g.set(f.data,0),g.set(s.subarray(0,c),f.data.byteLength),f.data=g,f.state=0}}a<n?(d=s[a]&31,u=a,h=d,i=0):i=-1}else i=0}if(u>=0&&i>=0){const f={data:s.subarray(u,n),type:h,state:i};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);if(f){const g=new Uint8Array(f.data.byteLength+s.byteLength);g.set(f.data,0),g.set(s,f.data.byteLength),f.data=g}}return e.naluState=i,o}parseAACPES(e,s){let n=0;const i=this.aacOverFlow;let r=s.data;if(i){this.aacOverFlow=null;const u=i.missing,h=i.sample.unit.byteLength;if(u===-1){const f=new Uint8Array(h+r.byteLength);f.set(i.sample.unit,0),f.set(r,h),r=f}else{const f=h-u;i.sample.unit.set(r.subarray(0,u),f),e.samples.push(i.sample),n=i.missing}}let o,a;for(o=n,a=r.length;o<a-1&&!isHeader$1(r,o);o++);if(o!==n){let u;const h=o<a-1;h?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES";const f=new Error(u);if(logger.warn(`parsing error: ${u}`),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,levelRetry:h,error:f,reason:u}),!h)return}initTrackConfig(e,this.observer,r,o,this.audioCodec);let l;if(s.pts!==void 0)l=s.pts;else if(i){const u=getFrameDuration(e.samplerate);l=i.sample.pts+u}else{logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,d;for(;o<a;)if(d=appendFrame$1(e,r,o,l,c),o+=d.length,d.missing){this.aacOverFlow=d;break}else for(c++;o<a-1&&!isHeader$1(r,o);o++);}parseMPEGPES(e,s){const n=s.data,i=n.length;let r=0,o=0;const a=s.pts;if(a===void 0){logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<i;)if(isHeader(n,o)){const l=appendFrame(e,n,o,a,r);if(l)o+=l.length,r++;else break}else o++}parseID3PES(e,s){if(s.pts===void 0){logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=_extends({},s,{type:this._avcTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function createAVCSample(t,e,s,n){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:n,length:0}}function parsePID(t,e){return((t[e+1]&31)<<8)+t[e+2]}function parsePAT(t,e){return(t[e+10]&31)<<8|t[e+11]}function parsePMT(t,e,s,n){const i={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},r=(t[e+1]&15)<<8|t[e+2],o=e+3+r-4,a=(t[e+10]&15)<<8|t[e+11];for(e+=12+a;e<o;){const l=parsePID(t,e);switch(t[e]){case 207:if(!n){logger.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:i.audio===-1&&(i.audio=l);break;case 21:i.id3===-1&&(i.id3=l);break;case 219:if(!n){logger.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:i.avc===-1&&(i.avc=l);break;case 3:case 4:s.mpeg!==!0&&s.mp3!==!0?logger.log("MPEG audio found, not supported in this browser"):i.audio===-1&&(i.audio=l,i.segmentCodec="mp3");break;case 36:logger.warn("Unsupported HEVC stream type found");break}e+=((t[e+3]&15)<<8|t[e+4])+5}return i}function parsePES(t){let e=0,s,n,i,r,o;const a=t.data;if(!t||t.size===0)return null;for(;a[0].length<19&&a.length>1;){const c=new Uint8Array(a[0].length+a[1].length);c.set(a[0]),c.set(a[1],a[0].length),a[0]=c,a.splice(1,1)}if(s=a[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(n=(s[4]<<8)+s[5],n&&n>t.size-6)return null;const c=s[7];c&192&&(r=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,c&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,r-o>60*9e4&&(logger.warn(`${Math.round((r-o)/9e4)}s delta between PTS and DTS, align them`),r=o)):o=r),i=s[8];let d=i+9;if(t.size<=d)return null;t.size-=d;const u=new Uint8Array(t.size);for(let h=0,f=a.length;h<f;h++){s=a[h];let g=s.byteLength;if(d)if(d>g){d-=g;continue}else s=s.subarray(d),g-=d,d=0;u.set(s,e),e+=g}return n&&(n-=i+3),{data:u,pts:r,dts:o,len:n}}return null}function pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){const s=e.samples,n=s.length;if(n){const i=s[n-1];t.pts=i.pts,t.dts=i.dts}else{e.dropped++;return}}e.samples.push(t)}t.debug.length&&logger.log(t.pts+"/"+t.dts+":"+t.debug)}class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(e,s,n,i){super.resetInitSegment(e,s,n,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:s,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let n=(getID3Data(e,0)||[]).length;for(let i=e.length;n<i;n++)if(probe(e,n))return logger.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,s){return canParse(e,s)}appendFrame(e,s,n){if(this.basePTS!==null)return appendFrame(e,s,n,this.basePTS,this.frameIndex)}}class AAC{static getSilentFrame(e,s){switch(e){case"mp4a.40.2":if(s===1)return new Uint8Array([0,200,0,128,35,128]);if(s===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(s===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(s===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(s===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(s===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(s===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(s===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(s===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const UINT32_MAX=Math.pow(2,32)-1;class MP4{static init(){MP4.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in MP4.types)MP4.types.hasOwnProperty(e)&&(MP4.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const s=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={video:s,audio:n};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new 
vendor: 30,837 bytes, line 12
12Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=r,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,o,l,o,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,i))}static box(e,...s){let n=8,i=s.length;const r=i;for(;i--;)n+=s[i].byteLength;const o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=n&255,o.set(e,4),i=0,n=8;i<r;i++)o.set(s[i],n),n+=s[i].byteLength;return o}static hdlr(e){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[e])}static mdat(e){return MP4.box(MP4.types.mdat,e)}static mdhd(e,s){s*=e;const n=Math.floor(s/(UINT32_MAX+1)),i=Math.floor(s%(UINT32_MAX+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return MP4.box(MP4.types.mdia,MP4.mdhd(e.timescale,e.duration),MP4.hdlr(e.type),MP4.minf(e))}static mfhd(e){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(e)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(e))}static moof(e,s,n){return MP4.box(MP4.types.moof,MP4.mfhd(e),MP4.traf(n,s))}static moov(e){let s=e.length;const n=[];for(;s--;)n[s]=MP4.trak(e[s]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(e[0].timescale,e[0].duration)].concat(n).concat(MP4.mvex(e)))}static mvex(e){let s=e.length;const n=[];for(;s--;)n[s]=MP4.trex(e[s]);return MP4.box.apply(null,[MP4.types.mvex,...n])}static mvhd(e,s){s*=e;const n=Math.floor(s/(UINT32_MAX+1)),i=Math.floor(s%(UINT32_MAX+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,r)}static sdtp(e){const s=e.samples||[],n=new Uint8Array(4+s.length);let i,r;for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return MP4.box(MP4.types.sdtp,n)}static stbl(e){return MP4.box(MP4.types.stbl,MP4.stsd(e),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(e){let s=[],n=[],i,r,o;for(i=0;i<e.sps.length;i++)r=e.sps[i],o=r.byteLength,s.push(o>>>8&255),s.push(o&255),s=s.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],o=r.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(r));const a=MP4.box(MP4.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),l=e.width,c=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return MP4.box(MP4.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const s=e.config.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([s]).concat(e.config).concat([6,1,2]))}static mp4a(e){const s=e.samplerate;return MP4.box(MP4.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,s>>8&255,s&255,0,0]),MP4.box(MP4.types.esds,MP4.esds(e)))}static mp3(e){const s=e.samplerate;return MP4.box(MP4.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,s>>8&255,s&255,0,0]))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(e))}static tkhd(e){const s=e.id,n=e.duration*e.timescale,i=e.width,r=e.height,o=Math.floor(n/(UINT32_MAX+1)),a=Math.floor(n%(UINT32_MAX+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,s&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,s){const n=MP4.sdtp(e),i=e.id,r=Math.floor(s/(UINT32_MAX+1)),o=Math.floor(s%(UINT32_MAX+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255])),MP4.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(e),MP4.mdia(e))}static trex(e){const s=e.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,s){const n=e.samples||[],i=n.length,r=12+16*i,o=new Uint8Array(r);let a,l,c,d,u,h;for(s+=8+r,o.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255],0),a=0;a<i;a++)l=n[a],c=l.duration,d=l.size,u=l.flags,h=l.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*a);return MP4.box(MP4.types.trun,o)}static initSegment(e){MP4.types||MP4.init();const s=MP4.moov(e),n=new Uint8Array(MP4.FTYP.byteLength+s.byteLength);return n.set(MP4.FTYP),n.set(s,MP4.FTYP.byteLength),n}}MP4.types=void 0;MP4.HDLR_TYPES=void 0;MP4.STTS=void 0;MP4.STSC=void 0;MP4.STCO=void 0;MP4.STSZ=void 0;MP4.VMHD=void 0;MP4.SMHD=void 0;MP4.STSD=void 0;MP4.FTYP=void 0;MP4.DINF=void 0;const MPEG_TS_CLOCK_FREQ_HZ=9e4;function toTimescaleFromBase(t,e,s=1,n=!1){const i=t*e*s;return n?Math.round(i):i}function toTimescaleFromScale(t,e,s=1,n=!1){return toTimescaleFromBase(t,e,1/s,n)}function toMsFromMpegTsClock(t,e=!1){return toTimescaleFromBase(t,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,e)}function toMpegTsClockFromTimescale(t,e=1){return toTimescaleFromBase(t,MPEG_TS_CLOCK_FREQ_HZ,1/e)}const MAX_SILENT_FRAME_DURATION=10*1e3,AAC_SAMPLES_PER_FRAME=1024,MPEG_AUDIO_SAMPLE_PER_FRAME=1152;let chromeVersion=null,safariWebkitVersion=null;class MP4Remuxer{constructor(e,s,n,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=s,this.typeSupported=n,this.ISGenerated=!1,chromeVersion===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion=o?parseInt(o[1]):0}if(safariWebkitVersion===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);safariWebkitVersion=r?parseInt(r[1]):0}}destroy(){}resetTimeStamp(e){logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let s=!1;const n=e.reduce((i,r)=>{const o=r.pts-i;return o<-4294967296?(s=!0,normalizePts(i,r.pts)):o>0?i:r.pts},e[0].pts);return s&&logger.debug("PTS rollover detected"),n}remux(e,s,n,i,r,o,a,l){let c,d,u,h,f,g,p=r,m=r;const v=e.pid>-1,S=s.pid>-1,y=s.samples.length,C=e.samples.length>0,E=a&&y>0||y>1;if((!v||C)&&(!S||E)||this.ISGenerated||a){this.ISGenerated||(u=this.generateIS(e,s,r,o));const T=this.isVideoContiguous;let b=-1,_;if(E&&(b=findKeyframeIndex(s.samples),!T&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,b>0){logger.warn(`[mp4-remuxer]: Dropped ${b} out of ${y} video samples due to a missing keyframe`);const I=this.getVideoStartPts(s.samples);s.samples=s.samples.slice(b),s.dropped+=b,m+=(s.samples[0].pts-I)/s.inputTimeScale,_=m}else b===-1&&(logger.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),g=!1);if(this.ISGenerated){if(C&&E){const I=this.getVideoStartPts(s.samples),R=(normalizePts(e.samples[0].pts,I)-I)/s.inputTimeScale;p+=Math.max(0,R),m+=Math.max(0,-R)}if(C){if(e.samplerate||(logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,s,r,o)),d=this.remuxAudio(e,p,this.isAudioContiguous,o,S||E||l===PlaylistLevelType.AUDIO?m:void 0),E){const I=d?d.endPTS-d.startPTS:0;s.inputTimeScale||(logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,s,r,o)),c=this.remuxVideo(s,m,T,I)}}else E&&(c=this.remuxVideo(s,m,T,0));c&&(c.firstKeyFrame=b,c.independent=b!==-1,c.firstKeyFramePTS=_)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(f=flushTextTrackMetadataCueSamples(n,r,this._initPTS,this._initDTS)),i.samples.length&&(h=flushTextTrackUserdataCueSamples(i,r,this._initPTS))),{audio:d,video:c,initSegment:u,independent:g,text:h,id3:f}}generateIS(e,s,n,i){const r=e.samples,o=s.samples,a=this.typeSupported,l={},c=this._initPTS;let d=!c||i,u="audio/mp4",h,f,g;if(d&&(h=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(u="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):MP4.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(g=e.inputTimeScale,!c||g!==c.timescale?h=f=r[0].pts-Math.round(g*n):d=!1)}if(s.sps&&s.pps&&o.length&&(s.timescale=s.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:s.codec,initSegment:MP4.initSegment([s]),metadata:{width:s.width,height:s.height}},d))if(g=s.inputTimeScale,!c||g!==c.timescale){const p=this.getVideoStartPts(o),m=Math.round(g*n);f=Math.min(f,normalizePts(o[0].dts,p)-m),h=Math.min(h,p-m)}else d=!1;if(Object.keys(l).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:h,timescale:g},this._initDTS={baseTime:f,timescale:g}):h=g=void 0,{tracks:l,initPTS:h,timescale:g}}remuxVideo(e,s,n,i){const r=e.inputTimeScale,o=e.samples,a=[],l=o.length,c=this._initPTS;let d=this.nextAvcDts,u=8,h=this.videoSampleDuration,f,g,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!n||d===null){const M=s*r,A=o[0].pts-normalizePts(o[0].dts,o[0].pts);d=M-A}const S=c.baseTime*r/c.timescale;for(let M=0;M<l;M++){const A=o[M];A.pts=normalizePts(A.pts-S,d),A.dts=normalizePts(A.dts-S,d),A.dts<o[M>0?M-1:M].dts&&(v=!0)}v&&o.sort(function(M,A){const w=M.dts-A.dts,k=M.pts-A.pts;return w||k}),f=o[0].dts,g=o[o.length-1].dts;const y=g-f,C=y?Math.round(y/(l-1)):h||e.inputTimeScale/30;if(n){const M=f-d,A=M>C,w=M<-1;if((A||w)&&(A?logger.warn(`AVC: ${toMsFromMpegTsClock(M,!0)} ms (${M}dts) hole between fragments detected, filling it`):logger.warn(`AVC: ${toMsFromMpegTsClock(-M,!0)} ms (${M}dts) overlapping between fragments detected`),!w||d>=o[0].pts)){f=d;const k=o[0].pts-M;o[0].dts=f,o[0].pts=k,logger.log(`Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock(k,!0)}/${toMsFromMpegTsClock(f,!0)}, delta: ${toMsFromMpegTsClock(M,!0)} ms`)}}f=Math.max(0,f);let E=0,L=0;for(let M=0;M<l;M++){const A=o[M],w=A.units,k=w.length;let F=0;for(let B=0;B<k;B++)F+=w[B].data.length;L+=F,E+=k,A.length=F,A.dts=Math.max(A.dts,f),p=Math.min(A.pts,p),m=Math.max(A.pts,m)}g=o[l-1].dts;const T=L+4*E+8;let b;try{b=new Uint8Array(T)}catch(M){this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:T,reason:`fail allocating video mdat ${T}`});return}const _=new DataView(b.buffer);_.setUint32(0,T),b.set(MP4.types.mdat,4);let I=!1,P=Number.POSITIVE_INFINITY,R=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let M=0;M<l;M++){const A=o[M],w=A.units;let k=0;for(let K=0,G=w.length;K<G;K++){const U=w[K],Y=U.data,J=U.data.byteLength;_.setUint32(u,J),u+=4,b.set(Y,u),u+=J,k+=4+J}let F;if(M<l-1)h=o[M+1].dts-A.dts,F=o[M+1].pts-A.pts;else{const K=this.config,G=M>0?A.dts-o[M-1].dts:C;if(F=M>0?A.pts-o[M-1].pts:C,K.stretchShortVideoTrack&&this.nextAudioPts!==null){const U=Math.floor(K.maxBufferHole*r),Y=(i?p+i*r:this.nextAudioPts)-A.pts;Y>U?(h=Y-G,h<0?h=G:I=!0,logger.log(`[mp4-remuxer]: It is approximately ${Y/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=G}else h=G}const B=Math.round(A.pts-A.dts);P=Math.min(P,h),D=Math.max(D,h),R=Math.min(R,F),O=Math.max(O,F),a.push(new Mp4Sample(A.key,h,k,B))}if(a.length){if(chromeVersion){if(chromeVersion<70){const M=a[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(safariWebkitVersion&&O-R<D-P&&C/D<.025&&a[0].cts===0){logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=f;for(let A=0,w=a.length;A<w;A++){const k=M+a[A].duration,F=M+a[A].cts;if(A<w-1){const B=k+a[A+1].cts;a[A].duration=B-F}else a[A].duration=A?a[A-1].duration:C;a[A].cts=0,M=k}}}h=I||!h?C:h,this.nextAvcDts=d=g+h,this.videoSampleDuration=h,this.isVideoContiguous=!0;const W={data1:MP4.moof(e.sequenceNumber++,f,_extends({},e,{samples:a})),data2:b,startPTS:p/r,endPTS:(m+h)/r,startDTS:f/r,endDTS:d/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}remuxAudio(e,s,n,i,r){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,c=e.segmentCodec==="aac"?AAC_SAMPLES_PER_FRAME:MPEG_AUDIO_SAMPLE_PER_FRAME,d=c*l,u=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let p=e.samples,m=h?0:8,v=this.nextAudioPts||-1;const S=s*o,y=u.baseTime*o/u.timescale;if(this.isAudioContiguous=n=n||p.length&&v>0&&(i&&Math.abs(S-v)<9e3||Math.abs(normalizePts(p[0].pts-y,S)-v)<20*d),p.forEach(function(H){H.pts=normalizePts(H.pts-y,S)}),!n||v<0){if(p=p.filter(H=>H.pts>=0),!p.length)return;r===0?v=0:i&&!g?v=Math.max(0,S):v=p[0].pts}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let W=0,M=v;W<p.length;W++){const A=p[W],w=A.pts,k=w-M,F=Math.abs(1e3*k/o);if(k<=-H*d&&g)W===0&&(logger.warn(`Audio frame @ ${(w/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*k/o)} ms.`),this.nextAudioPts=v=M=w);else if(k>=H*d&&F<MAX_SILENT_FRAME_DURATION&&g){let B=Math.round(k/d);M=w-B*d,M<0&&(B--,M+=d),W===0&&(this.nextAudioPts=v=M),logger.warn(`[mp4-remuxer]: Injecting ${B} audio frame @ ${(M/o).toFixed(3)}s due to ${Math.round(1e3*k/o)} ms gap.`);for(let K=0;K<B;K++){const G=Math.max(M,0);let U=AAC.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);U||(logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),U=A.unit.subarray()),p.splice(W,0,{unit:U,pts:G}),M+=d,W++}}A.pts=M,M+=d}}let C=null,E=null,L,T=0,b=p.length;for(;b--;)T+=p[b].unit.byteLength;for(let H=0,W=p.length;H<W;H++){const M=p[H],A=M.unit;let w=M.pts;if(E!==null){const F=f[H-1];F.duration=Math.round((w-E)/l)}else if(n&&e.segmentCodec==="aac"&&(w=v),C=w,T>0){T+=m;try{L=new Uint8Array(T)}catch(F){this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:T,reason:`fail allocating audio mdat ${T}`});return}h||(new DataView(L.buffer).setUint32(0,T),L.set(MP4.types.mdat,4))}else return;L.set(A,m);const k=A.byteLength;m+=k,f.push(new Mp4Sample(!0,c,k,0)),E=w}const _=f.length;if(!_)return;const I=f[f.length-1];this.nextAudioPts=v=E+l*I.duration;const P=h?new Uint8Array(0):MP4.moof(e.sequenceNumber++,C/l,_extends({},e,{samples:f}));e.samples=[];const R=C/o,D=v/o,N={data1:P,data2:L,startPTS:R,endPTS:D,startDTS:R,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:_};return this.isAudioContiguous=!0,N}remuxEmptyAudio(e,s,n,i){const r=e.inputTimeScale,o=e.samplerate?e.samplerate:r,a=r/o,l=this.nextAudioPts,c=this._initDTS,d=c.baseTime*9e4/c.timescale,u=(l!==null?l:i.startDTS*r)+d,h=i.endDTS*r+d,f=a*AAC_SAMPLES_PER_FRAME,g=Math.ceil((h-u)/f),p=AAC.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(logger.warn("[mp4-remuxer]: remux empty Audio"),!p){logger.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const m=[];for(let v=0;v<g;v++){const S=u+v*f;m.push({unit:p,pts:S,dts:S})}return e.samples=m,this.remuxAudio(e,s,n,!1)}}function normalizePts(t,e){let s;if(e===null)return t;for(e<t?s=-8589934592:s=8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function findKeyframeIndex(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}function flushTextTrackMetadataCueSamples(t,e,s,n){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let a=0;a<i;a++){const l=t.samples[a];l.pts=normalizePts(l.pts-s.baseTime*r/s.timescale,e*r)/r,l.dts=normalizePts(l.dts-n.baseTime*r/n.timescale,e*r)/r}const o=t.samples;return t.samples=[],{samples:o}}function flushTextTrackUserdataCueSamples(t,e,s){const n=t.samples.length;if(!n)return;const i=t.inputTimeScale;for(let o=0;o<n;o++){const a=t.samples[o];a.pts=normalizePts(a.pts-s.baseTime*i/s.timescale,e*i)/i}t.samples.sort((o,a)=>o.pts-a.pts);const r=t.samples;return t.samples=[],{samples:r}}class Mp4Sample{constructor(e,s,n,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=s,this.size=n,this.cts=i,this.flags=new Mp4SampleFlags(e)}}class Mp4SampleFlags{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}class PassThroughRemuxer{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,s,n,i){this.audioCodec=s,this.videoCodec=n,this.generateInitSegment(patchEncyptionData(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:s,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=parseInitSegment(e);s||(s=getParsedTrackCodec(i.audio,ElementaryStreamTypes.AUDIO)),n||(n=getParsedTrackCodec(i.video,ElementaryStreamTypes.VIDEO));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:s+","+n,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:s,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:n,initSegment:e,id:"main"}:logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,s,n,i,r,o){var a,l;let{initPTS:c,lastEndTime:d}=this;const u={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};isFiniteNumber(d)||(d=this.lastEndTime=r||0);const h=s.samples;if(!(h!=null&&h.length))return u;const f={initPTS:void 0,timescale:1};let g=this.initData;if((a=g)!=null&&a.length||(this.generateInitSegment(h),g=this.initData),!((l=g)!=null&&l.length))return logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=getDuration(h,g),m=getStartDTS(g,h),v=m===null?r:m;(isInvalidInitPts(c,v,r,p)||f.timescale!==c.timescale&&o)&&(f.initPTS=v-r,c&&c.timescale===1&&logger.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const S=e?v-c.baseTime/c.timescale:d,y=S+p;offsetStartDTS(g,h,c.baseTime/c.timescale),p>0?this.lastEndTime=y:(logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const C=!!g.audio,E=!!g.video;let L="";C&&(L+="audio"),E&&(L+="video");const T={data1:h,startPTS:S,startDTS:S,endPTS:y,endDTS:y,type:L,hasAudio:C,hasVideo:E,nb:1,dropped:0};return u.audio=T.type==="audio"?T:void 0,u.video=T.type!=="audio"?T:void 0,u.initSegment=f,u.id3=flushTextTrackMetadataCueSamples(n,r,c,c),i.samples.length&&(u.text=flushTextTrackUserdataCueSamples(i,r,c)),u}}function isInvalidInitPts(t,e,s,n){if(t===null)return!0;const i=Math.max(n,1),r=e-t.baseTime/t.timescale;return Math.abs(r-s)>i}function getParsedTrackCodec(t,e){const s=t==null?void 0:t.codec;return s&&s.length>4?s:s==="hvc1"||s==="hev1"?"hvc1.1.6.L120.90":s==="av01"?"av01.0.04M.08":s==="avc1"||e===ElementaryStreamTypes.VIDEO?"avc1.42e01e":"mp4a.40.5"}let now;try{now=self.performance.now.bind(self.performance)}catch{logger.debug("Unable to use Performance API on this environment"),now=typeof self<"u"&&self.Date.now}const muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:TSDemuxer,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:MP3Demuxer,remux:MP4Remuxer}];class Transmuxer{constructor(e,s,n,i,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=s,this.config=n,this.vendor=i,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,s,n,i){const r=n.transmuxing;r.executeStart=now();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:d,trackSwitch:u,accurateTimeOffset:h,timeOffset:f,initSegmentChange:g}=i||a,{audioCodec:p,videoCodec:m,defaultInitPts:v,duration:S,initSegmentData:y}=l,C=getEncryptionType(o,s);if(C&&C.method==="AES-128"){const b=this.getDecrypter();if(b.isSync()){let _=b.softwareDecrypt(o,C.key.buffer,C.iv.buffer);if(n.part>-1&&(_=b.flush()),!_)return r.executeEnd=now(),emptyResult(n);o=new Uint8Array(_)}else return this.decryptionPromise=b.webCryptoDecrypt(o,C.key.buffer,C.iv.buffer).then(_=>{const I=this.push(_,null,n);return this.decryptionPromise=null,I}),this.decryptionPromise}const E=this.needsProbing(d,u);if(E){const b=this.configureTransmuxer(o);if(b)return logger.warn(`[transmuxer] ${b.message}`),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),r.executeEnd=now(),emptyResult(n)}(d||u||g||E)&&this.resetInitSegment(y,p,m,S,s),(d||g||E)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const L=this.transmux(o,C,f,h,n),T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,r.executeEnd=now(),L}flush(e){const s=e.transmuxing;s.executeStart=now();const{decrypter:n,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const o=[],{timeOffset:a}=i;if(n){const u=n.flush();u&&o.push(this.push(u,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return s.executeEnd=now(),[emptyResult(e)];const d=l.flush(a);return isPromise(d)?d.then(u=>(this.flushRemux(o,u,e),o)):(this.flushRemux(o,d,e),o)}flushRemux(e,s,n){const{audioTrack:i,videoTrack:r,id3Track:o,textTrack:a}=s,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;logger.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?" p: "+n.part:""} of level ${n.level}`);const d=this.remuxer.remux(i,r,o,a,c,l,!0,this.id);e.push({remuxResult:d,chunkMeta:n}),n.transmuxing.executeEnd=now()}resetInitialTimestamp(e){const{demuxer:s,remuxer:n}=this;!s||!n||(s.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:s}=this;!e||!s||(e.resetContiguity(),s.resetNextTimestamp())}resetInitSegment(e,s,n,i,r){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,s,n,i),a.resetInitSegment(e,s,n,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,s,n,i,r){let o;return s&&s.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,s,n,i,r):o=this.transmuxUnencrypted(e,n,i,r),o}transmuxUnencrypted(e,s,n,i){const{audioTrack:r,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,s,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,a,l,s,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,s,n,i,r){return this.demuxer.demuxSampleAes(e,s,n).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,n,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:s,observer:n,typeSupported:i,vendor:r}=this;let o;for(let u=0,h=muxConfig.length;u<h;u++)if(muxConfig[u].demux.probe(e)){o=muxConfig[u];break}if(!o)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,c=o.remux,d=o.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(n,s,i,r)),(!a||!(a instanceof d))&&(this.demuxer=new d(n,s,i),this.probe=d.probe)}needsProbing(e,s){return!this.demuxer||!this.remuxer||e||s}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Decrypter(this.config)),e}}function getEncryptionType(t,e){let s=null;return t.byteLength>0&&e!=null&&e.key!=null&&e.iv!==null&&e.method!=null&&(s=e),s}const emptyResult=t=>({remuxResult:{},chunkMeta:t});function isPromise(t){return"then"in t&&t.then instanceof Function}class TransmuxConfig{constructor(e,s,n,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=s,this.initSegmentData=n,this.duration=i,this.defaultInitPts=r||null}}class TransmuxState{constructor(e,s,n,i,r,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=s,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=o}}var eventemitter3={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,s="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(s=!1));function i(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function r(l,c,d,u,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new i(d,u||l,h),g=s?s+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],d,u;if(this._eventsCount===0)return c;for(u in d=this._events)e.call(d,u)&&c.push(s?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},a.prototype.listeners=function(c){var d=s?s+c:c,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var h=0,f=u.length,g=new Array(f);h<f;h++)g[h]=u[h].fn;return g},a.prototype.listenerCount=function(c){var d=s?s+c:c,u=this._events[d];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,d,u,h,f,g){var p=s?s+c:c;if(!this._events[p])return!1;var m=this._events[p],v=arguments.length,S,y;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),v){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,d),!0;case 3:return m.fn.call(m.context,d,u),!0;case 4:return m.fn.call(m.context,d,u,h),!0;case 5:return m.fn.call(m.context,d,u,h,f),!0;case 6:return m.fn.call(m.context,d,u,h,f,g),!0}for(y=1,S=new Array(v-1);y<v;y++)S[y-1]=arguments[y];m.fn.apply(m.context,S)}else{var C=m.length,E;for(y=0;y<C;y++)switch(m[y].once&&this.removeListener(c,m[y].fn,void 0,!0),v){case 1:m[y].fn.call(m[y].context);break;case 2:m[y].fn.call(m[y].context,d);break;case 3:m[y].fn.call(m[y].context,d,u);break;case 4:m[y].fn.call(m[y].context,d,u,h);break;default:if(!S)for(E=1,S=new Array(v-1);E<v;E++)S[E-1]=arguments[E];m[y].fn.apply(m[y].context,S)}}return!0},a.prototype.on=function(c,d,u){return r(this,c,d,u,!1)},a.prototype.once=function(c,d,u){return r(this,c,d,u,!0)},a.prototype.removeListener=function(c,d,u,h){var f=s?s+c:c;if(!this._events[f])return this;if(!d)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!h||g.once)&&(!u||g.context===u)&&o(this,f);else{for(var p=0,m=[],v=g.length;p<v;p++)(g[p].fn!==d||h&&!g[p].once||u&&g[p].context!==u)&&m.push(g[p]);m.length?this._events[f]=m.length===1?m[0]:m:o(this,f)}return this},a.prototype.removeAllListeners=function(c){var d;return c?(d=s?s+c:c,this._events[d]&&o(this,d)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=s,a.EventEmitter=a,t.exports=a})(eventemitter3);var eventemitter3Exports=eventemitter3.exports,EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);const MediaSource$1=getMediaSource()||{isTypeSupported:()=>!1};class TransmuxerInterface{constructor(e,s,n,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=s,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;const o=(c,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,c===Events.ERROR&&(this.error=d.error),this.hls.trigger(c,d)};this.observer=new EventEmitter,this.observer.on(Events.FRAG_DECRYPTED,o),this.observer.on(Events.ERROR,o);const a={mp4:MediaSource$1.isTypeSupported("video/mp4"),mpeg:MediaSource$1.isTypeSupported("audio/mpeg"),mp3:MediaSource$1.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||hasUMDWorker())){try{r.workerPath?(logger.log(`loading Web Worker ${r.workerPath} for "${s}"`),this.workerContext=loadWorker(r.workerPath)):(logger.log(`injecting Web Worker for "${s}"`),this.workerContext=injectWorker()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:d}=this.workerContext;d.addEventListener("message",this.onwmsg),d.onerror=u=>{const h=new Error(`${u.message}  (${u.filename}:${u.lineno})`);r.enableWorker=!1,logger.warn(`Error in "${s}" Web Worker, fallback to inline`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:h})}
12,d.postMessage({cmd:"init",typeSupported:a,vendor:l,id:s,config:JSON.stringify(r)})}catch(d){logger.warn(`Error setting up "${s}" Web Worker, fallback to inline`,d),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,a,r,l,s)}return}this.transmuxer=new Transmuxer(this.observer,a,r,l,s)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:s}=this.workerContext;s&&self.URL.revokeObjectURL(s),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const s=this.transmuxer;s&&(s.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,s,n,i,r,o,a,l,c,d){var u,h;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=o?o.start:r.start,p=r.decryptdata,m=this.frag,v=!(m&&r.cc===m.cc),S=!(m&&c.level===m.level),y=m?c.sn-m.sn:-1,C=this.part?c.part-this.part.index:-1,E=y===0&&c.id>1&&c.id===(m==null?void 0:m.stats.chunkCount),L=!S&&(y===1||y===0&&(C===1||E&&C<=0)),T=self.performance.now();(S||y||r.stats.parsing.start===0)&&(r.stats.parsing.start=T),o&&(C||!L)&&(o.stats.parsing.start=T);const b=!(m&&((u=r.initSegment)==null?void 0:u.url)===((h=m.initSegment)==null?void 0:h.url)),_=new TransmuxState(v,L,l,S,g,b);if(!L||v||b){logger.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
13        discontinuity: ${v}
14        trackSwitch: ${S}
15        contiguous: ${L}
16        accurateTimeOffset: ${l}
17        timeOffset: ${g}
18        initSegmentChange: ${b}`);const I=new TransmuxConfig(n,i,s,a,d);this.configureTransmuxer(I)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:c,state:_},e instanceof ArrayBuffer?[e]:[]);else if(f){const I=f.push(e,p,c,_);isPromise(I)?(f.async=!0,I.then(P=>{this.handleTransmuxComplete(P)}).catch(P=>{this.transmuxerError(P,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(s){let n=s.flush(e);isPromise(n)||s.async?(isPromise(n)||(n=Promise.resolve(n)),n.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}}transmuxerError(e,s,n){this.hls&&(this.error=e,this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:s,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,s){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(s)}onWorkerMessage(e){const s=e.data,n=this.hls;switch(s.event){case"init":{var i;const r=(i=this.workerContext)==null?void 0:i.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(s.data);break}case"flush":{this.onFlush(s.data);break}case"workerLog":logger[s.data.logType]&&logger[s.data.logType](s.data.message);break;default:{s.data=s.data||{},s.data.frag=this.frag,s.data.id=this.id,n.trigger(s.event,s.data);break}}}configureTransmuxer(e){const{transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const STALL_MINIMUM_DURATION_MS=250,MAX_START_GAP_JUMP=2,SKIP_BUFFER_HOLE_STEP_SECONDS=.1,SKIP_BUFFER_RANGE_START=.05;class GapController{constructor(e,s,n,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=s,this.fragmentTracker=n,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,s){const{config:n,media:i,stalled:r}=this;if(i===null)return;const{currentTime:o,seeking:a}=i,l=this.seeking&&!a,c=!this.seeking&&a;if(this.seeking=a,o!==e){if(this.moved=!0,r!==null){if(this.stallReported){const v=self.performance.now()-r;logger.warn(`playback not stuck anymore @${o}, after ${Math.round(v)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(c||l){this.stalled=null;return}if(i.paused&&!a||i.ended||i.playbackRate===0||!BufferHelper.getBuffered(i).length)return;const d=BufferHelper.bufferInfo(i,o,0),u=d.len>0,h=d.nextStart||0;if(!u&&!h)return;if(a){const v=d.len>MAX_START_GAP_JUMP,S=!h||s&&s.start<=o||h-o>MAX_START_GAP_JUMP&&!this.fragmentTracker.getPartialFragment(o);if(v||S)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;
18const v=Math.max(h,d.start||0)-o,S=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,C=(S==null||(f=S.details)==null?void 0:f.live)?S.details.targetduration*2:MAX_START_GAP_JUMP,E=this.fragmentTracker.getPartialFragment(o);if(v>0&&(v<=C||E)){this._trySkipBufferHole(E);return}}const g=self.performance.now();if(r===null){this.stalled=g;return}const p=g-r;if(!a&&p>=STALL_MINIMUM_DURATION_MS&&(this._reportStall(d),!this.media))return;const m=BufferHelper.bufferInfo(i,o,n.maxBufferHole);this._tryFixBufferStall(m,p)}_tryFixBufferStall(e,s){const{config:n,fragmentTracker:i,media:r}=this;if(r===null)return;const o=r.currentTime,a=i.getPartialFragment(o);a&&(this._trySkipBufferHole(a)||!this.media)||(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-o<n.maxBufferHole)&&s>n.highBufferWatchdogPeriod*1e3&&(logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:s,media:n,stallReported:i}=this;if(!i&&n){this.stallReported=!0;const r=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);logger.warn(r.message),s.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:s,hls:n,media:i}=this;if(i===null)return 0;const r=i.currentTime,o=BufferHelper.bufferInfo(i,r,0),a=r<o.start?o.start:o.nextStart;if(a){const l=o.len<=s.maxBufferHole,c=o.len>0&&o.len<1&&i.readyState<3,d=a-r;if(d>0&&(l||c)){if(d>s.maxBufferHole){const{fragmentTracker:h}=this;let f=!1;if(r===0){const g=h.getAppendedFrag(0,PlaylistLevelType.MAIN);g&&a<g.end&&(f=!0)}if(!f){const g=e||h.getAppendedFrag(r,PlaylistLevelType.MAIN);if(g){let p=!1,m=g.end;for(;m<a;){const v=h.getPartialFragment(m);if(v)m+=v.duration;else{p=!0;break}}if(p)return 0}}}const u=Math.max(a+SKIP_BUFFER_RANGE_START,r+SKIP_BUFFER_HOLE_STEP_SECONDS);if(logger.warn(`skipping hole, adjusting currentTime from ${r} to ${u}`),this.moved=!0,this.stalled=null,i.currentTime=u,e&&!e.gap){const h=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${u}`);n.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:e})}return u}}return 0}_tryNudgeBuffer(){const{config:e,hls:s,media:n,nudgeRetry:i}=this;if(n===null)return;const r=n.currentTime;if(this.nudgeRetry++,i<e.nudgeMaxRetry){const o=r+(i+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${r} to ${o}`);logger.warn(a.message),n.currentTime=o,s.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const o=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);logger.error(o.message),s.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}}const TICK_INTERVAL$2=100;class StreamController extends BaseStreamController{constructor(e,s,n){super(e,s,n,"[stream-controller]",PlaylistLevelType.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Events.ERROR,this.onError,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;
18e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Events.ERROR,this.onError,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:s,hls:n}=this;if(this.stopLoad(),this.setInterval(TICK_INTERVAL$2),this.level=-1,!this.startFragRequested){let i=n.startLevel;i===-1&&(n.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=n.nextAutoLevel),this.level=n.nextLoadLevel=i,this.loadedmetadata=!1}s>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=State.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case State.WAITING_LEVEL:{var e;const{levels:n,level:i}=this,r=n==null||(e=n[i])==null?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=State.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:{var s;const n=self.performance.now(),i=this.retryDate;(!i||n>=i||(s=this.media)!=null&&s.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=State.IDLE)}break}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:s,levels:n,media:i}
18=this,{config:r,nextLoadLevel:o}=e;if(s===null||!i&&(this.startFragRequested||!r.startFragPrefetch)||this.altAudio&&this.audioOnly||!(n!=null&&n[o]))return;const a=n[o],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(Events.BUFFER_EOS,m),this.state=State.ENDED;return}e.loadLevel!==o&&e.manualLevel===-1&&this.log(`Adapting to level ${o} from level ${this.level}`),this.level=e.nextLoadLevel=o;const d=a.details;if(!d||this.state===State.WAITING_LEVEL||d.live&&this.levelLastLoaded!==o){this.level=o,this.state=State.WAITING_LEVEL;return}const u=l.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&g.sn!=="initSegment"&&this.fragmentTracker.getState(g)!==FragmentState.OK){var p;const v=((p=this.backtrackFragment)!=null?p:g).sn-d.startSN,S=d.fragments[v-1];S&&g.cc===S.cc&&(g=S,this.fragmentTracker.removeFragment(S))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const v=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,S=(v===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;S&&this.afterBufferFlushed(S,v,PlaylistLevelType.MAIN)}g=this.getNextFragmentLoopLoading(g,d,l,PlaylistLevelType.MAIN,h)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,a,f))}loadFragment(e,s,n){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===FragmentState.NOT_LOADED||i===FragmentState.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,s):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,s)):(this.startFragRequested=!0,super.loadFragment(e,s,n)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:s}=this;if(s!=null&&s.readyState){let n;const i=this.getAppendedFrag(s.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<r.targetduration*2)return}if(!s.paused&&e){const a=this.hls.nextLoadLevel,l=e[a],c=this.fragLastKbps;c&&this.fragCurrent?n=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:n=0}else n=0;const o=this.getBufferedFrag(s.currentTime+n);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const l=a.maxStartPTS?a.maxStartPTS:a.start,c=a.duration,d=Math.max(o.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*.5),c*.75));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,s){super.flushMainBuffer(e,s,this.altAudio?"video":null)}onMediaAttached(e,s){super.onMediaAttached(e,s);const n=s.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),n.addEventListener("playing",this.onvplaying),n.addEventListener("seeked",this.onvseeked),this.gapController=new GapController(this.config,n,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,s=e?e.currentTime:null;isFiniteNumber(s)&&this.log(`Media seeked to ${s.toFixed(3)}`);const n=this.getMainFwdBufferInfo();if(n===null||n.len===0){this.warn(`Main forward buffer length on "seeked" event ${n?n.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,s){let n=!1,i=!1,r;
18s.levels.forEach(o=>{r=o.audioCodec,r&&(r.indexOf("mp4a.40.2")!==-1&&(n=!0),r.indexOf("mp4a.40.5")!==-1&&(i=!0))}),this.audioCodecSwitch=n&&i&&!changeTypeSupported(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=s.levels,this.startFragRequested=!1}onLevelLoading(e,s){const{levels:n}=this;if(!n||this.state!==State.IDLE)return;const i=n[s.level];(!i.details||i.details.live&&this.levelLastLoaded!==s.level||this.waitForCdnTuneIn(i.details))&&(this.state=State.WAITING_LEVEL)}onLevelLoaded(e,s){var n;const{levels:i}=this,r=s.level,o=s.details,a=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${a}`);const l=i[r],c=this.fragCurrent;c&&(this.state===State.FRAG_LOADING||this.state===State.FRAG_LOADING_WAITING_RETRY)&&(c.level!==s.level||c.urlId!==l.urlId)&&c.loader&&this.abortCurrentFrag();let d=0;if(o.live||(n=l.details)!=null&&n.live){if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details)}if(l.details=o,this.levelLastLoaded=r,this.hls.trigger(Events.LEVEL_UPDATED,{details:o,level:r}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=State.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,d),this.tick()}_handleFragmentLoadProgress(e){var s;const{frag:n,part:i,payload:r}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const a=o[n.level],l=a.details;if(!l){this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),this.fragmentTracker.removeFragment(n);return}const c=a.videoCodec,d=l.PTSKnown||!l.live,u=(s=n.initSegment)==null?void 0:s.data,h=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,m=new ChunkMetadata(n.level,n.sn,n.stats.chunkCount,r.byteLength,g,p),v=this.initPTS[n.cc];f.push(r,u,h,c,n,i,l.totalduration,d,m,v)}onAudioTrackSwitching(e,s){const n=this.altAudio;if(!!!s.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;n&&(r.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(Events.AUDIO_TRACK_SWITCHED,s)}}onAudioTrackSwitched(e,s){const n=s.id,i=!!this.hls.audioTracks[n].url;if(i){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i,this.tick()}onBufferCreated(e,s){const n=s.tracks;let i,r,o=!1;for(const a in n){const l=n[a];if(l.id==="main"){if(r=a,i=l,a==="video"){const c=n[a];c&&(this.videoBuffer=c.buffer)}}else o=!0}o&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,s){const{frag:n,part:i}=s;if(n&&n.type!==PlaylistLevelType.MAIN)return;if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===State.PARSED&&(this.state=State.IDLE);return}const r=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),n.sn!=="initSegment"&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}onError(e,s){var n;if(s.fatal){this.state=State.ERROR;return}switch(s.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,s);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:!s.levelRetry&&this.state===State.WAITING_LEVEL&&((n=s.context)==null?void 0:n.type)===PlaylistContextType.LEVEL&&(this.state=State.IDLE);break;case ErrorDetails.BUFFER_FULL_ERROR:if(!s.parent||s.parent!=="main")return;this.reduceLengthAndFlushBuffer(s)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(s);break}}
18checkBuffer(){const{media:e,gapController:s}=this;if(!(!e||!s||!e.readyState)){if(this.loadedmetadata||!BufferHelper.getBuffered(e).length){const n=this.state!==State.IDLE?this.fragCurrent:null;s.poll(this.lastCurrentTime,n)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=State.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:s}){if(s!==ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){const n=(s===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(n,s,PlaylistLevelType.MAIN)}}onLevelsUpdated(e,s){this.levels=s.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const s=e.currentTime;let n=this.startPosition;if(n>=0&&s<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${s}`);return}const i=BufferHelper.getBuffered(e),o=(i.length?i.start(0):0)-n;o>0&&(o<this.config.maxBufferHole||o<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${o} to match buffer start`),n+=o,this.startPosition=n),this.log(`seek to target start position ${n} from current time ${s}`),e.currentTime=n}}_getAudioCodec(e){let s=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&s&&(this.log("Swapping audio codec"),s.indexOf("mp4a.40.5")!==-1?s="mp4a.40.2":s="mp4a.40.5"),s}_loadBitrateTestFrag(e,s){e.bitrateTest=!0,this._doFragLoad(e,s).then(n=>{const{hls:i}=this;if(!n||this.fragContextChanged(e))return;s.fragmentError=0,this.state=State.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(Events.FRAG_LOADED,n),e.bitrateTest=!1})}_handleTransmuxComplete(e){var s;const n="main",{hls:i}=this,{remuxResult:r,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:d}=a,{video:u,text:h,id3:f,initSegment:g}=r,{details:p}=d,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=State.PARSING,g){if(g!=null&&g.tracks){const y=l.initSegment||l;this._bufferInitSegment(d,g.tracks,y,o),i.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:n,tracks:g.tracks})}const v=g.initPTS,S=g.timescale;isFiniteNumber(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:S},i.trigger(Events.INIT_PTS_FOUND,{frag:l,id:n,initPTS:v,timescale:S}))}if(u&&p&&l.sn!=="initSegment"){const v=p.fragments[l.sn-1-p.startSN],S=l.sn===p.startSN,y=!v||l.cc>v.cc;if(r.independent!==!1){const{startPTS:C,endPTS:E,startDTS:L,endDTS:T}=u;if(c)c.elementaryStreams[u.type]={startPTS:C,endPTS:E,startDTS:L,endDTS:T};else if(u.firstKeyFrame&&u.independent&&o.id===1&&!y&&(this.couldBacktrack=!0),u.dropped&&u.independent){const b=this.getMainFwdBufferInfo(),_=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:C;if(!S&&_<I-this.config.maxBufferHole&&!y){this.backtrack(l);return}else y&&(l.gap=!0);l.setElementaryStreamInfo(u.type,l.start,E,l.start,T,!0)}l.setElementaryStreamInfo(u.type,C,E,L,T),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,o,S||y)}else if(S||y)l.gap=!0;else{this.backtrack(l);return}}if(m){const{startPTS:v,endPTS:S,startDTS:y,endDTS:C}=m;c&&(c.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:v,endPTS:S,startDTS:y,endDTS:C}),l.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,v,S,y,C),this.bufferFragmentData(m,l,c,o)}if(p&&f!=null&&(s=f.samples)!=null&&s.length){const v={id:n,frag:l,details:p,samples:f.samples};i.trigger(Events.FRAG_PARSING_METADATA,v)}if(p&&h){const v={id:n,frag:l,details:p,samples:h.samples};i.trigger(Events.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,s,n,i){if(this.state!==State.PARSING)return;this.audioOnly=!!s.audio&&!s.video,this.altAudio&&!this.audioOnly&&delete s.audio;const{audio:r,video:o,audiovideo:a}=s;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),r.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.codec}]`)}o&&(o.levelCodec=e.videoCodec,o.id="main",this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${o.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(Events.BUFFER_CODECS,s),Object.keys(s).forEac
18h(l=>{const d=s[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(Events.BUFFER_APPENDING,{type:l,data:d,frag:n,part:null,chunkMeta:i,parent:n.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,PlaylistLevelType.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=State.IDLE}checkFragmentChanged(){const e=this.media;let s=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(BufferHelper.isBuffered(e,n)?s=this.getAppendedFrag(n):BufferHelper.isBuffered(e,n+.1)&&(s=this.getAppendedFrag(n+.1)),s){this.backtrackFragment=null;const i=this.fragPlaying,r=s.level;(!i||s.sn!==i.sn||i.level!==r||s.urlId!==i.urlId)&&(this.fragPlaying=s,this.hls.trigger(Events.FRAG_CHANGED,{frag:s}),(!i||i.level!==r)&&this.hls.trigger(Events.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const s=e.currentTime,n=this.currentFrag;if(n&&isFiniteNumber(s)&&isFiniteNumber(n.programDateTime)){const i=n.programDateTime+(s-n.start)*1e3;return new Date(i)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class EWMA{constructor(e,s=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=s,this.totalWeight_=n}sample(e,s){const n=Math.pow(this.alpha_,e);this.estimate_=s*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class EwmaBandWidthEstimator{constructor(e,s,n,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_
18=new EWMA(e),this.fast_=new EWMA(s),this.defaultTTFB_=i,this.ttfb_=new EWMA(e)}update(e,s){const{slow_:n,fast_:i,ttfb_:r}=this;n.halfLife!==e&&(this.slow_=new EWMA(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==s&&(this.fast_=new EWMA(s,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new EWMA(e,r.getEstimate(),r.getTotalWeight()))}sample(e,s){e=Math.max(e,this.minDelayMs_);const n=8*s,i=e/1e3,r=n/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const s=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(s,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class AbrController{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const s=e.config;this.bwEstimator=new EwmaBandWidthEstimator(s.abrEwmaSlowVoD,s.abrEwmaFastVoD,s.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,s){var n;const i=s.frag;this.ignoreFragment(i)||(this.fragCurrent=i,this.partCurrent=(n=s.part)!=null?n:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,s){this.clearTimer()}getTimeToLoadFrag(e,s,n,i){const r=e+n/s,o=i?this.lastLevelLoadSec:0;return r+o}onLevelLoaded(e,s){const n=this.hls.config,{total:i,bwEstimate:r}=s.stats;isFiniteNumber(i)&&isFiniteNumber(r)&&(this.lastLevelLoadSec=8*i/r),s.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:s,hls:n}=this,{autoLevelEnabled:i,media:r}=n;if(!e||!r)return;const o=performance.now(),a=s?s.stats:e.stats,l=s?s.duration:e.duration,c=o-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i||r.paused||!r.playbackRate||!r.readyState)return;const d=n.mainForwardBufferInfo;if(d===null)return;const u=this.bwEstimator.getEstimateTTFB(),h=Math.abs(r.playbackRate);if(c<=Math.max(u,1e3*(l/(h*2))))return;const f=d.len/h;if(f>=2*l/h)return;const g=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&g>-1,m=this.bwEstimator.getEstimate(),{levels:v,minAutoLevel:S}=n,y=v[e.level],C=a.total||Math.max(a.loaded,Math.round(l*y.maxBitrate/8));let E=c-g;E<1&&p&&(E=Math.min(c,a.loaded*8/m));const L=p?a.loaded*1e3/E:0,T=L?(C-a.loaded)/L:C*8/m+u/1e3;if(T<=f)return;const b=L?L*8:m;let _=Number.POSITIVE_INFINITY,I;for(I=e.level-1;I>S;I--){const P=v[I].maxBitrate;if(_=this.getTimeToLoadFrag(u/1e3,b,l*P,!v[I].details),_<f)break}_>=T||_>l*10||(n.nextLoadLevel=I,p?this.bwEstimator.sample(c-Math.min(u,g),a.loaded):this.bwEstimator.sampleTTFB(c),this.clearTimer(),logger.warn(`[abr] Fragment ${e.sn}${s?" part "+s.index:""} of level ${e.level} is loading too slowly;
19      Time to underbuffer: ${f.toFixed(3)} s
20      Estimated load time for current fragment: ${T.toFixed(3)} s
21      Estimated load time for down switch fragment: ${_.toFixed(3)} s
22      TTFB estimate: ${g}
23      Current BW estimate: ${isFiniteNumber(m)?(m/1024).toFixed(3):"Unknown"} Kb/s
24      New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
25      Aborting and switching to level ${I}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),n.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:s,stats:a}))}onFragLoaded(e,{frag:s,part:n}){const i=n?n.stats:s.stats;if(s.type===PlaylistLevelType.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(s)){if
25(this.clearTimer(),this.lastLoadedFragLevel=s.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const r=n?n.duration:s.duration,o=this.hls.levels[s.level],a=(o.loaded?o.loaded.bytes:0)+i.loaded,l=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(s.bitrateTest){const r={stats:i,frag:s,part:n,id:s.type};this.onFragBuffered(Events.FRAG_BUFFERED,r),s.bitrateTest=!1}}}onFragBuffered(e,s){const{frag:n,part:i}=s,r=i!=null&&i.stats.loaded?i.stats:n.stats;if(r.aborted||this.ignoreFragment(n))return;const o=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.bwEstimator.getEstimate(),n.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==PlaylistLevelType.MAIN||e.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,s=this.bwEstimator;if(e!==-1&&!s.canEstimate())return e;let n=this.getNextABRAutoLevel();if(e!==-1){const i=this.hls.levels;if(i.length>Math.max(e,n)&&i[e].loadError<=i[n].loadError)return e}return e!==-1&&(n=Math.min(e,n)),n}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:s,hls:n}=this,{maxAutoLevel:i,config:r,minAutoLevel:o,media:a}=n,l=s?s.duration:e?e.duration:0,c=a&&a.playbackRate!==0?Math.abs(a.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():r.abrEwmaDefaultEstimate,u=n.mainForwardBufferInfo,h=(u?u.len:0)/c;let f=this.findBestLevel(d,o,i,h,r.abrBandWidthFactor,r.abrBandWidthUpFactor);if(f>=0)return f;logger.trace(`[abr] ${h?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=l?Math.min(l,r.maxStarvationDelay):r.maxStarvationDelay,p=r.abrBandWidthFactor,m=r.abrBandWidthUpFactor;if(!h){const v=this.bitrateTestDelay;v&&(g=(l?Math.min(l,r.maxLoadingDelay):r.maxLoadingDelay)-v,logger.trace(`[abr] bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),p=m=1)}return f=this.findBestLevel(d,o,i,h+g,p,m),Math.max(f,0)}findBestLevel(e,s,n,i,r,o){var a;const{fragCurrent:l,partCurrent:c,lastLoadedFragLevel:d}=this,{levels:u}=this.hls,h=u[d],f=!!(h!=null&&(a=h.details)!=null&&a.live),g=h==null?void 0:h.codecSet,p=c?c.duration:l?l.duration:0,m=this.bwEstimator.getEstimateTTFB()/1e3;let v=s,S=-1;for(let y=n;y>=s;y--){const C=u[y];if(!C||g&&C.codecSet!==g){C&&(v=Math.min(y,v),S=Math.max(y,S));continue}S!==-1&&logger.trace(`[abr] Skipped level(s) ${v}-${S} with CODECS:"${u[S].attrs.CODECS}"; not compatible with "${h.attrs.CODECS}"`);const E=C.details,L=(c?E==null?void 0:E.partTarget:E==null?void 0:E.averagetargetduration)||p;let T;y<=d?T=r*e:T=o*e;const b=u[y].maxBitrate,_=this.getTimeToLoadFrag(m,T,b*L,E===void 0);if(logger.trace(`[abr] level:${y} adjustedbw-bitrate:${Math.round(T-b)} avgDuration:${L.toFixed(1)} maxFetchDuration:${i.toFixed(1)} fetchDuration:${_.toFixed(1)}`),T>b&&(_===0||!isFiniteNumber(_)||f&&!this.bitrateTestDelay||_<i))return y}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:s}=this;let n;if(e.length)e.length===1?n=e[0]:n=concatUint8Arrays(e,s);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function concatUint8Arrays(t,e){const s=new Uint8Array(e);let n=0;for(let i=0;i<t.length;i++){const r=t[i];s.set(r,n),n+=r.length}return s}const TICK_INTERVAL$1=100;class AudioStreamController extends BaseStreamController{constructor(e,s,n){super(e,s,n,"[audio-stream-controller]",PlaylistLevelType.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;
vendor: 5,477 bytes, line 25
25e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.ERROR,this.onError,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.ERROR,this.onError,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:s,id:n,initPTS:i,timescale:r}){if(n==="main"){const o=s.cc;this.initPTS[s.cc]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${o} found from main: ${i}`),this.videoTrackCC=o,this.state===State.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=State.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(TICK_INTERVAL$1),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=State.IDLE):(this.loadedmetadata=!1,this.state=State.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case State.IDLE:this.doTickIdle();break;case State.WAITING_TRACK:{var e;const{levels:n,trackId:i}=this,r=n==null||(e=n[i])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=State.WAITING_INIT_PTS}break}case State.FRAG_LOADING_WAITING_RETRY:{var s;const n=performance.now(),i=this.retryDate;(!i||n>=i||(s=this.media)!=null&&s.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=State.IDLE);break}case State.WAITING_INIT_PTS:{const n=this.waitingData;if(n){const{frag:i,part:r,cache:o,complete:a}=n;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=State.FRAG_LOADING;const l=o.flush(),c={frag:i,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),a&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=BufferHelper.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);fragmentWithinToleranceTest(c.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=State.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=State.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:s,media:n,trackId:i}=this,r=e.config;if(!(s!=null&&s[i])||!n&&(this.startFragRequested||!r.startFragPrefetch))return;const o=s[i],a=o.details;if(!a||a.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(a)){this.state=State.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ElementaryStreamTypes.AUDIO,PlaylistLevelType.AUDIO));const c=this.getFwdBufferInfo(l,PlaylistLevelType.AUDIO);if(c===null)return;const{bufferedTrack:d,switchingTrack:u}=this;if(!u&&this._streamEnded(c,a)){e.trigger(Events.BUFFER_EOS,{type:"audio"}),this.state=State.ENDED;return}const h=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,PlaylistLevelType.MAIN),f=c.len,g=this.getMaxBufferLength(h==null?void 0:h.len);if(f>=g&&!u)return;const m=a.fragments[0].start;let v=c.end;if(u&&n){const E=this.getLoadPosition();d&&u.attrs!==d.attrs&&(v=E),a.PTSKnown&&E<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=m+.05)}let S=this.getNextFragment(v,a),y=!1;if(S&&this.isLoopLoading(S,v)&&(y=!!S.gap,S=this.getNextFragmentLoopLoading(S,a,c,PlaylistLevelType.MAIN,g)),!S){this.bufferFlushed=!0;return}const C=h&&S.start>h.end+a.targetduration;if(C||!(h!=null&&h.len)&&c.len){const E=this.getAppendedFrag(S.start,PlaylistLevelType.MAIN);if(E===null||(y||(y=!!E.gap||!!C&&h.len===0),C&&!y||y&&c.nextStart&&c.nextStart<E.end))return}this.loadFragment(S,o,v)}getMaxBufferLength(e){const s=super.getMaxBufferLength();
25return e?Math.min(Math.max(s,e),this.config.maxMaxBufferLength):s}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:s}){this.resetTransmuxer(),this.levels=s.map(n=>new Level(n))}onAudioTrackSwitching(e,s){const n=!!s.url;this.trackId=s.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),n?this.setInterval(TICK_INTERVAL$1):this.resetTransmuxer(),n?(this.switchingTrack=s,this.state=State.IDLE):(this.switchingTrack=null,this.bufferedTrack=s,this.state=State.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,s){this.mainDetails=s.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(Events.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,s){var n;if(this.mainDetails==null){this.cachedTrackLoadedData=s;return}const{levels:i}=this,{details:r,id:o}=s;if(!i){this.warn(`Audio tracks were reset while loading level ${o}`);return}this.log(`Track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const a=i[o];let l=0;if(r.live||(n=a.details)!=null&&n.live){const c=this.mainDetails;if(r.fragments[0]||(r.deltaUpdateFailed=!0),r.deltaUpdateFailed||!c)return;!a.details&&r.hasProgramDateTime&&c.hasProgramDateTime?(alignMediaPlaylistByPDT(r,c),l=r.fragments[0].start):l=this.alignPlaylists(r,a.details)}a.details=r,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(a.details,l),this.state===State.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=State.IDLE),this.tick()}_handleFragmentLoadProgress(e){var s;const{frag:n,part:i,payload:r}
vendor: 4,389 bytes, line 25
25=e,{config:o,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const c=l[a];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const d=c.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const u=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new TransmuxerInterface(this.hls,PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[n.cc],g=(s=n.initSegment)==null?void 0:s.data;if(f!==void 0){const m=i?i.index:-1,v=m!==-1,S=new ChunkMetadata(n.level,n.sn,n.stats.chunkCount,r.byteLength,m,v);h.push(r,g,u,"",n,i,d.totalduration,!1,S,f)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:p}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new ChunkCache,complete:!1};p.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=State.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,s){const n=s.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),s.tracks.video&&(this.videoBuffer=s.tracks.video.buffer||null)}onFragBuffered(e,s){const{frag:n,part:i}=s;if(n.type!==PlaylistLevelType.AUDIO){if(!this.loadedmetadata&&n.type===PlaylistLevelType.MAIN){const r=this.videoBuffer||this.media;r&&BufferHelper.getBuffered(r).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(n.sn!=="initSegment"){this.fragPrevious=n;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},r)))}this.fragBufferedComplete(n,i)}onError(e,s){var n;if(s.fatal){this.state=State.ERROR;return}switch(s.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO,s);break;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:!s.levelRetry&&this.state===State.WAITING_TRACK&&((n=s.context)==null?void 0:n.type)===PlaylistContextType.AUDIO_TRACK&&(this.state=State.IDLE);break;case ErrorDetails.BUFFER_FULL_ERROR:if(!s.parent||s.parent!=="audio")return;this.reduceLengthAndFlushBuffer(s)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(s);break}}onBufferFlushed(e,{type:s}){s===ElementaryStreamTypes.AUDIO&&(this.bufferFlushed=!0,this.state===State.ENDED&&(this.state=State.IDLE))}_handleTransmuxComplete(e){var s;const n="audio",{hls:i}=this,{remuxResult:r,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:d}=a,{details:u}=d,{audio:h,text:f,id3:g,initSegment:p}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=State.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const m=l.initSegment||l;this._bufferInitSegment(p.tracks,m,o),i.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:n,tracks:p.tracks})}if(h){const{startPTS:m,endPTS:v,startDTS:S,endDTS:y}=h;c&&(c.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:m,endPTS:v,startDTS:S,endDTS:y}),l.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,m,v,S,y),this.bufferFragmentData(h,l,c,o)}if(g!=null&&(s=g.samples)!=null&&s.length){const m=_extends({id:n,frag:l,details:u},g);i.trigger(Events.FRAG_PARSING_METADATA,m)}if(f){const m=_extends({id:n,frag:l,details:u},f);i.trigger(Events.FRAG_PARSING_USERDATA,m)}
25}_bufferInitSegment(e,s,n){if(this.state!==State.PARSING)return;e.video&&delete e.video;const i=e.audio;if(!i)return;i.levelCodec=i.codec,i.id="audio",this.log(`Init audio buffer, container:${i.container}, codecs[parsed]=[${i.codec}]`),this.hls.trigger(Events.BUFFER_CODECS,e);const r=i.initSegment;if(r!=null&&r.byteLength){const o={type:"audio",frag:s,part:null,chunkMeta:n,parent:s.type,data:r};this.hls.trigger(Events.BUFFER_APPENDING,o)}this.tick()}loadFragment(e,s,n){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===FragmentState.NOT_LOADED||i===FragmentState.PARTIAL){var r;e.sn==="initSegment"?this._loadInitSegment(e,s):(r=s.details)!=null&&r.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=State.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,s,n))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:s,media:n,bufferedTrack:i}=this,r=i==null?void 0:i.attrs,o=e.attrs;n&&r&&(r.CHANNELS!==o.CHANNELS||r.NAME!==o.NAME||r.LANGUAGE!==o.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,s.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e))}}class AudioTrackController extends BasePlaylistController{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,s){this.tracks=s.audioTracks||[]}onAudioTrackLoaded(e,s){const{id:n,groupId:i,details:r}=s,o=this.tracksInGroup[n];if(!o||o.groupId!==i){this.warn(`Track with id:${n} and group:${i} not found in active group ${o.groupId}`);return}const a=o.details;o.details=s.details,this.log(`audio-track ${n} "${o.name}" lang:${o.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),n===this.trackId&&this.playlistLoaded(n,s,a)}onLevelLoading(e,s){this.switchLevel(s.level)}onLevelSwitching(e,s){this.switchLevel(s.level)}switchLevel(e){const s=this.hls.levels[e];if(!(s!=null&&s.audioGroupIds))return;const n=s.audioGroupIds[s.urlId];if(this.groupId!==n){this.groupId=n||null;const i=this.tracks.filter(o=>!n||o.groupId===n);this.selectDefaultTrack&&!i.some(o=>o.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=i;const r={audioTracks:i};this.log(`Updating audio tracks, ${i.length} track(s) found in group:${n}`),this.hls.trigger(Events.AUDIO_TRACKS_UPDATED,r),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,s){s.fatal||!s.context||s.context.type===PlaylistContextType.AUDIO_TRACK&&s.context.id===this.trackId&&s.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(s))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const s=this.tracksInGroup;if(e<0||e>=s.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const n=this.currentTrack;s[this.trackId];const i=s[e],{groupId:r,name:o}=i;if(this.log(`Switching to audio-track ${e} "${o}" lang:${i.lang} group:${r}`),this.trackId=e,this.currentTrack=i,this.selectDefaultTrack=!1,this.hls.trigger(Events.AUDIO_TRACK_SWITCHING,_objectSpread2
25({},i)),i.details&&!i.details.live)return;const a=this.switchParams(i.url,n==null?void 0:n.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,s=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(s!==-1)this.setAudioTrack(s);else{const n=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(n.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:n})}}findTrackId(e){const s=this.tracksInGroup;for(let n=0;n<s.length;n++){const i=s[n];if((!this.selectDefaultTrack||i.default)&&(!e||e.attrs["STABLE-RENDITION-ID"]!==void 0&&e.attrs["STABLE-RENDITION-ID"]===i.attrs["STABLE-RENDITION-ID"]||e.name===i.name&&e.lang===i.lang))return i.id}return-1}loadPlaylist(e){super.loadPlaylist();const s=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(s)){const n=s.id,i=s.groupId;let r=s.url;if(e)try{r=e.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`loading audio-track playlist ${n} "${s.name}" lang:${s.lang} group:${i}`),this.clearTimer(),this.hls.trigger(Events.AUDIO_TRACK_LOADING,{url:r,id:n,groupId:i,deliveryDirectives:e||null})}}}function subtitleOptionsIdentical(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!subtitleAttributesIdentical(t[s].attrs,e[s].attrs))return!1;return!0}function subtitleAttributesIdentical(t,e){const s=t["STABLE-RENDITION-ID"];return s?s===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(n=>t[n]!==e[n])}const TICK_INTERVAL=500;class SubtitleStreamController extends BaseStreamController{constructor(e,s,n){super(e,s,n,"[subtitle-stream-controller]",PlaylistLevelType.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.ERROR,this.onError,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.ERROR,this.onError,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=State.IDLE,this.setInterval(TICK_INTERVAL),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,s){this.mainDetails=s.details}onSubtitleFragProcessed(e,s){const{frag:n,success:i}=s;if(this.fragPrevious=n,this.state=State.IDLE,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const a=n.start;for(let c=0;c<r.length;c++)if(a>=r[c].start&&a<=r[c].end){o=r[c];break}const l=n.start+n.duration;o?o.end=l:(o={start:a,end:l},r.push(o)),this.fragmentTracker.fragBuffered(n)}onBufferFlushing(e,s){const{startOffset:n,endOffset:i}=s;if(n===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;s.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=r){o.shift();continue}else if(o[a].start<r)o[a].start=r;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(n,r,PlaylistLevelType.SUBTITLE)}}onFragBuffered(e,s){if(!this.loadedmetadata&&s.frag.type===PlaylistLevelType.MAIN){var n;(n=this.media)!=null&&n.buffered.length&&(this.loadedmetadata=!0)}}onError(e,s){const n=s.frag;(n==null?void 0:n.type)===PlaylistLevelType.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==State.STOPPED&&(this.state=State.IDLE))}
25onSubtitleTracksUpdated(e,{subtitleTracks:s}){if(subtitleOptionsIdentical(this.levels,s)){this.levels=s.map(n=>new Level(n));return}this.tracksBuffered=[],this.levels=s.map(n=>{const i=new Level(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,s){if(this.currentTrackId=s.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.setInterval(TICK_INTERVAL)}onSubtitleTrackLoaded(e,s){var n;const{details:i,id:r}=s,{currentTrackId:o,levels:a}=this;if(!a.length)return;const l=a[o];if(r>=a.length||r!==o||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(i.live||(n=l.details)!=null&&n.live){const d=this.mainDetails;if(i.deltaUpdateFailed||!d)return;const u=d.fragments[0];l.details?(c=this.alignPlaylists(i,l.details),c===0&&u&&(c=u.start,addSliding(i,c))):i.hasProgramDateTime&&d.hasProgramDateTime?(alignMediaPlaylistByPDT(i,d),c=i.fragments[0].start):u&&(c=u.start,addSliding(i,c))}l.details=i,this.levelLastLoaded=r,!this.startFragRequested&&(this.mainDetails||!i.live)&&this.setStartPosition(l.details,c),this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===State.IDLE&&(findFragmentByPTS(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:s,payload:n}=e,i=s.decryptdata,r=this.hls;if(!this.fragContextChanged(s)&&n&&n.byteLength>0&&i&&i.key&&i.iv&&i.method==="AES-128"){const o=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer).catch(a=>{throw r.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:s}),a}).then(a=>{const l=performance.now();r.trigger(Events.FRAG_DECRYPTED,{frag:s,payload:a,stats:{tstart:o,tdecrypt:l}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=State.IDLE})}}doTick(){if(!this.media){this.state=State.IDLE;return}if(this.state===State.IDLE){const{currentTrackId:e,levels:s}=this,n=s[e];if(!s.length||!n||!n.details)return;const{config:i}=this,r=this.getLoadPosition(),o=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:l}=o,c=this.getFwdBufferInfo(this.media,PlaylistLevelType.MAIN),d=n.details,u=this.getMaxBufferLength(c==null?void 0:c.len)+d.levelTargetDuration;if(l>u)return;const h=d.fragments,f=h.length,g=d.edge;let p=null;const m=this.fragPrevious;if(a<g){const v=i.maxFragLookUpTolerance,S=a>g-v?0:v;p=findFragmentByPTS(m,h,Math.max(h[0].start,a),S),!p&&m&&m.start<h[0].start&&(p=h[0])}else p=h[f-1];if(!p)return;if(p=this.mapToInitFragWhenRequired(p),p.sn!=="initSegment"){const v=p.sn-d.startSN,S=h[v-1];S&&S.cc===p.cc&&this.fragmentTracker.getState(S)===FragmentState.NOT_LOADED&&(p=S)}this.fragmentTracker.getState(p)===FragmentState.NOT_LOADED&&this.loadFragment(p,n,a)}}getMaxBufferLength(e){const s=super.getMaxBufferLength();return e?Math.max(s,e):s}loadFragment(e,s,n){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,s):(this.startFragRequested=!0,super.loadFragment(e,s,n))}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}class BufferableInstance{constructor(e){this.buffered=void 0;const s=(n,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][n]};this.buffered={get length(){return e.length},end(n){return s("end",n,e.length)},start(n){return s("start",n,e.length)}}}}class SubtitleTrackController extends BasePlaylistController{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;
vendor: 1,728 bytes, line 25
25e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}onMediaAttached(e,s){this.media=s.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),filterSubtitleTracks(this.media.textTracks).forEac
25h(s=>{clearCurrentCues(s)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,s){this.tracks=s.subtitleTracks}onSubtitleTrackLoaded(e,s){const{id:n,details:i}=s,{trackId:r}=this,o=this.tracksInGroup[r];if(!o){this.warn(`Invalid subtitle track id ${n}`);return}const a=o.details;o.details=s.details,this.log(`subtitle track ${n} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,s,a)}onLevelLoading(e,s){this.switchLevel(s.level)}onLevelSwitching(e,s){this.switchLevel(s.level)}switchLevel(e){const s=this.hls.levels[e];if(!(s!=null&&s.textGroupIds))return;const n=s.textGroupIds[s.urlId],i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==n){const r=this.tracks.filter(l=>!n||l.groupId===n);this.tracksInGroup=r;const o=this.findTrackId(i==null?void 0:i.name)||this.findTrackId();this.groupId=n||null;const a={subtitleTracks:r};this.log(`Updating subtitle tracks, ${r.length} track(s) found in "${n}" group-id`),this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED,a),o!==-1&&this.setSubtitleTrack(o,i)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId,i)}findTrackId(e){const s=this.tracksInGroup;for(let n=0;n<s.length;n++){const i=s[n];if((!this.selectDefaultTrack||i.default)&&(!e||e===i.name))return i.id}return-1}onError(e,s){s.fatal||!s.context||s.context.type===PlaylistContextType.SUBTITLE_TRACK&&s.context.id===this.trackId&&s.context.groupId===this.groupId&&this.checkRetry(s)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const s=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,s)}loadPlaylist(e){super.loadPlaylist();const s=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(s)){const n=s.id,i=s.groupId;let r=s.url;if(e)try{r=e.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}this.log(`Loading subtitle playlist for id ${n}`),this.hls.trigger(Events.SUBTITLE_TRACK_LOADING,{url:r,id:n,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:s,trackId:n}=this;if(!s)return;const i=filterSubtitleTracks(s.textTracks),r=i.filter(a=>a.groupId===this.groupId);if(e===-1)[].slice.call(i).forEach(a=>{a.mode="disabled"});else{const a=r[n];a&&(a.mode="disabled")}const o=r[e];o&&(o.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,s){var n;const i=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(n=i[e])!=null&&n.details)||e<-1||e>=i.length)return;this.clearTimer();const r=i[e];if(this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:"")),this.trackId=e,r){const{id:o,groupId:a="",name:l,type:c,url:d}=r;this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:c,url:d});const u=this.switchParams(r.url,s==null?void 0:s.details);this.loadPlaylist(u)}else this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const s=filterSubtitleTracks(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")e=n;else if(s[n].mode==="showing"){e=n;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}}function filterSubtitleTracks(t){const e=[];for(let s=0;s<t.length;s++){const n=t[s];(n.kind==="subtitles"||n.kind==="captions")&&n.label&&e.push(t[s])}return e}class BufferOperationQueue{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,s){const n=this.queues[s];n.push(e),n.length===1&&this.buffers[s]&&this.executeNext(s)}insertAbort(e,s){this.queues[s].unshift(e),this.executeNext(s)}appendBlocker(e){let s;const n=new Promise(r=>{s=r}),i={execute:s,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),n}executeNext(e){const{buffers:s,queues:n}=this,i=s[e],r=n[e];if(r.length){const o=r[0];try{o.execute()}catch(a){logger.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),o.onError(a),i!=null&&i.updating||(r.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const MediaSource=getMediaSource(),VIDEO_CODEC_PROFILE_REPACE=/([ha]vc.)(?:\.[^.,]+)+/;class BufferController{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:s,mediaSource:n}=this;logger.log("[buffer-controller]: Media source opened"),s&&(s.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Events.MEDIA_ATTA
25CHED,{media:s})),n&&n.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{logger.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{logger.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:s,_objectUrl:n}=this;s&&s.src!==n&&logger.error(`Media element src was set while attaching MediaSource (${n} > ${s.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.BUFFER_EOS,this.onBufferEos,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.FRAG_PARSED,this.onFragParsed,this),e.on(Events.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.BUFFER_EOS,this.onBufferEos,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.FRAG_PARSED,this.onFragParsed,this),e.off(Events.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,s){let n=2;(s.audio&&!s.video||!s.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,logger.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,s){const n=this.media=s.media;if(n&&MediaSource){const i=this.mediaSource=new MediaSource;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),n.src=self.URL.createObjectURL(i),this._objectUrl=n.src,n.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:s,_objectUrl:n}=this;if(s){if(logger.log("[buffer-controller]: media source detaching"),s.readyState==="open")try{s.endOfStream()}catch(i){logger.warn(`[buffer-controller]: onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),n&&self.URL.revokeObjectURL(n),e.src===n?(e.removeAttribute("src"),e.load()):logger.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(Events.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{const s=this.sourceBuffer[e];try{s&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(s),this.sourceBuffer[e]=void 0)}catch(n){logger.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,n)}}),this._initSourceBuffer()}onBufferCodecs(e,s){const n=this.getSourceBufferTypes().length;
25Object.keys(s).forEach(i=>{if(n){const r=this.tracks[i];if(r&&typeof r.buffer.changeType=="function"){const{id:o,codec:a,levelCodec:l,container:c,metadata:d}=s[i],u=(r.levelCodec||r.codec).replace(VIDEO_CODEC_PROFILE_REPACE,"$1"),h=(l||a).replace(VIDEO_CODEC_PROFILE_REPACE,"$1");if(u!==h){const f=`${c};codecs=${l||a}`;this.appendChangeType(i,f),logger.log(`[buffer-controller]: switching codec ${u} to ${h}`),this.tracks[i]={buffer:r.buffer,codec:a,container:c,levelCodec:l,metadata:d,id:o}}}}else this.pendingTracks[i]=s[i]}),!n&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(e,s){const{operationQueue:n}=this,i={execute:()=>{const r=this.sourceBuffer[e];r&&(logger.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${s}`),r.changeType(s)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{logger.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,r)}};n.append(i,e)}onBufferAppending(e,s){const{hls:n,operationQueue:i,tracks:r}=this,{data:o,type:a,frag:l,part:c,chunkMeta:d}=s,u=d.buffering[a],h=self.performance.now();u.start=h;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=h),g&&g.start===0&&(g.start=h);const p=r.audio;let m=!1;a==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(m=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const v=l.start,S={execute:()=>{if(u.executeStart=self.performance.now(),m){const y=this.sourceBuffer[a];if(y){const C=v-y.timestampOffset;Math.abs(C)>=.1&&(logger.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${v} (delta: ${C}) sn: ${l.sn})`),y.timestampOffset=v)}}this.appendExecutor(o,a)},onStart:()=>{},onComplete:()=>{const y=self.performance.now();u.executeEnd=u.end=y,f.first===0&&(f.first=y),g&&g.first===0&&(g.first=y);const{sourceBuffer:C}=this,E={};for(const L in C)E[L]=BufferHelper.getBuffered(C[L]);this.appendError=0,this.hls.trigger(Events.BUFFER_APPENDED,{type:a,frag:l,part:c,chunkMeta:d,parent:l.type,timeRanges:E})},onError:y=>{logger.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,y);const C={type:ErrorTypes.MEDIA_ERROR,parent:l.type,details:ErrorDetails.BUFFER_APPEND_ERROR,frag:l,part:c,chunkMeta:d,error:y,err:y,fatal:!1};y.code===DOMException.QUOTA_EXCEEDED_ERR?C.details=ErrorDetails.BUFFER_FULL_ERROR:(this.appendError++,C.details=ErrorDetails.BUFFER_APPEND_ERROR,this.appendError>n.config.appendErrorMaxRetry&&(logger.error(`[buffer-controller]: Failed ${n.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),C.fatal=!0)),n.trigger(Events.ERROR,C)}};i.append(S,a)}onBufferFlushing(e,s){const{operationQueue:n}=this,i=r=>({execute:this.removeExecutor.bind(this,r,s.startOffset,s.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Events.BUFFER_FLUSHED,{type:r})},onError:o=>{logger.warn(`[buffer-controller]: Failed to remove from ${r} SourceBuffer`,o)}});s.type?n.append(i(s.type),s.type):this.getSourceBufferTypes().forEach(r=>{n.append(i(r),r)})}onFragParsed(e,s){const{frag:n,part:i}=s,r=[],o=i?i.elementaryStreams:n.elementaryStreams;o[ElementaryStreamTypes.AUDIOVIDEO]?r.push("audiovideo"):(o[ElementaryStreamTypes.AUDIO]&&r.push("audio"),o[ElementaryStreamTypes.VIDEO]&&r.push("video"));const a=()=>{const l=self.performance.now();n.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const c=i?i.stats:n.stats;this.hls.trigger(Events.FRAG_BUFFERED,{frag:n,part:i,stats:c,id:n.type})};r.length===0&&logger.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(a,r)}onFragChanged(e,s){this.flushBackBuffer()}onBufferEos(e,s){this.getSourceBufferTypes().reduce((i,r)=>{const o=this.sourceBuffer[r];return o&&(!s.type||s.type===r)&&(o.ending=!0,o.ended||(o.ended=!0,logger.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),i&&!!(!o||o.ended)},!0)&&(logger.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>
25{this.getSourceBufferTypes().forEach(r=>{const o=this.sourceBuffer[r];o&&(o.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&logger.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}logger.log("[buffer-controller]: Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:s}){s.fragments.length&&(this.details=s,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:s,media:n,sourceBuffer:i}=this;if(!n||s===null)return;const r=this.getSourceBufferTypes();if(!r.length)return;const o=s.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!isFiniteNumber(o)||o<0)return;const a=n.currentTime,l=s.levelTargetDuration,c=Math.max(o,l),d=Math.floor(a/l)*l-c;r.forEach(u=>{const h=i[u];if(h){const f=BufferHelper.getBuffered(h);if(f.length>0&&d>f.start(0)){if(e.trigger(Events.BACK_BUFFER_REACHED,{bufferEnd:d}),s.live)e.trigger(Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(h.ended&&f.end(f.length-1)-a<l*2){logger.info(`[buffer-controller]: Cannot flush ${u} back buffer while SourceBuffer is in ended state`);return}e.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:u})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:s,media:n,mediaSource:i}=this,r=e.fragments[0].start+e.totalduration,o=n.duration,a=isFiniteNumber(i.duration)?i.duration:0;e.live&&s.config.liveDurationInfinity?(logger.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(e)):(r>a&&r>o||!isFiniteNumber(o))&&(logger.log(`[buffer-controller]: Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(e){const s=this.mediaSource,n=e.fragments;if(n.length&&e.live&&s!=null&&s.setLiveSeekableRange){const r=Math.max(0,n[0].start),o=Math.max(r,r+e.totalduration);s.setLiveSeekableRange(r,o)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:s,pendingTracks:n}=this,i=Object.keys(n).length;if(i&&!e||i===2){this.createSourceBuffers(n),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(Events.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(o=>{s.executeNext(o)});else{const o=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:o,reason:o.message})}}}createSourceBuffers(e){const{sourceBuffer:s,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(const i in e)if(!s[i]){const r=e[i];if(!r)throw Error(`source buffer exists for track ${i}, however track does not`);const o=r.levelCodec||r.codec,a=`${r.container};codecs=${o}`;logger.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const l=s[i]=n.addSourceBuffer(a),c=i;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[i]={buffer:l,codec:o,container:r.container,levelCodec:r.levelCodec,metadata:r.metadata,id:r.id}}catch(l){logger.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:s}=this;s.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:s}=this;s.current(e).onComplete(),s.shiftAndExecuteNext(e)}_onSBUpdateError(e,s){const n=new Error(`${e} SourceBuffer error`);logger.error(`[buffer-controller]: ${n}`,s),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,error:n,fatal:!1});const i=this.operationQueue.current(e);i&&i.onError(s)}removeExecutor(e,s,n){const{media:i,mediaSource:r,operationQueue:o,sourceBuffer:a}=this,l=a[e];if(!i||!r||!l){logger.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),o.shiftAndExecuteNext(e);return}const c=isFiniteNumber(i.duration)?i.duration:1/0,d=isFiniteNumber(r.duration)?r.duration:1/0,u=Math.max(0,s),h=Math.min(n,c,d);h>u&&!l.ending?(l.ended=!1,logger.log(`[buffer-controller]: Removing [${u},${h}] from the ${e} SourceBuffer`),l.remove(u,h)):o.shiftAndExecuteNext(e)}appendExecutor(e,s){const{operationQueue:n,sourceBuffer:i}=this,r=i[s];if(!r){logger.warn(`[buffer-controller]: Attempting to append to the ${s} SourceBuffer, but it does not exist`),n.shiftAndExecuteNext(s);return}r.ended=!1,r.appendBuffer(e)}blockBuffers(e,s=this.getSourceBufferTypes()){if(!s.length){logger.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:n}=this,i=s.map(r=>n.appendBlocker(r));Promise.all(i).then(()=>
vendor: 12,515 bytes, lines 25-26
25{e(),s.forEach(r=>{const o=this.sourceBuffer[r];o!=null&&o.updating||n.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,s,n){const i=this.sourceBuffer[e];if(!i)return;const r=n.bind(this,e);this.listeners[e].push({event:s,listener:r}),i.addEventListener(s,r)}removeBufferListeners(e){const s=this.sourceBuffer[e];s&&this.listeners[e].forEach(n=>{s.removeEventListener(n.event,n.listener)})}}const specialCea608CharsCodes={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},getCharForByte=function(e){let s=e;return specialCea608CharsCodes.hasOwnProperty(e)&&(s=specialCea608CharsCodes[e]),String.fromCharCode(s)},NR_ROWS=15,NR_COLS=100,rowsLowCh1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rowsHighCh1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rowsLowCh2={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rowsHighCh2={25:2,26:4,29:6,30:8,31:10,27:13,28:15},backgroundColors=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(e,s){if(this.verboseLevel>=e){const n=typeof s=="function"?s():s;logger.log(`${this.time} [${e}] ${n}`)}}}const numArrayToHexArray=function(e){const s=[];for(let n=0;n<e.length;n++)s.push(e[n].toString(16));return s};class PenState{constructor(e,s,n,i,r){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=s||!1,this.italics=n||!1,this.background=i||"black",this.flash=r||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const s=["foreground","underline","italics","background","flash"];for(let n=0;n<s.length;n++){const i=s[n];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(e,s,n,i,r,o){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new PenState(s,n,i,r,o)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,s){this.uchar=e,this.penState.copy(s)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Row{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let s=0;s<NR_COLS;s++)this.chars.push(new StyledUnicodeChar);this.logger=e,this.pos=0,this.currPenState=new PenState}equals(e){let s=!0;for(let n=0;n<NR_COLS;n++)if(!this.chars[n].equals(e.chars[n])){s=!1;break}return s}copy(e){for(let s=0;s<NR_COLS;s++)this.chars[s].copy(e.chars[s])}isEmpty(){let e=!0;for(let s=0;s<NR_COLS;s++)if(!this.chars[s].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>NR_COLS&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=NR_COLS)}moveCursor(e){const s=this.pos+e;if(e>1)for(let n=this.pos+1;n<s+1;n++)this.chars[n].setPenState(this.currPenState);this.setCursor(s)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const s=getCharForByte(e);if(this.pos>=NR_COLS){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+s+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(s,this.currPenState),this.moveCursor(1)}clearFromPos(e){let s;for(s=e;s<NR_COLS;s++)this.chars[s].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let s=!0;for(let n=0;n<NR_COLS;n++){const i=this.chars[n].uchar;i!==" "&&(s=!1),e.push(i)}return s?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let s=0;s<NR_ROWS;s++)this.rows.push(new Row(e));this.logger=e,this.currRow=NR_ROWS-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<NR_ROWS;e++)this.rows[e].clear();this.currRow=NR_ROWS-1}equals(e){let s=!0;for(let n=0;n<NR_ROWS;n++)if(!this.rows[n].equals(e.rows[n])){s=!1;break}return s}copy(e){for(let s=0;s<NR_ROWS;s++)this.rows[s].copy(e.rows[s])}isEmpty(){let e=!0;for(let s=0;s<NR_ROWS;s++)if(!this.rows[s].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let s=e.row-1;if(this.nrRollUpRows&&s<this.nrRollUpRows-1&&(s=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==s){for(let a=0;a<NR_ROWS;a++)this.rows[a].clear();const r=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[r].cueStartTime,l=this.logger.time;if(a&&l!==null&&a<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[s-this.nrRollUpRows+c+1].copy(o.rows[r+c])}}this.currRow=s;const n=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,o=Math.max(r-1,0);n.setCursor(e.indent),e.color=n.chars[o].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,s=this.rows.splice(e,1)[0];s.clear(),this.rows.splice(this.currRow,0,s),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const s=[];let n="",i=-1;for(let r=0;r<NR_ROWS;r++){const o=this.rows[r].getTextString();o&&(i=r+1,e?s.push("Row "+i+": '"+o+"'"):s.push(o.trim()))}return s.length>0&&(e?n="["+s.join(" | ")+"]":n=s.join(`
26`)),n}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(e,s,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=s,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(n),this.nonDisplayedMemory=new CaptionScreen(n),this.lastOutputScreen=new CaptionScreen(n),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let n=0;n<e.length;n++)this.writeScreen.insertChar(e[n]);const s=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>s+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const s={flash:!1};if(s.underline=e%2===1,s.italics=e>=46,s.italics)s.foreground="white";else{const n=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];s.foreground=i[n]}this.logger.log(2,"MIDROW: "+JSON.stringify(s)),this.writeScreen.setPen(s)}outputDataUpdate(e=!1){const s=this.logger.time;s!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=s:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,s,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:s),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Cea608Parser{constructor(e,s,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const i=new CaptionsLogger;this.channels=[null,new Cea608Channel(e,s,i),new Cea608Channel(e+1,n,i)],this.cmdHistory=createCmdHistory(),this.logger=i}getHandler(e){return this.channels[e].getHandler()}setHandler(e,s){this.channels[e].setHandler(s)}addData(e,s){let n,i,r,o=!1;this.logger.time=e;for(let a=0;a<s.length;a+=2)if(i=s[a]&127,r=s[a+1]&127,!(i===0&&r===0)){if(this.logger.log(3,"["+numArrayToHexArray([s[a],s[a+1]])+"] -> ("+numArrayToHexArray([i,r])+")"),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroun
vendor: 8,746 bytes, line 26
26dAttributes(i,r)),!n&&(o=this.parseChars(i,r),o)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,"Couldn't parse cleaned data "+numArrayToHexArray([i,r])+" orig: "+numArrayToHexArray([s[a],s[a+1]]))}}parseCmd(e,s){const{cmdHistory:n}=this,i=(e===20||e===28||e===21||e===29)&&s>=32&&s<=47,r=(e===23||e===31)&&s>=33&&s<=35;if(!(i||r))return!1;if(hasCmdRepeated(e,s,n))return setLastCmd(null,null,n),this.logger.log(3,"Repeated command ("+numArrayToHexArray([e,s])+") is dropped"),!0;const o=e===20||e===21||e===23?1:2,a=this.channels[o];return e===20||e===21||e===28||e===29?s===32?a.ccRCL():s===33?a.ccBS():s===34?a.ccAOF():s===35?a.ccAON():s===36?a.ccDER():s===37?a.ccRU(2):s===38?a.ccRU(3):s===39?a.ccRU(4):s===40?a.ccFON():s===41?a.ccRDC():s===42?a.ccTR():s===43?a.ccRTD():s===44?a.ccEDM():s===45?a.ccCR():s===46?a.ccENM():s===47&&a.ccEOC():a.ccTO(s-32),setLastCmd(e,s,n),this.currentChannel=o,!0}parseMidrow(e,s){let n=0;if((e===17||e===25)&&s>=32&&s<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return i?(i.ccMIDROW(s),this.logger.log(3,"MIDROW ("+numArrayToHexArray([e,s])+")"),!0):!1}return!1}parsePAC(e,s){let n;const i=this.cmdHistory,r=(e>=17&&e<=23||e>=25&&e<=31)&&s>=64&&s<=127,o=(e===16||e===24)&&s>=64&&s<=95;if(!(r||o))return!1;if(hasCmdRepeated(e,s,i))return setLastCmd(null,null,i),!0;const a=e<=23?1:2;s>=64&&s<=95?n=a===1?rowsLowCh1[e]:rowsLowCh2[e]:n=a===1?rowsHighCh1[e]:rowsHighCh2[e];const l=this.channels[a];return l?(l.setPAC(this.interpretPAC(n,s)),setLastCmd(e,s,i),this.currentChannel=a,!0):!1}interpretPAC(e,s){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return s>95?n=s-96:n=s-64,i.underline=(n&1)===1,n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((n-16)/2)*4,i}parseChars(e,s){let n,i=null,r=null;if(e>=25?(n=2,r=e-8):(n=1,r=e),r>=17&&r<=19){let o;r===17?o=s+80:r===18?o=s+112:o=s+144,this.logger.log(2,"Special char '"+getCharForByte(o)+"' in channel "+n),i=[o]}else e>=32&&e<=127&&(i=s===0?[e]:[e,s]);if(i){const o=numArrayToHexArray(i);this.logger.log(3,"Char codes =  "+o.join(",")),setLastCmd(e,s,this.cmdHistory)}return i}parseBackgroundAttributes(e,s){const n=(e===16||e===24)&&s>=32&&s<=47,i=(e===23||e===31)&&s>=45&&s<=47;if(!(n||i))return!1;let r;const o={};e===16||e===24?(r=Math.floor((s-32)/2),o.background=backgroundColors[r],s%2===1&&(o.background=o.background+"_semi")):s===45?o.background="transparent":(o.foreground="black",s===47&&(o.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(o),setLastCmd(e,s,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const s=this.channels[e];s&&s.reset()}this.cmdHistory=createCmdHistory()}cueSplitAtTime(e){for(let s=0;s<this.channels.length;s++){const n=this.channels[s];n&&n.cueSplitAtTime(e)}}}function setLastCmd(t,e,s){s.a=t,s.b=e}function hasCmdRepeated(t,e,s){return s.a===t&&s.b===e}function createCmdHistory(){return{a:null,b:null}}class OutputFilter{constructor(e,s){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=s}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,s,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=s,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var VTTCue=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(a,l){if(typeof l!="string"||!Array.isArray(a))return!1;const c=l.toLowerCase();return~a.indexOf(c)?c:!1}function n(a){return s(t,a)}function i(a){return s(e,a)}function r(a,...l){let c=1;for(;c<arguments.length;c++){const d=arguments[c];for(const u in d)a[u]=d[u]}return a}function o(a,l,c){const d=this,u={enumerable:!0};d.hasBeenReset=!1;let h="",f=!1,g=a,p=l,m=c,v=null,S="",y=!0,C="auto",E="start",L=50,T="middle",b=50,_="middle";Object.defineProperty(d,"id",r({},u,{get:function(){return h},set:function(I){h=""+I}})),Object.defineProperty(d,"pauseOnExit",r({},u,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(d,"startTime",r({},u,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",r({},u,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",r({},u,{get:function(){return m},set:function(I){m=""+I,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",r({},u,{get:function(){return v},set:function(I){v=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",r({},u,{get:function(){return S},set:function(I){const P=n(I);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");S=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",r({},u,{get:function(){return y},set:function(I){y=!!I,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",r({},u,{get:function(){return C},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");C=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",r({},u,{get:function(){return E},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");E=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",r({},u,{get:function(){return L},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");L=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",r({},u,{get:function(){return T},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");T=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",r({},u,{get:function(){return b},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");b=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",r({},u,{get:function(){return _},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");_=P,this.hasBeenReset=!0}})),d.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class StringDecoder{decode(e,s){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function parseTimeStamp(t){function e(n,i,r,o){return(n|0)*3600+(i|0)*60+(r|0)+parseFloat(o||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(e,s){!this.get(e)&&s!==""&&(this.values[e]=s)}get(e,s,n){return n?this.has(e)?this.values[e]:s[n]:this.has(e)?this.values[e]:s}has(e){return e in this.values}alt(e,s,n){for(let i=0;i<n.length;++i)if(s===n[i]){this.set(e,s);break}}integer(e,s){/^-?\d+$/.test(s)&&this.set(e,parseInt(s,10))}percent(e,s){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(s)){const n=parseFloat(s);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}}function parseOptions(t,e,s,n){const i=n?t.split(n):[t];for(const r in i){if(typeof i[r]!="string")continue;const o=i[r].split(s);if(o.length!==2)continue;const a=o[0],l=o[1];e(a,l)}}const defaults=new VTTCue(0,0,""),center=defaults.align==="middle"?"middle":"center";function parseCue(t,e,s){const n=t;function i(){const a=parseTimeStamp(t);if(a===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),a}function r(a,l){const c=new Settings;parseOptions(a,function(h,f){let g;switch(h){case"region":for(let p=s.length-1;p>=0;p--)if(s[p].id===f){c.set(h,s[p].region);break}break;case"vertical":c.alt(h,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(h,g[0]),c.percent(h,g[0])&&c.set("snapToLines",!1),c.alt(h,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",center,"end"]);break;case"position":g=f.split(","),c.percent(h,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",center,"end","line-left","line-right","auto"]);break;case"size":c.percent(h,f);break;case"align":c.alt(h,f,["start",center,"end","left","right"]);break}}
vendor: 3,819 bytes, lines 26-34
26,/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let d=c.get("line","auto");d==="auto"&&defaults.line===-1&&(d=-1),l.line=d,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",center);let u=c.get("position","auto");u==="auto"&&defaults.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function o(){t=t.replace(/^\s+/,"")}if(o(),e.startTime=i(),o(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);t=t.slice(3),o(),e.endTime=i(),o(),r(t,e)}function fixLineBreaks(t){return t.replace(/<br(?: \/)?>/gi,`
27`)}class VTTParser{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const s=this;e&&(s.buffer+=s.decoder.decode(e,{stream:!0}));function n(){let r=s.buffer,o=0;for(r=fixLineBreaks(r);o<r.length&&r[o]!=="\r"&&r[o]!==`
28`;)++o;const a=r.slice(0,o);return r[o]==="\r"&&++o,r[o]===`
29`&&++o,s.buffer=r.slice(o),a}function i(r){parseOptions(r,function(o,a){},/:/)}try{let r="";if(s.state==="INITIAL"){if(!/\r\n|\n/.test(s.buffer))return this;r=n();const a=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");s.state="HEADER"}let o=!1;for(;s.buffer;){if(!/\r\n|\n/.test(s.buffer))return this;switch(o?o=!1:r=n(),s.state){case"HEADER":/:/.test(r)?i(r):r||(s.state="ID");continue;case"NOTE":r||(s.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){s.state="NOTE";break}if(!r)continue;if(s.cue=new VTTCue(0,0,""),s.state="CUE",r.indexOf("-->")===-1){s.cue.id=r;continue}case"CUE":if(!s.cue){s.state="BADCUE";continue}try{parseCue(r,s.cue,s.regionList)}catch{s.cue=null,s.state="BADCUE";continue}s.state="CUETEXT";continue;case"CUETEXT":{const a=r.indexOf("-->")!==-1;if(!r||a&&(o=!0)){s.oncue&&s.cue&&s.oncue(s.cue),s.cue=null,s.state="ID";continue}if(s.cue===null)continue;s.cue.text&&(s.cue.text+=`
30`),s.cue.text+=r}continue;case"BADCUE":r||(s.state="ID")}}}catch{s.state==="CUETEXT"&&s.cue&&s.oncue&&s.oncue(s.cue),s.cue=null,s.state=s.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
31
32`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(s){e.onparsingerror&&e.onparsingerror(s)}return e.onflush&&e.onflush(),this}}const LINEBREAKS=/\r\n|\n\r|\n|\r/g,startsWith=function(e,s,n=0){return e.slice(n,n+s.length)===s},cueString2millis=function(e){let s=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!isFiniteNumber(s)||!isFiniteNumber(n)||!isFiniteNumber(i)||!isFiniteNumber(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return s+=1e3*n,s+=60*1e3*i,s+=60*60*1e3*r,s},hash=function(e){let s=5381,n=e.length;for(;n;)s=s*33^e.charCodeAt(--n);return(s>>>0).toString()};function generateCueId(t,e,s){return hash(t.toString())+hash(e.toString())+hash(s)}const calculateOffset=function(e,s,n){let i=e[s],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(o=r)!=null&&o.new;){var o;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=n};function parseWebVTT(t,e,s,n,i,r,o){const a=new VTTParser,l=utf8ArrayToStr(new Uint8Array(t)).trim().replace(LINEBREAKS,`
33`).split(`
34`),c=[],d=e?toMpegTsClockFromTimescale(e.baseTime,e.timescale):0;let u="00:00.000",h=0,f=0,g,p=!0;a.oncue=function(m){const v=s[n];let S=s.ccOffset;const y=(h-d)/9e4;if(v!=null&&v.new&&(f!==void 0?S=s.ccOffset=v.start:calculateOffset(s,n,y)),y){if
vendor: 5,232 bytes, lines 34-36
34(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}S=y-s.presentationOffset}const C=m.endTime-m.startTime,E=normalizePts((m.startTime+S-f)*9e4,i*9e4)/9e4;m.startTime=Math.max(E,0),m.endTime=Math.max(E+C,0);const L=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(L)),m.id||(m.id=generateCueId(m.startTime,m.endTime,L)),m.endTime>0&&c.push(m)},a.onparsingerror=function(m){g=m},a.onflush=function(){if(g){o(g);return}r(c)},l.forEach(m=>{if(p)if(startsWith(m,"X-TIMESTAMP-MAP=")){p=!1,m.slice(16).split(",").forEach(v=>{startsWith(v,"LOCAL:")?u=v.slice(6):startsWith(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=cueString2millis(u)/1e3}catch(v){g=v}return}else m===""&&(p=!1);a.parse(m+`
35`)}),a.flush()}const IMSC1_CODEC="stpp.ttml.im1t",HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(t,e,s,n){const i=findBox(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(a=>utf8ArrayToStr(a)),o=toTimescaleFromScale(e.baseTime,1,e.timescale);try{r.forEach(a=>s(parseTTML(a,o)))}catch(a){n(a)}}function parseTTML(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(r).reduce((u,h)=>(u[h]=i.getAttribute(`ttp:${h}`)||r[h],u),{}),a=i.getAttribute("xml:space")!=="preserve",l=collectionToDictionary(getElementCollection(i,"styling","style")),c=collectionToDictionary(getElementCollection(i,"layout","region")),d=getElementCollection(i,"body","[begin]");return[].map.call(d,u=>{const h=getTextContent(u,a);if(!h||!u.hasAttribute("begin"))return null;const f=parseTtmlTime(u.getAttribute("begin"),o),g=parseTtmlTime(u.getAttribute("dur"),o);let p=parseTtmlTime(u.getAttribute("end"),o);if(f===null)throw timestampParsingError(u);if(p===null){if(g===null)throw timestampParsingError(u);p=f+g}const m=new VTTCue(f-e,p-e,h);m.id=generateCueId(m.startTime,m.endTime,m.text);const v=c[u.getAttribute("region")],S=l[u.getAttribute("style")],y=getTtmlStyles(v,S,l),{textAlign:C}=y;if(C){const E=textAlignToLineAlign[C];E&&(m.lineAlign=E),m.align=C}return _extends(m,y),m}).filter(u=>u!==null)}function getElementCollection(t,e,s){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(s)):[]}function collectionToDictionary(t){return t.reduce((e,s)=>{const n=s.getAttribute("xml:id");return n&&(e[n]=s),e},{})}function getTextContent(t,e){return[].slice.call(t.childNodes).reduce((s,n,i)=>{var r;return n.nodeName==="br"&&i?s+`
36`:(r=n.childNodes)!=null&&r.length?getTextContent(n,e):e?s+n.textContent.trim().replace(/\s+/g," "):s+n.textContent},"")}function getTtmlStyles(t,e,s){const n="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return o&&s.hasOwnProperty(o)&&(i=s[o]),r.reduce((a,l)=>{const c=getAttributeNS(e,n,l)||getAttributeNS(t,n,l)||getAttributeNS(i,n,l);return c&&(a[l]=c),a},{})}function getAttributeNS(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function timestampParsingError(t){return new Error(`Could not parse ttml timestamp ${t}`)}function parseTtmlTime(t,e){if(!t)return null;let s=parseTimeStamp(t);return s===null&&(HMSF_REGEX.test(t)?s=parseHoursMinutesSecondsFrames(t,e):TIME_UNIT_REGEX.test(t)&&(s=parseTimeUnits(t,e))),s}function parseHoursMinutesSecondsFrames(t,e){const s=HMSF_REGEX.exec(t),n=(s[4]|0)+(s[5]|0)/e.subFrameRate;return(s[1]|0)*3600+(s[2]|0)*60+(s[3]|0)+n/e.frameRate}function parseTimeUnits(t,e){const s=TIME_UNIT_REGEX.exec(t),n=Number(s[1]);switch(s[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}class TimelineController{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const s=new OutputFilter(this,"textTrack1"),n=new OutputFilter(this,"textTrack2"),i=new OutputFilter(this,"textTrack3"),r=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,s,n),this.cea608Parser2=new Cea608Parser(3,i,r)}
36e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,s,n,i,r){let o=!1;for(let a=r.length;a--;){const l=r[a],c=intersection(l[0],l[1],s,n);if(c>=0&&(l[0]=Math.min(l[0],s),l[1]=Math.max(l[1],n),o=!0,c/(n-s)>.5))return}if(o||r.push([s,n]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,s,n,i)}else{const a=this.Cues.newCue(null,s,n,i);this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:s,id:n,initPTS:i,timescale:r}){const{unparsedVttFrags:o}=this;n==="main"&&(this.initPTS[s.cc]={baseTime:i,timescale:r}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(Events.FRAG_LOADED,a)}))}getExistingTrack(e){const{media:s}=this;if(s)for(let n=0;n<s.textTracks.length;n++){const i=s.textTracks[n];if(i[e])return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:s,captionsTracks:n,media:i}=this,{label:r,languageCode:o}=s[e],a=this.getExistingTrack(e);if(a)n[e]=a,clearCurrentCues(n[e]),sendAddTrackEvent(n[e],i);else{const l=this.createTextTrack("captions",r,o);l&&(l[e]=!0,n[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const s=this.captionsProperties[e];if(!s)return;const n=s.label,i={_id:e,label:n,kind:"captions",default:s.media?!!s.media.default:!1,closedCaptions:s.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,s,n){const i=this.media;if(i)return i.addTextTrack(e,s,n)}onMediaAttaching(e,s){this.media=s.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(s=>{clearCurrentCues(e[s]),delete e[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const s=e.textTracks;if(s)for(let n=0;n<s.length;n++)clearCurrentCues(s[n])}onSubtitleTracksUpdated(e,s){const n=s.subtitleTracks||[],i=n.some(r=>r.textCodec===IMSC1_CODEC);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(subtitleOptionsIdentical(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const o=this.media?this.media.textTracks:null;this.tracks.forEach((a,l)=>{let c;if(o&&l<o.length){let d=null;for(let u=0;u<o.length;u++)if(canReuseVttTextTrack(o[u],a)){d=o[u];break}d&&(c=d)}if(c)clearCurrentCues(c);else{const d=this._captionsOrSubtitlesFromCharacteristics(a);c=this.createTextTrack(d,a.name,a.lang),c&&(c.mode="disabled")}c&&(c.groupId=a.groupId,this.textTracks.push(c))})}else if(this.tracks.length){const o=this.tracks.map(a=>
36({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const s=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),n=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(s&&n)return"captions"}return"subtitles"}onManifestLoaded(e,s){this.config.enableCEA708Captions&&s.captions&&s.captions.forEach(n=>{const i=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!i)return;const r=`textTrack${i[1]}`,o=this.captionsProperties[r];o&&(o.label=n.name,n.lang&&(o.languageCode=n.lang),o.media=n)})}closedCaptionsForLevel(e){const s=this.hls.levels[e.level];return s==null?void 0:s.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,s){const{cea608Parser1:n,cea608Parser2:i,lastSn:r,lastPartIndex:o}=this;if(!(!this.enabled||!(n&&i))&&s.frag.type===PlaylistLevelType.MAIN){var a,l;const c=s.frag.sn,d=(a=s==null||(l=s.part)==null?void 0:l.index)!=null?a:-1;c===r+1||c===r&&d===o+1||(n.reset(),i.reset()),this.lastSn=c,this.lastPartIndex=d}}onFragLoaded(e,s){const{frag:n,payload:i}=s;if(n.type===PlaylistLevelType.SUBTITLE)if(i.byteLength){const r=n.decryptdata,o="stats"in s;if(r==null||!r.encrypted||o){const a=this.tracks[n.level],l=this.vttCCs;l[n.cc]||(l[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),a&&a.textCodec===IMSC1_CODEC?this._parseIMSC1(n,i):this._parseVTTs(s)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,s){const n=this.hls;parseIMSC1(s,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{logger.log(`Failed to parse IMSC1: ${i}`),n.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var s;const{frag:n,payload:i}=e,{initPTS:r,unparsedVttFrags:o}=this,a=r.length-1;if(!r[n.cc]&&a===-1){o.push(e);return}const l=this.hls,c=(s=n.initSegment)!=null&&s.data?appendUint8Array(n.initSegment.data,new Uint8Array(i)):i;parseWebVTT(c,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,d=>{this._appendCues(d,n.level),l.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},d=>{const u=d.message==="Missing initPTS for VTT MPEGTS";u?o.push(e):this._fallbackToIMSC1(n,i),logger.log(`Failed to parse VTT cue: ${d}`),!(u&&a>n.cc)&&l.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:d})})}_fallbackToIMSC1(e,s){const n=this.tracks[e.level];n.textCodec||parseIMSC1(s,this.initPTS[e.cc],()=>{n.textCodec=IMSC1_CODEC,this._parseIMSC1(e,s)},()=>{n.textCodec="wvtt"})}_appendCues(e,s){const n=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[s];if(!i||i.mode==="disabled")return;e.forEach(r=>addCueToTrack(i,r))}else{const i=this.tracks[s];if(!i)return;const r=i.default?"default":"subtitles"+s;n.trigger(Events.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,s){const{frag:n}=s;n.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,s)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,s){const{cea608Parser1:n,cea608Parser2:i}=this;if(!this.enabled||!(n&&i))return;const{frag:r,samples:o}=s;if(!(r.type===PlaylistLevelType.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let a=0;a<o.length;a++){const l=o[a].bytes;if(l){const c=this.extractCea608Data(l);n.addData(o[a].pts,c[0]),i.addData(o[a].pts,c[1])}}}onBufferFlushing(e,{startOffset:s,endOffset:n,endOffsetSubtitles:i,type:r}){const{media:o}=this;if(!(!o||o.currentTime<n)){if(!r||r==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>removeCuesInRange(a[l],s,n))}if(this.config.renderTextTracksNatively&&s===0&&i!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>removeCuesInRange(a[l],s,i))}}}extractCea608Data(e){const s=[[],[]],n=e[0]&31;let i=2;for(let r=0;r<n;r++){const o=e[i++],a=127&e[i++],l=127&e[i++];if(a===0&&l===0)continue;if((4&o)!==0){const d=3&o;(d===0||d===1)&&(s[d].push(a),s[d].push(l))}}return s}}function canReuseVttTextTrack(t,e){return!!t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}function intersection(t,e,s,n){return Math.min(e,n)-Math.max(t,s)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class CapLevelController{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Events.MEDIA_ATTA
vendor: 22,478 bytes, lines 36-37
36CHING,this.onMediaAttaching,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,s){const n=this.hls.levels[s.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,s){this.media=s.media instanceof HTMLVideoElement?s.media:null,this.clientRect=null}onManifestParsed(e,s){const n=this.hls;this.restrictedLevels=[],this.firstLevel=s.firstLevel,n.config.capLevelToPlayerSize&&s.video&&this.startCapping()}onBufferCodecs(e,s){this.hls.config.capLevelToPlayerSize&&s.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const s=this.hls;s.autoLevelCapping=this.getMaxLevel(e.length-1),s.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=s.autoLevelCapping}}}getMaxLevel(e){const s=this.hls.levels;if(!s.length)return-1;const n=s.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,s={width:0,height:0};if(e){const n=e.getBoundingClientRect();s.width=n.width,s.height=n.height,!s.width&&!s.height&&(s.width=n.right-n.left||e.width||0,s.height=n.bottom-n.top||e.height||0)}return this.clientRect=s,s}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,s,n){if(!(e!=null&&e.length))return-1;const i=(o,a)=>a?o.width!==a.width||o.height!==a.height:!0;let r=e.length-1;for(let o=0;o<e.length;o+=1){const a=e[o];if((a.width>=s||a.height>=n)&&i(a,e[o+1])){r=o;break}}return r}}class FPSController{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,s){const n=this.hls.config;if(n.capLevelOnFPSDrop){const i=s.media instanceof self.HTMLVideoElement?s.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,s,n){const i=performance.now();if(s){if(this.lastTime){const r=i-this.lastTime,o=n-this.lastDroppedFrames,a=s-this.lastDecodedFrames,l=1e3*o/r,c=this.hls;if(c.trigger(Events.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:n}),l>0&&o>c.config.fpsDroppedMonitoringThreshold*a){let d=c.currentLevel;logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=d)&&(d=d-1,c.trigger(Events.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:c.currentLevel}),c.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=n,this.lastDecodedFrames=s}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const s=e.getVideoPlaybackQuality();this.checkFPS(e,s.totalVideoFrames,s.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const LOGGER_PREFIX="[eme]";class EMEController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=logger.debug.bind(logger,LOGGER_PREFIX),this.log=logger.log.bind(logger,LOGGER_PREFIX),this.warn=logger.warn.bind(logger,LOGGER_PREFIX),this.error=logger.error.bind(logger,LOGGER_PREFIX),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:s,widevineLicenseUrl:n}=this.config,i=s[e];if(i)return i.licenseUrl;if(e===KeySystems.WIDEVINE&&n)return n;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:s}=this.config,n=s[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const s=this.hls.levels,n=(o,a,l)=>!!o&&l.indexOf(o)===a,i=s.map(o=>o.audioCodec).filter(n),r=s.map(o=>o.videoCodec).filter(n);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((o,a)=>{const l=c=>{const d=c.shift();this.getMediaKeysPromise(d,i,r).then(u=>o({keySystem:d,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof EMEKeyError?a(u):a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,s){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return requestMediaKeySystemAccess===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return n(e,s)}getMediaKeysPromise(e,s,n){const i=getSupportedMediaKeySystemConfigurations(e,s,n,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let o=r==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),o=this.requestMediaKeySystemAccess(e,i);const a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),a.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.then(u=>u?this.setMediaKeysServerCertificate(d,e,u):d))),a.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),a.mediaKeys})}return o.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:s,mediaKeys:n}){this.log(`Creating key-system session "${s}" keyId: ${Hex.hexDump(e.keyId||[])}`);const i=n.createSession(),r={decryptdata:e,keySystem:s,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const s=e.decryptdata;if(s.pssh){const n=this.createMediaKeySessionContext(e),i=this.getKeyIdString(s),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,r,s.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Hex.hexDump(e.keyId)}updateKeySession(e,s){var n;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Hex.hexDump(((n=e.decryptdata)==null?void 0:n.keyId)||[])}
37      } (data length: ${s&&s.byteLength})`),i.update(s)}selectKeySystemFormat(e){const s=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((s,n)=>{const i=getKeySystemsForConfig(this.config),r=e.map(keySystemFormatToKeySystemDomain).filter(o=>!!o&&i.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:o})=>{const a=keySystemDomainToKeySystemFormat(o);a?s(a):n(new Error(`Unable to find format for key-system "${o}"`))}).catch(n)})}loadKey(e){const s=e.keyInfo.decryptdata,n=this.getKeyIdString(s),i=`(keyId: ${n} format: "${s.keyFormat}" method: ${s.method} uri: ${s.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[n];return r||(r=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(s).then(({keySystem:o,mediaKeys:a})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(o,a).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:o,mediaKeys:a,decryptdata:s});return this.generateRequestWithPreferredKeySession(l,"cenc",s.pssh,"playlist-key")}))),r.catch(o=>this.handleError(o))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof EMEKeyError?this.hls.trigger(Events.ERROR,e.data):this.hls.trigger(Events.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const s=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[s];if(!n){const i=keySystemFormatToKeySystemDomain(e.keyFormat),r=i?[i]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(r)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=getKeySystemsForConfig(this.config)),e.length===0)throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:s,initData:n}=e;if(this.debug(`"${e.type}" event: init data type: "${s}"`),n===null)return;let i,r;if(s==="sinf"&&this.config.drmSystems[KeySystems.FAIRPLAY]){const d=bin2str(new Uint8Array(n));try{const u=base64Decode(JSON.parse(d).sinf),h=parseSinf(new Uint8Array(u));if(!h)return;i=h.subarray(8,24),r=KeySystems.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const d=parsePssh(n);if(d===null)return;d.version===0&&d.systemId===KeySystemIds.WIDEVINE&&d.data&&(i=d.data.subarray(8,24)),r=keySystemIdToKeySystemDomain(d.systemId)}if(!r||!i)return;const o=Hex.hexDump(i),{keyIdToKeySessionPromise:a,mediaKeySessions:l}=this;let c=a[o];for(let d=0;d<l.length;d++){const u=l[d],h=u.decryptdata;if(h.pssh||!h.keyId)continue;const f=Hex.hexDump(h.keyId);if(o===f||h.uri.replace(/-/g,"").indexOf(o)!==-1){c=a[f],delete a[f],h.pssh=new Uint8Array(n),h.keyId=i,c=a[o]=c.then(()=>this.generateRequestWithPreferredKeySession(u,s,n,"encrypted-event-key-match"));break}}c||(c=a[o]=this.getKeySystemSelectionPromise([r]).then(({keySystem:d,mediaKeys:u})=>{var h;this.throwIfDestroyed();const f=new LevelKey("ISO-23001-7",o,(h=keySystemDomainToKeySystemFormat(d))!=null?h:"");return f.pssh=new Uint8Array(n),f.keyId=i,this.attemptSetMediaKeys(d,u).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:d,mediaKeys:u});return this.generateRequestWithPreferredKeySession(g,s,n,"encrypted-event-no-match")})})),c.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,s){const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(n).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(s)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>n.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,s,n,i){var r,o;const a=(r=this.config.drmSystems)==null||(o=r[e.keySystem])==null?void 0:o.generateRequest;if(a)try{const h=a.call(this.hls,s,n,e);if(!h)throw new Error("Invalid response from configured generateRequest filter");s=h.initDataType,n=e.decryptdata.pssh=h.initData?new Uint8Array(h.initData):null}catch(h){var l;if(this.warn(h.message),(l=this.hls)!=null&&l.config.debug)throw h}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${c} (init data type: ${s} length: ${n?n.byteLength:null})`);const d=new EventEmitter;e.mediaKeysSession.onmessage=h=>{const f=e.mediaKeysSession;if(!f){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:p}=h;this.log(`"${g}" message event for session "${f.sessionId}" message size: ${p.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,p).catch(m=>{this.handleError(m),d.emit("error",m)}):g==="license-release"?e.keySystem===KeySystems.FAIRPLAY&&(this.updateKeySession(e,strToUtf8array("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${g}"`)},e.mediaKeysSession.onkeystatuseschange=h=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const g=e.keyStatus;d.emit("keyStatus",g),g==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};const u=new Promise((h,f)=>{d.on("error",f),d.on("keyStatus",g=>{g.startsWith("usable")?h():g==="output-restricted"?f(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):g==="internal-error"?f(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${g}"`)):g==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${g}"`)})});return e.mediaKeysSession.generateRequest(s,n).then(()=>{var h;this.log(`Request generated for key-session "${(h=e.mediaKeysSession)==null?void 0:h.sessionId}" keyId: ${c}`)}).catch(h=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_SESSION,error:h,fatal:!1},`Error generating key-session request: ${h}`)}).then(()=>u).catch(h=>{throw d.removeAllListeners(),this.removeSession(e),h}).then(()=>(d.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((s,n)=>{this.log(`key status change "${s}" for keyStatuses keyId: ${Hex.hexDump("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${Hex.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=s})}fetchServerCertificate(e){const s=this.config,n=s.loader,i=new n(s),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:r},c=s.certLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,g,p)=>{o(h.data)},onError:(h,f,g,p)=>{a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:_objectSpread2({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${r}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,g)=>{a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(h,f,g)=>{a(new Error("aborted"))}};i.load(l,d,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,s,n){return new Promise((i,r)=>{e.setServerCertificate(n).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${n==null?void 0:n.byteLength}) on "${s}"`),i(e)}).catch(o=>{r(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,s){return this.requestLicense(e,new Uint8Array(s)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(i=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}setupLicenseXHR(e,s,n,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,s,n,i)}).catch(o=>{if(!n.decryptdata)throw o;return e.open("POST",s,!0),r.call(this.hls,e,s,n,i)}).then(o=>(e.readyState||e.open("POST",s,!0),{xhr:e,licenseChallenge:o||i})):(e.open("POST",s,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,s){const n=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const o=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${o}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let l=a.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,a,o,e)}catch(d){this.error(d)}i(l)}else{const l=n.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||a.status>=400&&a.status<500)r(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else{const d=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,s).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,s).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,s){if(!this.config.emeEnabled)return;const n=s.media;this.media=n,n.addEventListener("encrypted",this.onMediaEncrypted),n.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,s=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();const n=s.length;EMEController.CDMCleanupPromise=Promise.all(s.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:s}){if(!(!s||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=s.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(e){const{mediaKeysSession:s,licenseXhr:n}=e;if(s){this.log(`Remove licenses and keys and close session ${s.sessionId}`),s.onmessage=null,s.onkeystatuseschange=null,n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),s.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>s.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(e,s){super(s),this.data=void 0,e.error||(e.error=new Error(s)),this.data=e,e.err=e.error}}const CMCDVersion=1;var CMCDObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",
37KEY:"k",OTHER:"o"};const CMCDStreamingFormatHLS="h";class CMCDController{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:CMCDObjectType.MANIFEST,su:!this.initialized})}catch(r){logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,o=this.hls.levels[r.level],a=this.getObjectType(r),l={d:r.duration*1e3,ot:a};(a===CMCDObjectType.VIDEO||a===CMCDObjectType.AUDIO||a==CMCDObjectType.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(a)/1e3,l.bl=this.getBufferLength(a)),this.apply(i,l)}catch(r){logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const s=this.config=e.config,{cmcd:n}=s;n!=null&&(s.pLoader=this.createPlaylistLoader(),s.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||CMCDController.uuid(),this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,s){this.media=s.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,s){var n,i;this.audioBuffer=(n=s.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(i=s.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:CMCDVersion,sf:CMCDStreamingFormatHLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,s={}){_extends(s,this.createData());const n=s.ot===CMCDObjectType.INIT||s.ot===CMCDObjectType.VIDEO||s.ot===CMCDObjectType.MUXED;if(this.starved&&n&&(s.bs=!0,s.su=!0,this.starved=!1),s.su==null&&(s.su=this.buffering),this.useHeaders){const i=CMCDController.toHeaders(s);if(!Object.keys(i).length)return;e.headers||(e.headers={}),_extends(e.headers,i)}else{const i=CMCDController.toQuery(s);if(!i)return;e.url=CMCDController.appendQueryToUri(e.url,i)}}getObjectType(e){const{type:s}=e;if(s==="subtitle")return CMCDObjectType.TIMED_TEXT;if(e.sn==="initSegment")return CMCDObjectType.INIT;if(s==="audio")return CMCDObjectType.AUDIO;if(s==="main")return this.hls.audioTracks.length?CMCDObjectType.VIDEO:CMCDObjectType.MUXED}getTopBandwidth(e){let s=0,n;const i=this.hls;if(e===CMCDObjectType.AUDIO)n=i.audioTracks;else{const r=i.maxAutoLevel,o=r>-1?r+1:i.levels.length;n=i.levels.slice(0,o)}for(const r of n)r.bitrate>s&&(s=r.bitrate);return s>0?s:NaN}getBufferLength(e){const s=this.hls.media,n=e===CMCDObjectType.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!s?NaN:BufferHelper.bufferInfo(n,s.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,s=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new n(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,a){s(r),this.loader.load(r,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,s=this.applyFragmentData,n=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new n(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,a){s(r),this.loader.load(r,o,a)}}}static uuid(){const e=URL.createObjectURL(new Blob),s=e.toString();return URL.revokeObjectURL(e),s.slice(s.lastIndexOf("/")+1)}static serialize(e){const s=[],n=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,i=c=>Math.round(c),r=c=>i(c/100)*100,a={br:i,d:i,bl:r,dl:r,mtp:r,nor:c=>encodeURIComponent(c),rtp:r,tb:i},l=Object.keys(e||{}).sort();for(const c of l){let d=e[c];if(!n(d)||c==="v"&&d===1||c=="pr"&&d===1)continue;const u=a[c];u&&(d=u(d));const h=typeof d;let f;c==="ot"||c==="sf"||c==="st"?f=`${c}=${d}`:h==="boolean"?f=c:h==="number"?f=`${c}=${d}`:f=`${c}=${JSON.stringify(d)}`,s.push(f)}return s.join(",")}static toHeaders(e){const s=Object.keys(e),n={},i=["Object","Request","Session","Status"],r=[{},{},{},{}],o={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const a of s){const l=o[a]!=null?o[a]:1;r[l][a]=e[a]}for(let a=0;a<r.length;a++){const l=CMCDController.serialize(r[a]);l&&(n[`CMCD-${i[a]}`]=l)}return n}static toQuery(e){return`CMCD=${encodeURIComponent(CMCDController.serialize(e))}`}static appendQueryToUri(e,s){if(!s)return e;const n=e.includes("?")?"&":"?";return`${e}${n}${s}`}}const PATHWAY_PENALTY_DURATION_MS=3e5;class ContentSteeringController{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=logger.log.bind(logger,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.ERROR,this.onError,this))}
37startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const s=this.levels;s&&(this.levels=s.filter(n=>n!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,s){const{contentSteering:n}=s;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,s){this.audioTracks=s.audioTracks,this.subtitleTracks=s.subtitleTracks}onError(e,s){const{errorAction:n}=s;if((n==null?void 0:n.action)===NetworkErrorAction.SendAlternateToPenaltyBox&&n.flags===ErrorActionFlags.MoveAllAlternatesMatchingHost){let i=this.pathwayPriority;const r=this.pathwayId;this.penalizedPathways[r]||(this.penalizedPathways[r]=performance.now()),!i&&this.levels&&(i=this.levels.reduce((o,a)=>(o.indexOf(a.pathwayId)===-1&&o.push(a.pathwayId),o),[])),i&&i.length>1&&(this.updatePathwayPriority(i),n.resolved=this.pathwayId!==r)}}filterParsedLevels(e){this.levels=e;let s=this.getLevelsForPathway(this.pathwayId);if(s.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),s=this.getLevelsForPathway(n),this.pathwayId=n}return s.length!==e.length?(this.log(`Found ${s.length}/${e.length} levels in Pathway "${this.pathwayId}"`),s):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(s=>e===s.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let s;const n=this.penalizedPathways,i=performance.now();Object.keys(n).forEach(r=>{i-n[r]>PATHWAY_PENALTY_DURATION_MS&&delete n[r]});for(let r=0;r<e.length;r++){const o=e[r];if(n[o])continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(s=this.getLevelsForPathway(o),s.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,this.hls.trigger(Events.LEVELS_UPDATED,{levels:s});const c=this.hls.levels[a];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=a);break}}}clonePathways(e){const s=this.levels;if(!s)return;const n={},i={};e.forEach(r=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=r;if(s.some(d=>d.pathwayId===o))return;const c=this.getLevelsForPathway(a).map(d=>{const u=_extends({},d);u.details=void 0,u.url=performUriReplacement(d.uri,d.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const h=new AttrList(d.attrs);h["PATHWAY-ID"]=o;const f=h.AUDIO&&`${h.AUDIO}_clone_${o}`,g=h.SUBTITLES&&`${h.SUBTITLES}_clone_${o}`;f&&(n[h.AUDIO]=f,h.AUDIO=f),g&&(i[h.SUBTITLES]=g,h.SUBTITLES=g),u.attrs=h;const p=new Level(u);return addGroupId(p,"audio",f),addGroupId(p,"text",g),p});s.push(...c),cloneRenditionGroups(this.audioTracks,n,l,o),cloneRenditionGroups(this.subtitleTracks,i,l,o)})}loadSteeringManifest(e){const s=this.hls.config,n=s.loader;this.loader&&this.loader.destroy(),this.loader=new n(s);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||s.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+d)}const r={responseType:"json",url:i.href},o=s.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(d,u,h,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=d.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":v}=g;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),m&&this.clonePathways(m),v&&this.updatePathwayPriority(v)},onError:(d,u,h,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${u.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const m=p.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(d,u,h)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,s=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},s)}}function cloneRenditionGroups(t,e,s,n){t&&Object.keys(e).forEach(i=>
37{const r=t.filter(o=>o.groupId===i).map(o=>{const a=_extends({},o);return a.details=void 0,a.attrs=new AttrList(a.attrs),a.url=a.attrs.URI=performUriReplacement(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),a.groupId=a.attrs["GROUP-ID"]=e[i],a.attrs["PATHWAY-ID"]=n,a});t.push(...r)})}function performUriReplacement(t,e,s,n){const{HOST:i,PARAMS:r,[s]:o}=n;let a;e&&(a=o==null?void 0:o[e],a&&(t=a));const l=new self.URL(t);return i&&!a&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im;class XhrLoader{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,s,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=s,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:s}=this;if(!e)return;const n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!this.stats.aborted)return r(n,s.url)}).catch(o=>(n.open("GET",s.url,!0),r(n,s.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(n,s,e)}).catch(o=>{this.callbacks.onError({code:n.status,text:o.message},s,n,i)}):this.openAndSendXhr(n,s,e)}openAndSendXhr(e,s,n){e.readyState||e.open("GET",s.url,!0);const i=this.context.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:o}=n.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);s.rangeEnd&&e.setRequestHeader("Range","bytes="+s.rangeStart+"-"+(s.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=s.responseType,self.clearTimeout(this.requestTimeout),n.timeout=r&&isFiniteNumber(r)?r:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:s,stats:n}=this;if(!e||!s)return;const i=s.readyState,r=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),s.onreadystatechange=null,s.onprogress=null;const o=s.status,a=s.responseType!=="text";if(o>=200&&o<300&&(a&&s.response||s.responseText!==null)){n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=a?s.response:s.responseText,c=s.responseType==="arraybuffer"?l.byteLength:l.length;if(n.loaded=n.total=c,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(n,e,l,s),!this.callbacks)return;const u={url:s.responseURL,data:l,code:o};this.callbacks.onSuccess(u,n,e,s)}else{const l=r.loadPolicy.errorRetry,c=n.retry;shouldRetry(l,c,!1,o)?this.retry(l):(logger.error(`${o} while loading ${e.url}`),this.callbacks.onError({code:o,text:s.statusText},e,s,n))}}}loadtimeout(){var e;const s=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,n=this.stats.retry;if(shouldRetry(s,n,!0))this.retry(s);else{logger.warn(`timeout while loading ${this.context.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:s,stats:n}=this;this.retryDelay=getRetryDelay(e,n.retry),n.retry++,logger.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${s.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const s=this.stats;s.loaded=e.loaded,e.lengthComputable&&(s.total=e.total)}getCacheAge(){let e=null;if(this.loader&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){const s=this.loader.getResponseHeader("age");e=s?parseFloat(s):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const BYTERANGE=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,s,n){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=getRequestParameters(e,this.controller.signal),o=n.onProgress,a=e.responseType==="arraybuffer",l=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=s.loadPolicy;this.context=e,this.config=s,this.callbacks=n,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),s.timeout=c&&isFiniteNumber(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},s.timeout),self.fetch(this.request).then(u=>{this.response=this.loader=u;const h=Math.max(self.performance.now(),i.loading.start);
37if(self.clearTimeout(this.requestTimeout),s.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},d-(h-i.loading.start)),!u.ok){const{status:f,statusText:g}=u;throw new FetchError(g||"fetch, bad network response",f,u)}return i.loading.first=h,i.total=getContentLength(u.headers)||i.total,o&&isFiniteNumber(s.highWaterMark)?this.loadProgressively(u,i,e,s.highWaterMark,o):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{const{response:h}=this;self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const f=u[l];f&&(i.loaded=i.total=f);const g={url:h.url,data:u,code:h.status};o&&!isFiniteNumber(s.highWaterMark)&&o(i,e,u,h),n.onSuccess(g,i,e,h)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const h=u&&u.code||0,f=u?u.message:null;n.onError({code:h,text:f},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const s=this.response.headers.get("age");e=s?parseFloat(s):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,s,n,i=0,r){const o=new ChunkCache,a=e.body.getReader(),l=()=>a.read().then(c=>{if(c.done)return o.dataLength&&r(s,n,o.flush(),e),Promise.resolve(new ArrayBuffer(0));const d=c.value,u=d.length;return s.loaded+=u,u<i||o.dataLength?(o.push(d),o.dataLength>=i&&r(s,n,o.flush(),e)):r(s,n,d,e),l()}).catch(()=>Promise.reject());return l()}}function getRequestParameters(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(_extends({},t.headers))};return t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),s}function getByteRangeLength(t){const e=BYTERANGE.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function getContentLength(t){const e=t.get("Content-Range");if(e){const n=getByteRangeLength(e);if(isFiniteNumber(n))return n}const s=t.get("Content-Length");if(s)return parseInt(s)}function getRequest(t,e){return new self.Request(t.url,e)}class FetchError extends Error{constructor(e,s,n){super(e),this.code=void 0,this.details=void 0,this.code=s,this.details=n}}const WHITESPACE_CHAR=/\s/,Cues={newCue(t,e,s,n){const i=[];let r,o,a,l,c;const d=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(r=n.rows[h],a=!0,l=0,c="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)WHITESPACE_CHAR.test(r.chars[p].uchar)&&a?l++:(c+=r.chars[p].uchar,a=!1);r.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const f=fixLineBreaks(c.trim()),g=generateCueId(e,s,f);t!=null&&(u=t.cues)!=null&&u.getCueById(g)||(o=new d(e,s,f),o.id=g,o.line=h+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(o))}return t&&i.length&&(i.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),i.forEach(h=>addCueToTrack(t,h))),i}},defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:requestMediaKeySystemAccess,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,cert
vendor: 4,124 bytes, line 37
37LoadPolicy:{default:defaultLoadPolicy},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=deepCpy(t),n=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(r=>{const o=`${r==="level"?"playlist":r}LoadPolicy`,a=e[o]===void 0,l=[];i.forEach(c=>{const d=`${r}Loading${c}`,u=e[d];if(u!==void 0&&a){l.push(d);const h=s[o].default;switch(e[o]={default:h},c){case"TimeOut":h.maxLoadTimeMs=u,h.maxTimeToFirstByteMs=u;break;case"MaxRetry":h.errorRetry.maxNumRetry=u,h.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":h.errorRetry.retryDelayMs=u,h.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=u,h.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&logger.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${JSON.stringify(e[o])}`)}),_objectSpread2(_objectSpread2({},s),e)}function deepCpy(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(deepCpy):Object.keys(t).reduce((e,s)=>(e[s]=deepCpy(t[s]),e),{}):t}function enableStreamingMode(t){const e=t.loader;e!==FetchLoader&&e!==XhrLoader?(logger.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):fetchSupported()&&(t.loader=FetchLoader,t.progressive=!0,t.enableSoftw
37areAES=!0,logger.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Hls{static get version(){return"1.4.10"}static isSupported(){return isSupported()}static get Events(){return Events}static get ErrorTypes(){return ErrorTypes}static get ErrorDetails(){return ErrorDetails}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig}static set DefaultConfig(e){Hls.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new EventEmitter,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,enableLogs(e.debug||!1,"Hls instance");const s=this.config=mergeConfig(Hls.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,s.progressive&&enableStreamingMode(s);const{abrController:n,bufferController:i,capLevelController:r,errorController:o,fpsController:a}=s,l=new o(this),c=this.abrController=new n(this),d=this.bufferController=new i(this),u=this.capLevelController=new r(this),h=new a(this),f=new PlaylistLoader(this),g=new ID3TrackController(this),p=s.contentSteeringController,m=p?new p(this):null,v=this.levelController=new LevelController(this,m),S=new FragmentTracker(this),y=new KeyLoader(this.config),C=this.streamController=new StreamController(this,S,y);u.setStreamController(C),h.setStreamController(C);const E=[f,v,C];m&&E.splice(1,0,m),this.networkControllers=E;const L=[c,d,u,h,g,S];this.audioTrackController=this.createController(s.audioTrackController,E);const T=s.audioStreamController;T&&E.push(new T(this,S,y)),this.subtitleTrackController=this.createController(s.subtitleTrackController,E);const b=s.subtitleStreamController;b&&E.push(new b(this,S,y)),this.createController(s.timelineController,L),y.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(LatencyController,L),this.coreComponents=L,E.push(l);const _=l.onErrorOut;typeof _=="function"&&this.on(Events.ERROR,_,l)}createController(e,s){if(e){const n=new e(this);return s&&s.push(n),n}return null}on(e,s,n=this){this._emitter.on(e,s,n)}once(e,s,n=this){this._emitter.once(e,s,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,s,n=this,i){this._emitter.off(e,s,n,i)}listeners(e){return this._emitter.listeners(e)}emit(e,s,n){return this._emitter.emit(e,s,n)}trigger(e,s){if(this.config.debug)return this.emit(e,e,s);try{return this.emit(e,e,s)}catch(n){logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:e,error:n})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){logger.log("destroy"),this.trigger(Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(s=>s.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(s=>s.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){logger.log("attachMedia"),this._media=e,this.trigger(Events.MEDIA_ATTACHING,{media:e})}detachMedia(){logger.log("detachMedia"),this.trigger(Events.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const s=this.media,n=this.url,i=this.url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});logger.log(`loadSource:${i}`),s&&n&&(n!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(Events.MANIFEST_LOADING,{url:e})}startLoad(e=-1){logger.log(`startLoad(${e}
37)`),this.networkControllers.forEach(s=>{s.startLoad(e)})}stopLoad(){logger.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){logger.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,s=0){this.levelController.removeLevel(e,s)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){logger.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const s=!!e;s!==this.config.capLevelToPlayerSize&&(s?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){HdcpLevels.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:s}}=this;if(!e)return 0;const n=e.length;for(let i=0;i<n;i++)if(e[i].maxBitrate>=s)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:s,maxHdcpLevel:n}=this;let i;if(s===-1&&e&&e.length?i=e.length-1:i=s,n)for(let r=i;r--;){const o=e[r].attrs["HDCP-LEVEL"];if(o&&o<=n)return r}return i}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const s=this.audioTrackController;s&&(s.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const s=this.subtitleTrackController;s&&(s.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const s=this.subtitleTrackController;s&&(s.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Hls.defaultConfig=void 0;const sum=t=>t.length===0?void 0:t.reduce((e,s)=>e+s,0);function avg(t){if(t.length!==0)return t.reduce((e,s)=>e+s,0)/t.length}function min(t){if(t.length!==0)return Math.min.apply(null,t)}function max(t){if(t.length!==0)return Math.max.apply(null,t)}function filledWithZeros(t){return new Array(t).fill(0)}function flatten(t){let e=[];return t.forEach(s=>{Array.isArray(s)?e=e.concat(flatten(s)):e.push(s)}),e}const log$9=logger$1("tv-stats"),CONNECTION_TYPE={ethernet:"lan",wifi:"wifi",cellular:"mobile"},PLAYER_ID={hls:"hls",native:"native"};class PlayerStats{constructor(e){$(this,"channelId","");$(this,"playbackTime",0);$(this,"mediaId","");$(this,"pbsId","");$(this,"isLive",!1);$(this,"playIntervalNum",0);$(this,"dvrDelayMs",0);$(this,"isPrograms",!1);$(this,"isVitrina",!1);$(this,"connectionType");$(this,"playerId","");$(this,"systemMiniplayerTimeMs",0);$(this,"secondScreenTimeMs",0);$(this,"errorEventsCnt",0);$(this,"isPlaybackAborted",!1);$(this,"commonSizeFragsKbps",0);$(this,"commonTimeFragsLoadingSeconds",0);$(this,"minimalFragsKbps",0);$(this,"languages",[]);$(this,"playingLanguageIndex",0);$(this,"playingRenditionIndex",0);$(this,"fullScreenStartTime",0);$(this,"fullScreenTime",0);$(this,"windowedStartTime",0);$(this,"windowedTime",0);$(this,"audioOnlyStartTime",0);$(this,"audioOnlyTime",0);$(this,"startTopQualityTime",0);$(this,"startLowQualityTime",0);$(this,"qualitySwitchesCnt",0);$(this,"lowQualityTime",0);$(this,"topQualityTime",0);$(this,"bufferStartTime",0);$(this,"bufferingEventsCnt",0);$(this,"bufferTime",0);$(this,"playingTimeStart",0);$(this,"playingTimeStop",0);$(this,"initTime",0);$(this,"externalPlayerPlatform","");$(this,"vodSourceId","");$(this,"vodTitleId","");$(this,"vodSeasonId","");$(this,"vodEpisodeId","");$(this,"vodMediaItemId","");$(this,"hlsLevels",[]);$(this,"ctx");var a,l,c;const s=e.channelId,n=(e==null?void 0:e.mediaId)||"",i=((a=e.playbackInfo)==null?void 0:a.pbsId)||"",r=!!e.isVitrina,o=(e==null?void 0:e.vodMediaItemId)||"";if(!e.isArchive&&!n){log$9.warn("could not init TV stats, mediaId is not set");return}if(!i&&!r){log$9.warn("could not init TV stats, pbsId is not set");return}if(e.isArchive&&!o){log$9.warn("could not init TV stats, vodMediaItemId is not set");return}
37log$9.info("init",r?{channelId:s}:{channelId:s,mediaId:n,pbsId:i}),this.ctx=e.ctx,this.channelId=s,this.mediaId=n,this.vodMediaItemId=o,this.isPrograms=e.isArchive,this.isVitrina=r,this.playerId=e.playerId,this.getNetworkType(),this.languages=((l=e.playbackInfo)==null?void 0:l.languages)||[],this.playingLanguageIndex=((c=e.playbackInfo)==null?void 0:c.languageIndex)||0,this.pbsId=i,this.externalPlayerPlatform=e.externalPlayerPlatform,this.vodSourceId=(e==null?void 0:e.vodSourceId)||"",this.vodTitleId=(e==null?void 0:e.vodTitleId)||"",this.vodSeasonId=(e==null?void 0:e.vodSeasonId)||"",this.vodEpisodeId=(e==null?void 0:e.vodEpisodeId)||""}get eventDuration(){return Math.round(this.elapsedTime/1e3)}get startTime(){return this.playingTimeStart===0?this.elapsedTime:this.playingTimeStart-this.initTime}get elapsedTime(){return this.playingTimeStop-this.initTime}get playingTime(){return this.playingTimeStart===0?0:this.playingTimeStop-this.playingTimeStart-this.bufferTime}get averageFragsKbps(){return Math.round(this.commonSizeFragsKbps/this.commonTimeFragsLoadingSeconds)||0}get isPlayingStarted(){return this.playingTimeStart>0}get nativePlayerVersion(){const e=getUserAgent(this.ctx);return`${getBrowserName(e)} ${getBrowserVersion(e)}`}initPlaying(){this.resetStats(),this.initTime=Date.now(),log$9.info("initPlaying",{initTime:new Date(this.initTime)})}startPlaying(e,s,n=!1){this.playingTimeStart=Date.now(),this.playbackTime=s,this.isLive=n,this.dvrDelayMs=e,log$9.info("startPlaying",{dvrDelayMs:e,isLive:n,startTime:this.startTime,playbackTime:s}),getIsFullscreen()?this.startFullScreen():(this.stopFullScreen(),this.startWindowedScreen())}stopPlaying(e=!1){this.initTime&&(this.playingTimeStop=Date.now(),this.isPlaybackAborted=e,this.playIntervalNum++,log$9.info("stopPlaying"),this.stopBuffer(),this.stopFullScreen(),this.stopWindowedScreen(),this.stopLowQuality(),this.stopTopQuality(),this.sendStatistics(),this.resetStats())}addHlsLevels(e){this.hlsLevels=e}startFullScreen(){this.stopWindowedScreen(),this.stopAudioOnly(),this.fullScreenStartTime=Date.now()}stopFullScreen(){this.fullScreenStartTime&&(this.fullScreenTime+=Date.now()-this.fullScreenStartTime,this.fullScreenStartTime=0)}startAudioOnly(){this.stopWindowedScreen(),this.stopFullScreen(),this.audioOnlyStartTime=Date.now()}stopAudioOnly(){this.audioOnlyStartTime&&(this.audioOnlyTime+=Date.now()-this.audioOnlyStartTime,this.audioOnlyStartTime=0)}startWindowedScreen(){this.stopFullScreen(),this.stopAudioOnly(),this.windowedStartTime=Date.now()}stopWindowedScreen(){this.windowedStartTime&&(this.windowedTime+=Date.now()-this.windowedStartTime,this.windowedStartTime=0)}setPlayingLanguageIndex(e){this.playingLanguageIndex=e}setPlayingRenditionIndex(e){this.playingRenditionIndex=e}startBuffer(){this.isPlayingStarted&&this.bufferStartTime===0&&(this.bufferingEventsCnt++,this.bufferStartTime=Date.now())}stopBuffer(){this.bufferStartTime&&this.isPlayingStarted&&(this.bufferTime+=Date.now()-this.bufferStartTime,this.bufferStartTime=0)}addFrag(e){const s=e.size*.008,n=e.time*.001,i=Math.round(s/n);this.commonSizeFragsKbps+=s,this.commonTimeFragsLoadingSeconds+=n,this.minimalFragsKbps=this.minimalFragsKbps?Math.min(this.minimalFragsKbps,i):i}resetStats(){this.initTime=0,this.fullScreenStartTime=0,this.bufferingEventsCnt=0,this.fullScreenTime=0,this.windowedTime=0,this.topQualityTime=0,this.lowQualityTime=0,this.bufferTime=0,this.bufferStartTime=0,this.playingTimeStart=0,this.playingTimeStop=0,this.windowedStartTime=0,this.commonSizeFragsKbps=0,this.audioOnlyTime=0,this.commonTimeFragsLoadingSeconds=0,this.minimalFragsKbps=0,this.isPlaybackAborted=!1}startLowQuality(){this.startLowQualityTime=Date.now()}stopLowQuality(){this.startLowQualityTime&&(this.lowQualityTime+=Date.now()-this.startLowQualityTime,this.startLowQualityTime=0)}startTopQuality(){this.startTopQualityTime=Date.now()}stopTopQuality(){this.startTopQualityTime&&(this.topQualityTime+=Date.now()-this.startTopQualityTime,this.startTopQualityTime=0)}changeQuality(e){this.isPlayingStarted&&this.qualitySwitchesCnt++,this.startLowQualityTime?this.stopLowQuality():this.startTopQualityTime&&this.stopTopQuality();const s=this.hlsLevels[e];if(s){const n=this.hlsLevels.map(o=>o.bitrate),i=max(n)===s.bitrate,r=min(n)===s.bitrate;i?this.startTopQuality():r&&this.startLowQuality()}}getNetworkType(){const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;e&&(this.connectionType=(CONNECTION_TYPE==null?void 0:CONNECTION_TYPE[(e==null?void 0:e.type)||""])||void 0)}prepareData(){return this.isVitrina?this.prepareDataVitrina():this.prepareDataRegular()}prepareDataVitrina(){return{ChannelId:this.channelId,PlaybackTime:this.playbackTime,EventDuration:this.eventDuration}}prepareDataRegular(){var r;const e=(r=this.languages[this.playingLanguageIndex])==null?void 0:r.renditions[this.playingRenditionIndex],s=this.languages[this.playingLanguageIndex],n=this.playerId===PLAYER_ID.hls?Hls.version:this.nativePlayerVersion,i={ChannelId:this.channelId,MediaId:this.mediaId,PbsId:this.pbsId,VodMedia
37ItemId:this.vodMediaItemId,VodSourceId:this.vodSourceId,VodTitleId:this.vodTitleId,VodSeasonId:this.vodSeasonId,VodEpisodeId:this.vodEpisodeId,IsPrograms:this.isPrograms,IsLive:this.isLive,PlayerId:this.playerId,PlayerVersion:n,DvrDelayMs:this.dvrDelayMs,LanguageId:(s==null?void 0:s.id)||"",IsLanguageDefault:s==null?void 0:s.default,RenditionId:e.id,IsRenditionDefault:e.default,BufferingEventsCnt:this.bufferingEventsCnt,ErrorEventsCnt:this.errorEventsCnt,PlayIntervalNum:this.playIntervalNum,EventDuration:this.eventDuration,PlaybackTime:this.playbackTime,RebufferingTimeMs:this.bufferTime,ElapsedTimeMs:this.elapsedTime,PlayingTimeMs:this.playingTime,StartTimeMs:this.startTime,AudioOnlyTimeMs:this.audioOnlyTime,SystemMiniplayerTimeMs:this.systemMiniplayerTimeMs,SecondScreenTimeMs:this.secondScreenTimeMs,QualitySwitchesCnt:this.qualitySwitchesCnt,LowQualityTimeMs:this.lowQualityTime,TopQualityTimeMs:this.topQualityTime,WindowedTimeMs:this.windowedTime,FullScreenTimeMs:this.fullScreenTime,IsPlaybackAborted:this.isPlaybackAborted};return this.playerId!==PLAYER_ID.native&&(this.averageFragsKbps>0&&(i.AverageEstimatedBandwidthKbps=this.averageFragsKbps),this.minimalFragsKbps>0&&(i.MinimumEstimatedBandwidthKbps=this.minimalFragsKbps)),this.connectionType&&(i.ConnectionType=this.connectionType),i}checkData(){return Date.now()-this.initTime<CHANNEL_PLAYING_STATISTIC_SAFE_TIME_IN_SECONDS*1e3||this.initTime===0?!1:this.startTime<0?(log$9.warn("unable sendStatistics, incorrect startTime:",this.startTime),!1):this.playingTime<0?(log$9.warn("unable sendStatistics, incorrect playingTime:",this.playingTime),!1):!0}sendStatistics(){if(!this.checkData())return;const e=this.prepareData();try{log$9.info("sendStatistics"),sendStatistics(this.ctx,e,this.externalPlayerPlatform)}catch(s){log$9.error(s)}}}const log$8=logger$1("player-tv-stats"),usePlayerStats=()=>{const t=useSSRContext(),e=useStore(),s=useEvents(),n=ref(null),{currentMediaItemId:i}=useVod(),r=computed(()=>selectors.player.isPlayingSelector(e)),o=computed(()=>selectors.player.isFullscreenSelector(e)),a=computed(()=>selectors.player.playingChannelSelector(e)),l=computed(()=>selectors.player.playingChannelIdSelector(e)),c=computed(()=>selectors.playerPlayingChannel.languageIndexSelector(e)),d=computed(()=>selectors.playerPlayingChannel.renditionIndexSelector(e)),u=computed(()=>selectors.playerPlayingChannel.renditionSelector(e)),h=computed(()=>selectors.playerPlayingChannel.hasVitrinaSelector(e)),f=computed(()=>e.player.type),g=(O,N="",H)=>{var w,k,F;const W=selectors.player.playbackInfoSmotreshkaSelector(e),M=selectors.vod.archiveTitlePlaybackMethodSelector(e);if(!a.value||!W&&!H){log$8.warn("Unable to init player stats",{playbackInfo:W});return}const A={ctx:t,channelId:l.value,isArchive:f.value==="archive"||(M==null?void 0:M.name)===PLAYBACK_METHODS.smotreshkaPlaybackInfo,externalPlayerPlatform:N,playerId:O||"hls",playbackInfo:W};f.value==="archive"?(A.vodMediaItemId=i.value,A.vodEpisodeId=selectors.player.playingEpisodeIdSelector(e),A.vodSourceId=selectors.player.playingSourceIdSelector(e),A.vodTitleId=selectors.player.playingTitleIdSelector(e),A.vodSeasonId=selectors.player.playingSeasonIdSelector(e)):f.value==="tv"&&(A.mediaId=(F=(k=(w=a.value)==null?void 0:w.medias)==null?void 0:k[0])==null?void 0:F.id,A.isVitrina=H),n.value=new PlayerStats(A),m()},p=()=>{n.value=null,v()},m=()=>{s.on(EVENTS.player.changeLevel,S),s.on(EVENTS.player.loadFrag,y),s.on(EVENTS.player.manifestLoaded,C)},v=()=>{s.off(EVENTS.player.changeLevel,S),s.off(EVENTS.player.loadFrag,y),s.off(EVENTS.player.manifestLoaded,C)},S=O=>{u.value.id==="Auto"&&n.value&&n.value.changeQuality(O)},y=O=>{var N;(N=n.value)==null||N.addFrag(O)},C=O=>{var N;(N=n.value)==null||N.addHlsLevels(O)},E=(O,N,H=!1)=>{var W,M,A,w,k,F;r.value&&document.visibilityState==="hidden"?((W=n.value)==null||W.stopPlaying(),h.value||((M=n.value)==null||M.initPlaying(),(A=n.value)==null||A.startPlaying(O,N,H),(w=n.value)==null||w.startAudioOnly())):r.value&&document.visibilityState==="visible"&&!h.value&&(o.value?(k=n.value)==null||k.startFullScreen():(F=n.value)==null||F.startWindowedScreen())},L=(O,N,H=!1)=>{var W,M,A,w,k;r.value&&document.visibilityState==="hidden"&&!h.value?((W=n.value)==null||W.stopPlaying(),f.value==="tv"&&((M=n.value)==null||M.startPlaying(O,N,H),(A=n.value)==null||A.startAudioOnly())):r.value&&document.visibilityState==="visible"&&!h.value&&(o.value?(w=n.value)==null||w.startFullScreen():(k=n.value)==null||k.startWindowedScreen())},T=()=>{var O,N;if(n.value&&!n.value.isPlayingStarted){const H=selectors.appInfo.serverTimeSelector(e),W=selectors.player.playingTimeSelector(e),M=Math.max(0,H-W);(O=n.value)==null||O.startPlaying(Math.round(M),Math.round(W),o.value)}(N=n.value)==null||N.stopBuffer()},b=()=>{var O;r.value&&((O=n.value)==null||O.startBuffer())},_=(O=!1)=>{var N;(N=n.value)==null||N.stopPlaying(O)},I=()=>{var O;(O=n.value)==null||O.initPlaying()},P=(O,N,H=!1)=>{var W;(W=n.value)==null||W.startPlaying(O,N,H)},R=()=>{n.value&&n.value.errorEventsCnt++},D=()=>{var O,N;getIsFullscreen()?r.value&&((N=n.value)==null||N.startWindowedScreen()):r.value&&((O=n.value)==null||O.startFullScreen())};return watch(c,O=>{var N;(N=n.value)==null||N.setPlayingLanguageIndex(O)}),watch(d,O=>{var N;(N=n.value)==null||N.setPlayingRenditionIndex(O)}
37),{init:g,stopPlaying:_,destroy:p,initPlaying:I,startPlaying:P,updateErrorCounter:R,sendStatisticsOnSessionEnd:E,sendStatisticsOnCloseTab:L,onCanplay:T,onWaiting:b,actualizeFullscreen:D}},DEFAULT_PLAYBACK_SESSION_CONTEXT={pbsId:"",createdAt:"",nowTimestamp:"",updateInSec:0,expireInSec:0,pbsContextToken:""},usePlaybackSession=()=>{const t=useSSRContext(),e=useStore(),s=useEvents(),n=ref(""),i=ref(""),r=ref(""),o=[];let a=0,l=0,c=0,d=0,u=0,h=0,f=VOD_SESSION_STATE.stopped,g=Date.now(),p=!1,m=!1,v=0;const S=ref(!1),y=ref(!1);let C=!0,E=!1,L,T,b=[],_=0;const I=computed(()=>e.player.playbackSessionContext),P=computed(()=>selectors.player.isMinimizedSelector(e)),R=computed(()=>selectors.player.isFullscreenSelector(e)),D=computed(()=>R.value?VIDEO_DISPLAY_MODE.fullscreen:P.value&&!R.value||r.value==="hidden"?VIDEO_DISPLAY_MODE.audioOnly:VIDEO_DISPLAY_MODE.windowed),O=computed(()=>e.player.playing.titleId),N=computed(()=>e.player.playing.episodeId),H=()=>{I.value&&(S.value=!1,u=Date.now(),p=!1,n.value=O.value,i.value=N.value,y.value=!0)},W=()=>{var q;return!!((q=I.value)!=null&&q.pbsId)&&!S.value&&!p&&y.value},M=async()=>{r.value=document.visibilityState,await w(VOD_SESSION_USER_EVENT.displayMode)},A=()=>{e.player.playbackSessionContext=DEFAULT_PLAYBACK_SESSION_CONTEXT,ne()},w=async(q,te=!1,se=!1)=>{!W()||o.length>VOD_SESSION_QUEUE_LIMIT||(S.value=te,ne(),o.push(J(q,se)),await k())},k=async()=>{if(m||p)return;const q=o.pop();q&&(m=!0,await ae(q))},F=()=>{const q=b.reduce((te,se)=>{let re=0;return se.requestData.backwardSeekSec?re=se.requestData.backwardSeekSec:se.requestData.forwardSeekSec&&(re=se.requestData.forwardSeekSec),te+re},0);o.push({...b[b.length-1],requestData:{...b[b.length-1].requestData,backwardSeekSec:q<0?Math.abs(q):0,forwardSeekSec:q>0?q:0}}),b=[]},B=async()=>{if(Date.now()-_<VOD_SESSION_SEEK_EVENTS_TIMEOUT){_=Date.now(),b.push(J(VOD_SESSION_USER_EVENT.timeline)),T&&clearTimeout(T),T=setTimeout(async()=>{b.length&&F(),ne(),await k()},VOD_SESSION_SEEK_EVENTS_TIMEOUT);return}await w(VOD_SESSION_USER_EVENT.timeline)},K=()=>{E=!0,a=Date.now()},G=()=>{a&&(l+=Date.now()-a,a=0,E=!1)},U=()=>{c=Date.now()},Y=()=>{c&&(d+=Date.now()-c,c=0)},J=(q,te=!1)=>{var Se;q===VOD_SESSION_USER_EVENT.stop&&(C=!0),q===VOD_SESSION_USER_EVENT.start&&(C=!1),E&&G(),!E&&f!==VOD_SESSION_STATE.paused&&Y();let se=VOD_SESSION_STATE.playing;C&&(se=VOD_SESSION_STATE.paused),(C&&S.value||C&&f===VOD_SESSION_STATE.stopped)&&(se=VOD_SESSION_STATE.stopped);const re=q===VOD_SESSION_USER_EVENT.start?0:l/1e3||0,me=q===VOD_SESSION_USER_EVENT.start?0:d/1e3||0,ce=C&&f===VOD_SESSION_STATE.paused&&Date.now()-g>VOD_SESSION_LIFETIME;let ie=!1;(E||ce||te)&&(ie=!0);let Ce=0,_e=0;const he=e.player.video.playingTime||0;return q===VOD_SESSION_USER_EVENT.timeline&&(v<he&&(Ce=he-v),v>he&&(_e=he-v)),v=he,{requestData:{pbsContextToken:((Se=I.value)==null?void 0:Se.pbsContextToken)||"",currentState:se,previousState:f,loadingNewState:ie,currentPositionSec:he,forwardSeekSec:Ce,backwardSeekSec:_e,totalTimeSec:(Date.now()-u)/1e3,videoDisplayMode:D.value,playedTimeSec:me,playErrorsCnt:h,bufferingTimeSec:re},close_pbs:S.value||ce,eventType:q}},z=async()=>{await w(VOD_SESSION_USER_EVENT.start)},le=async q=>{await w(VOD_SESSION_USER_EVENT.stop,q==null?void 0:q.destroy,q==null?void 0:q.loadingNewState)},ae=async q=>{if(I.value)try{const te=await postVodPlaybackUpdate(I.value.pbsId,q==null?void 0:q.close_pbs,{languageCode:e.languageCode,ctx:t,data:q==null?void 0:q.requestData});m=!1,te&&await Q(te,q==null?void 0:q.requestData,q==null?void 0:q.eventType)}catch(te){m=!1,te.resStatus===HTTP_CODES.BAD_REQUEST&&(A(),p=!0)}},ue=()=>{var q;L=setTimeout(async()=>{W()&&await ae(J(VOD_SESSION_USER_EVENT.continue))},(((q=I.value)==null?void 0:q.updateInSec)||0)*1e3)},ne=()=>{L&&clearTimeout(L)},Q=async(q,te,se="")=>{h=0,f=(te==null?void 0:te.currentState)||"";const re=Date.now();if(u=re,E?(K(),c=0):c&&(a=0,c=re),se===VOD_SESSION_USER_EVENT.stop&&(g=re),se===VOD_SESSION_USER_EVENT.start&&(g=re,S.value=!1),_=0,q&&!S.value)if(e.player.playbackSessionContext=preparePlaybackSessionContext(q),o.length===0){if(C&&Date.now()-g>VOD_SESSION_LIFETIME){A();return}ue()}else await k();else A()};return watch(()=>e.player.minimized,async()=>{await M()}),onMounted(()=>{window.addEventListener("visibilitychange",M),s.on(EVENTS.player.seek,B)}),onUnmounted(()=>{window.removeEventListener("visibilitychange",M),s.off(EVENTS.player.seek,B)}),{isSessionError:p,prevTitleId:n,prevEpisodeId:i,init:H,start:z,stop:le,bufferStart:K,bufferStop:G,playingStart:U,playingStop:Y,timeline:B,actualizeDisplayMode:M,checkSession:W}},lastSavePauseCallTime=ref(void 0),usePauses=()=>{const t=useStore(),e=computed(()=>{var n,i;return((i=(n=t.siteConfig)==null?void 0:n.pauses)==null?void 0:i.autosaveInterval)||600});return{lastSavePauseCallTime,isItTimeToSavePause:n=>!lastSavePauseCallTime.value||Math.abs(n-lastSavePauseCallTime.value)>=e.value}},parseType=t=>{let e="";return e+=String.fromCharCode(t[0]),e+=String.fromCharCode(t[1]),e+=String.fromCharCode(t[2]),e+=String.fromCharCode(t[3]),e},nalParse=t=>{const e=new DataView(t.buffer,t.byteOffset,t.byteLength),s=[];let n;for(let i=0;i<t.length;i+=n)switch(n=e.getUint32(i),i+=4,t[i]&31){case 1:s.push("NDR");break;case 5:s.push("IDR");break;case 6:s.push("SEI");break;case 7:s.push("SPS");break;case 8:s.push("PPS");break;case 9:s.push("AUD");break;default:s.push(t[i]&31);break}return s},parse={mdat(t){return{byteLength:t.byteLength,nals:nalParse(t)}}},mp4toJSON=t=>{const e=[],s=new DataView(t.buffer,t.byteOffset,t.byteLength);let n=0,i,r,o,a;for(;n<t.byteLength;)i=s.getUint32(n),r=parseType(t.subarray(n+4,n+8)),o=i>1?n+i:t.byteLength,a=(parse[r]||(l=>({data:l})))(t.subarray(n+8,o)),a.size=i,a.type=r,e.push(a),n=o;return e},log$7=logger$1("hls"),MAX_RELOAD_ATTEMPTS=3,useHls=t=>{const e=useStore(),s=useUa(),{t:n}=useTranslation(),i=useEvents(),r=ref(!1),o=ref(0),a=ref(!0);let l="",c;const d={debug:storage.get("__debug_hls__")===1,manifestLoadPolicy:{default:{maxTimeToFirstByteMs:2e3,maxLoadTimeMs:5e3,timeoutRetry:{maxNumRetry:5,retryDelayMs:100,maxRetryDelayMs:1e3},errorRetry:{maxNumRetry:5,retryDelayMs:1e3,maxRetryDelayMs:4e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:2e3,maxLoadTimeMs:2e3,timeoutRetry:{maxNumRetry:5,retryDelayMs:100,maxRetryDelayMs:1e3},errorRetry:{maxNumRetry:5,retryDelayMs:1e3,maxRetryDelayMs:4e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:2e3,maxLoadTimeMs:1e4,timeoutRetry:{maxNumRetry:5,retryDelayMs:100,maxRetryDelayMs:1e3},errorRetry:{maxNumRetry:5,retryDelayMs:1e3,maxRetryDelayMs:4e3}}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:2e3,maxLoadTimeMs:2e3,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:4e3,backoff:"linear"},errorRetry:{maxNumRetry:4,retryDelayMs:1e3,maxRetryDelayMs:4e3,backoff:"linear"}}}
37,certLoadPolicy:{default:{maxTimeToFirstByteMs:2e3,maxLoadTimeMs:2e3,timeoutRetry:null,errorRetry:null}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:2e3,maxLoadTimeMs:4e3,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:4e3}}}};let u;const h=async T=>{var _;const b=((_=t.value)==null?void 0:_.currentTime)||0;await f(),b&&t.value&&(t.value.currentTime=b),log$7.debug("init"),u=new Hls(d),actions.player.clearError(e),await g(T),t.value&&u.attachMedia(t.value)},f=async()=>{u&&(log$7.debug("destroy"),u.destroy()),l="",r.value=!1},g=async T=>{var P;if(!u)return;let b=1;const _=(P=selectors.playerPlayingChannel.renditionSelector(e))==null?void 0:P.id,I=typeof _=="string"&&_.toLowerCase()==="max";u.on(Hls.Events.BUFFER_APPENDING,(R,D)=>{var O,N;if(D.type==="video"){i.emit(EVENTS.player.loadFrag,{time:D.frag.stats.loading.end-D.frag.stats.loading.start,size:D.frag.stats.loaded});const H=navigator.userAgent.includes(BROWSERS.chrome);if(b===2&&D.data&&I&&H){const W=(O=mp4toJSON(D.data))==null?void 0:O[1];W&&!((N=W.nals)!=null&&N.includes("IDR"))&&E()}b++}}),u.on(Hls.Events.MANIFEST_LOADED,(R,D)=>{i.emit(EVENTS.player.manifestLoaded,[...D.levels.map(H=>({bitrate:H.bitrate}))]);const O=(D==null?void 0:D.subtitles)||[],N=!!(O!=null&&O.length);if(log$7.debug(`MANIFEST_LOADED. hasSubtitles: ${N}`),actions.player.setHasSubtitles(e,N),u&&N){const H=selectors.player.subtitleDisplaySelector(e);u.subtitleDisplay=H,u.subtitleTrack=H?0:-1}}),u.on(Hls.Events.MEDIA_ATTACHED,()=>{log$7.debug("MEDIA_ATTACHED. Video html-element was attached to hls"),u.loadSource(T)}),u.on(Hls.Events.MANIFEST_PARSED,()=>{log$7.debug("MANIFEST_PARSED. Video URL was loaded to hls"),r.value=!0}),u.on(Hls.Events.LEVEL_SWITCHED,(R,D)=>{i.emit(EVENTS.player.changeLevel,D.level)}),u.on(Hls.Events.ERROR,m)},p=T=>c=T,m=async(T,b)=>{let _=b.fatal;const I=b.response,P=I==null?void 0:I.code,R=HTTP_PLAYER_BAD_RESPONSE_CODES.includes(P),D=b.type===Hls.ErrorTypes.NETWORK_ERROR,O=b.details===Hls.ErrorDetails.MANIFEST_PARSING_ERROR;if(_=D&&(R||O)||_,D&&P===403&&o.value<=MAX_RELOAD_ATTEMPTS){await y(P);return}if(c&&c({fatal:_}),_){log$7.error("HLS ERROR ",T,b);const H=[Hls.ErrorDetails.BUFFER_NUDGE_ON_STALL],W=selectors.player.isFullscreenSelector(e);!H.includes(b.details)&&W&&actions.player.exitFullscreen(e)}else log$7.warn("HLS WARNING ",T,b)},v=async T=>{if(!t.value){log$7.info("refVideo is not ready yet");return}T!==l&&(await h(T),l=T),a.value||(u==null||u.startLoad(t.value.currentTime),a.value=!0),await t.value.play()},S=async()=>{u==null||u.stopLoad(),a.value=!1,t.value.pause()},y=async T=>{try{log$7.info("Chunk load returns 403, maybe network has been changed... Reloading stream. Attempt",o.value),o.value++,l&&(await S(),await f(),c&&c({fatal:!1,responseCode:T}))}catch{}},C=()=>{u&&(u.subtitleDisplay=!u.subtitleDisplay,u.subtitleTrack=u.subtitleDisplay?0:-1)},E=()=>{getBrowserName(s)!==BROWSERS.firefox&&(actions.player.showOverlay(e),actions.player.setAlert(e,n("player_tv_max_quality_error")),actions.playerPlayingChannel.setRenditionIndex(e,0),i.emit(EVENTS.player.reloadStream,{isProgrammatic:!0}),log$7.error("max quality error"))};return{ready:r,play:v,pause:S,destroy:f,setOnError:p,toggleSubtitles:C,selectAudioTrack:T=>{log$7.warn(`Cannot proccess selected audioTrack index=${T}. Only TV-player supports multiple audio tracks for HLS at the moment`)}}},log$6=logger$1("shaka");let Shaka;const useShaka=t=>{const e=useStore(),s=useUa(),n=useSSRContext(),i=ref(!1),r=ref(null);let o,a="";const l=computed(()=>selectors.player.isVodSelector(e)),c=computed(()=>selectors.player.playbackMethodSelector(e)),d=computed(()=>selectors.player.playbackInfoAmediaSelector(e)),u=computed(()=>selectors.player.playbackInfoMegogoSelector(e)),h=computed(()=>selectors.player.audioTracksSelector(e)),f=computed(()=>selectors.player.playingTimeSelector(e)),g=async()=>{await m(),actions.player.clearError(e);const T=["localhost","0.0.0.0"].includes(window.location.hostname);if(window.location.protocol!=="https:"&&!T){const b=useHttpsProtocol(window.location.href);
37throw new Error(`Unable to play DRM because the protocol is not secure (http), try ${b}`)}Shaka||(window.muxjs=(await __vitePreload(async()=>{const{default:b}=await import("./mux.js-D3y-SZzd.js").then(_=>_.i);return{default:b}},__vite__mapDeps([0,1]))).default,Shaka=(await __vitePreload(async()=>{const{default:b}=await import("./shaka-player.ui-BEvA4ZG6.js").then(_=>_.s);return{default:b}},__vite__mapDeps([2,1]))).default);try{const b={drm:{servers:{},advanced:{"com.widevine.alpha":{videoRobustness:["SW_SECURE_CRYPTO"],audioRobustness:["SW_SECURE_CRYPTO"]}}}},_=selectors.player.playingUrlSelector(e,n);d.value?(b.drm.servers["com.apple.fps"]=d.value.laFairplay,b.drm.servers["com.widevine.alpha"]=d.value.laWidevine,b.drm.servers["com.microsoft.playready"]=d.value.laPlayready,b.drm.advanced["com.apple.fps"]={},b.drm.advanced["com.apple.fps"].serverCertificateUri=d.value.fpsCertificate):u.value&&(b.drm.servers["com.apple.fps"]=u.value.license_server,b.drm.servers["com.widevine.alpha"]=u.value.license_server,b.drm.servers["com.microsoft.playready"]=u.value.license_server,b.drm.advanced["com.apple.fps"]={},b.drm.advanced["com.apple.fps"].serverCertificateUri=u.value.wvls),log$6.info("initShaka",b);const I=new Shaka.Player;if(t!=null&&t.value&&await I.attach(t.value),r.value=I,I.configure(b),p(),_){await I.load(_);const P=I.getTextTracks();actions.player.setHasSubtitles(e,!!(P!=null&&P.length));const R=selectors.player.subtitleDisplaySelector(e);if(P.length>0&&R&&r.value.setTextTrackVisibility(!0),l.value&&c.value===PLAYBACK_METHODS.amedia2V1){const D=I.getAudioLanguages();if(D.length>1){const O=selectors.player.playbackInfoAmediaSelector(e);O&&(O.audioTracks=D);const N=storage.get(STORE_KEYS.player.audioTrackAmedia);let H=D.findIndex(W=>W===N);H=H>=0?H:0,H!==0&&H===selectors.vod.audioTrackIndexSelector(e)?L(H):actions.vod.setAudioTrackIndex(e,H)}}}else log$6.error("playingUrlSelector did not return a proper URL")}catch(b){const _=Shaka.util.Error.Code,I=Object.keys(_).find(P=>_[P]===b.code);throw log$6.error("unable to init",I,b),b}},p=()=>{const T=r.value;if(!T)return;let b=0;T.addEventListener("segmentappended",()=>{b++,b>=2&&selectors.player.isLoadingSelector(e)&&actions.player.stopLoading(e)}),T.addEventListener("error",S)},m=async()=>{r.value&&(log$6.info("destroyShaka"),await r.value.destroy()),r.value=null,a="",i.value=!1},v=T=>o=T,S=async T=>{var P,R,D,O;log$6.error("shakaError",T.detail||T);const b=PLAYER_ERROR_CODES.INTERNAL,_=(R=(P=T.detail)==null?void 0:P.data)==null?void 0:R[2],I={};getBrowserFlags(s).isYandex&&(!((D=T.detail)!=null&&D.code)||((O=T.detail)==null?void 0:O.code)>=6e3)&&(I.askUserToUpdateBrowser=!0),actions.player.setError(e,b,_,0,I),o&&o(T),actions.player.stopLoading(e),await C()},y=async T=>{if(!t.value){log$6.info("refVideo is not ready yet");return}T!==a&&(await g(),a=T,t.value.currentTime=f.value),await t.value.play()},C=async()=>{t.value.pause()},E=T=>{r.value&&(log$6.info("shaka.setTextTrackVisibility (subtitles) has been set to",T),r.value.setTextTrackVisibility(T))},L=T=>{l.value&&r.value&&T>=0&&c.value===PLAYBACK_METHODS.amedia2V1&&(r.value.selectAudioLanguage(h.value[T].id.toString(),"audio"),log$6.info("shaka.selectAudioLanguage (audio track) has been set to",h.value[T].id))};return{ready:i,play:y,pause:C,destroy:m,setOnError:v,toggleSubtitles:E,selectAudioTrack:L}},log$5=logger$1("drm-fairplay-native"),FAIRPLAY_KEY_SYSTEM="com.apple.fps.1_0",stringToUint16Array=t=>{const e=new ArrayBuffer(t.length*2),s=new Uint16Array(e);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s},base64DecodeUint8Array=t=>{const e=window.atob(t),s=e.length,n=new Uint8Array(new ArrayBuffer(s));for(let i=0;i<s;i++)n[i]=e.charCodeAt(i);return n},base64EncodeUint8Array=t=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let s="",n,i,r,o,a,l,c,d=0;for(;d<t.length;)n=t[d++],i=d<t.length?t[d++]:Number.NaN,r=d<t.length?t[d++]:Number.NaN,o=n>>2,a=(n&3)<<4|i>>4,l=(i&15)<<2|r>>6,c=r&63,isNaN(i)?l=c=64:isNaN(r)&&(c=64),s+=e.charAt(o)+e.charAt(a)+e.charAt(l)+e.charAt(c);return s},useDrmFairplayNative=t=>{let e=null;const s=[];let n=0;const i=useStore(),r=computed(()=>selectors.player.playbackInfoMegogoSelector(i)),o=computed(()=>{var S;return(S=r.value)==null?void 0:S.license_server}),a=computed(()=>{var S;return(S=r.value)==null?void 0:S.license_certificate}),l=computed(()=>
37{if(selectors.player.playbackMethodSelector(i)===PLAYBACK_METHODS.megogoV1&&o.value){const y=new URL(o.value);return y.searchParams.has("contentId")&&y.searchParams.get("responseType")==="rawckc"}return!1}),c=async()=>{if(a.value)try{const S=await axios.get(a.value,{responseType:"arraybuffer"});e=S.data?new Uint8Array(S.data):null}catch(S){log$5.error(S)}},d=()=>{var S;(S=t.value)==null||S.addEventListener("webkitneedkey",h,!1)},u=()=>{var S;(S=t.value)==null||S.removeEventListener("webkitneedkey",h,!1)},h=S=>{const y=new Date().getTime();s.push(S),y-n>200&&setTimeout(async()=>{await f(s[s.length-1])},200),n=y},f=async S=>{const y=g(S.initData);try{await p({cert:e,initData:S.initData,contentId:y,licenseUri:o.value})}catch(C){log$5.error(C)}},g=S=>{const y=String.fromCharCode.apply(null,S),C=String.fromCharCode.apply(null,new Uint16Array(S.buffer)).substring(2),E=C.indexOf("skd://")===0?C:y;return new URL(E).hostname},p=({contentId:S,initData:y,cert:C,licenseUri:E})=>new Promise((L,T)=>{var _;if(!t.value){T(Error("Video tag is not ready"));return}if(t.value.webkitKeys||t.value.webkitSetMediaKeys(new window.WebKitMediaKeys(FAIRPLAY_KEY_SYSTEM)),!((_=t.value)!=null&&_.webkitKeys)){T(Error("Could not create MediaKeys"));return}const b=t.value.webkitKeys.createSession("video/mp4",v({id:S,initData:y,cert:C}));if(!b){T(Error("Could not create key session"));return}b.contentId=S,b.addEventListener("webkitkeymessage",async I=>{try{const P=await m(E,I);if(!P.data.ckc_message){T(Error("invalid fairplay response"));return}const R=P.data.ckc_message,D=base64DecodeUint8Array(R);return b.update(D)}catch(P){log$5.error(P),T(P)}}),b.addEventListener("webkitkeyadded",I=>{log$5.debug("Key added"),L(I)}),b.addEventListener("webkitkeyerror",I=>{log$5.error("drm.webkitkeyerror",I),T(I)})}),m=(S,y)=>{const C=y.message,E=new URL(S);return E.searchParams.delete("responseType"),axios.post(E.toString(),JSON.stringify({content_id:E.searchParams.get("contentId"),spc_message:base64EncodeUint8Array(C)}),{responseType:"json",headers:{"Content-type":"application/json"}})},v=({initData:S,id:y,cert:C})=>{typeof y=="string"&&(y=stringToUint16Array(y));let E=0;const L=new ArrayBuffer(S.byteLength+4+y.byteLength+4+C.byteLength),T=new DataView(L);new Uint8Array(L,E,S.byteLength).set(S),E+=S.byteLength,T.setUint32(E,y.byteLength,!0),E+=4;const _=new Uint16Array(L,E,y.length);return _.set(y),E+=_.byteLength,T.setUint32(E,C.byteLength,!0),E+=4,new Uint8Array(L,E,C.byteLength).set(C),new Uint8Array(L,0,L.byteLength)};return{isSupported:l,init:c,bindEvents:d,unbindEvents:u}},log$4=logger$1("native"),useNative=t=>{const e=useStore(),s=ref(!1),n=ref(null),i=useDrmFairplayNative(t),r=async()=>{t.value&&(t.value.src=""),l()},o=async()=>{var S,y,C,E,L;log$4.debug("init"),a();const m=!!((y=(S=t.value)==null?void 0:S.textTracks)!=null&&y.length);actions.player.setHasSubtitles(e,m);const v=selectors.player.subtitleDisplaySelector(e);m&&v&&((L=(E=(C=t.value)==null?void 0:C.textTracks)==null?void 0:E[0])!=null&&L.mode)&&(t.value.textTracks[0].mode="showing"),i.isSupported.value&&await i.init()},a=()=>{var m,v;(m=t.value)==null||m.addEventListener("play",h),(v=t.value)==null||v.addEventListener("pause",f),i.bindEvents()},l=()=>{var m,v;(m=t.value)==null||m.removeEventListener("play",h),(v=t.value)==null||v.removeEventListener("pause",f),i.unbindEvents()},c=m=>m,d=async m=>{if(!t.value){log$4.info("refVideo is not ready yet");return}s.value||await o(),m!==t.value.src&&(t.value.src=m),s.value=!0,await t.value.play()},u=async()=>{t.value.pause()},h=()=>{log$4.info("Player event -> PLAYING"),n.value&&clearTimeout(n.value)},f=async()=>{log$4.trace("Player event -> PAUSE"),n.value&&clearTimeout(n.value)};return{ready:s,play:d,pause:u,destroy:r,setOnError:c,toggleSubtitles:m=>{var v,S,y;(y=(S=(v=t.value)==null?void 0:v.textTracks)==null?void 0:S[0])!=null&&y.mode&&(m?(t.value.textTracks[0].mode="showing",log$4.info("textTrack mode (subtitles) for native video player has been set to showing")):(t.value.textTracks[0].mode="hidden",log$4.info("textTrack mode (subtitles) for native video player has been set to hidden")))},selectAudioTrack:m=>{log$4.warn(`audioTrack with index='${m}' cannot be selected because audioTracks are not supported by native video player`)}}},log$3=logger$1("pauses"),useTvPauses=()=>{const{isAnonymous:t}=useAuth(),e=useSSRContext(),s=useStore(),{findChannelById:n}=useChannels(),i=useEpgSchedule();return{getPause:l=>{const c=n(l),d=i.getPrograms(c);if(!d.length)return;const u=d[0].scheduledFor.begin.unix();return s.pauses.tv.items.find(h=>h.time>=u&&h.channelId===l)},load:async l=>{if(t.value){log$3.error("Cannot load TV-pauses for anonymous");return}try{s.pauses.tv.items=await getTvPauses(l,{languageCode:s.languageCode,ctx:e})}catch(c){log$3.error("Load TV-pauses error:",c)}log$3.info(`TV-pauses have been loaded for channel ${l}`)},save:async(l,c)=>{const d={contentId:l,time:c,channelId:l};await saveTvPause({languageCode:s.languageCode,ctx:e,jsonData:!0,data:d})}}},hasSavedPause=t=>{var s,n;const e=(s=t==null?void 0:t.pauses)==null?void 0:s[0];if(!(e!=null&&e.id))return!1;
37if(!((n=t.preview)!=null&&n.hasSeries))return!0;if(getEpisodesForSeasonIndex(t).length)return!!getTitlePauseEpisode},getTitlePauseEpisode=t=>{var s,n,i;const e=(s=t==null?void 0:t.pauses)==null?void 0:s[0];return e?(i=(n=t.details)==null?void 0:n.episodes)==null?void 0:i.find(r=>{var o;return((o=r==null?void 0:r.preview)==null?void 0:o.id)===(e==null?void 0:e.episodeId)}):void 0},getTitlePauseSeason=t=>{var n,i;const e=(n=t.pauses)==null?void 0:n[0],s=((i=t.details)==null?void 0:i.seasons)||[];return e!=null&&e.seasonId?s.find(r=>(r==null?void 0:r.id)===e.seasonId):e!=null&&e.episodeId?s.find(r=>{var o,a,l,c;return(r==null?void 0:r.id)===((c=(l=(a=(o=t.details)==null?void 0:o.episodes)==null?void 0:a.find(d=>{var u;return((u=d==null?void 0:d.preview)==null?void 0:u.id)===e.episodeId}))==null?void 0:l.preview)==null?void 0:c.seasonId)}):void 0},getTitlePauseEpisodeName=(t,e,s)=>{var l,c,d,u,h,f,g,p,m,v,S;const n=[],i=(l=t==null?void 0:t.pauses)==null?void 0:l[0],r=((c=t==null?void 0:t.details)==null?void 0:c.episodes)||[];if(!hasSavedPause(t)||!((d=t.preview)!=null&&d.hasSeries))return"";const o=(u=getTitlePauseSeason(t))==null?void 0:u.number,a=o?`${e} ${o}`:"";if(a){n.push(a);const y=r.findIndex(T=>{var b;return((b=T.preview)==null?void 0:b.id)===(i==null?void 0:i.episodeId)}),C=(f=(h=r[y])==null?void 0:h.preview)==null?void 0:f.episodeNumber,E=((p=(g=r[y])==null?void 0:g.preview)==null?void 0:p.title)||((v=(m=getTitlePauseEpisode(t))==null?void 0:m.preview)==null?void 0:v.title);if(!E&&!C)return"";const L=E||(C?`${s} ${C}`:"");n.push(L)}else{const y=r.find(C=>{var E;return((E=C.preview)==null?void 0:E.id)===(i==null?void 0:i.episodeId)});if(!y)return"";n.push(((S=y==null?void 0:y.preview)==null?void 0:S.title)||"")}return n.join(". ")},THUMBNAILS_LOAD_DELAY=50,useThumbnails=()=>{const t=useStore(),e=ref([]),s=ref(void 0);let n=!1,i=null;const r=computed(()=>selectors.playerPlayingChannel.thumbnailsServerSelector(t));watch(r,()=>{e.value=[]});const o=async l=>{if(!!!e.value.find(u=>{const h=u[0].from,f=u[u.length-1].to;return l>=h&&l<=f})&&!n){n=!0;const u=await loadThumbnails(r.value,l);n=!1,e.value.push(u)}let d;return e.value.find(u=>(d=u.find(h=>l>=h.from&&l<h.to),!!d)),d};return{thumbnail:s,updateThumbnail:async(l,c=!1)=>{i&&clearTimeout(i);const d=l>=DateTime.timestamp();if(!r.value||d){s.value=void 0;return}c?(s.value=void 0,s.value=await o(l)):i=setTimeout(async()=>{s.value=await o(l)},THUMBNAILS_LOAD_DELAY)}}},loadScript=(t,e="head")=>new Promise(s=>{const n=document.createElement("script");n.src=t,n.onload=s,document.getElementsByTagName(e)[0].appendChild(n)}),useEpgCalendar=()=>{const t="YYYY-MM-DD",e=useEpgSchedule();return{getDates:o=>{const a=e.getPages(o).reduce((l,c)=>{const d=c.coveredInterval.begin.hour(0).minute(0).second(0),u=d.format(t);return l.set(u,{key:u,dayjs:d}),l},new Map);return Array.from(a.values())},getNowDateKey:()=>dayjs().format(t),formatToDateKey:o=>o.format(t),parseDateByKey:o=>dayjs(o,t)}},epgCalendar=useEpgCalendar(),isEpgVisible=ref(!1),isProgramInfoVisible=ref(!1),isChannelInfoVisible=ref(!0),selectedChannel=ref(null),selectedProgram=ref(null),pickedDate=ref(epgCalendar.getNowDateKey()),useFullScreenPlayer=()=>{const t=computed(()=>{var l;return(l=selectedChannel.value)==null?void 0:l.id});return{selectedChannel,selectedProgram,isEpgVisible,isProgramInfoVisible,isChannelInfoVisible,selectedChannelId:t,pickedDate,setSelectedChannel:l=>{selectedChannel.value=l},setPickedDate:l=>{pickedDate.value=l},resetPickedDate:()=>{pickedDate.value=epgCalendar.getNowDateKey()},setSelectedProgram:l=>{selectedProgram.value=l},setEpgVisible:l=>{isEpgVisible.value=l},setProgramInfoVisible:l=>{isProgramInfoVisible.value=l},setChannelInfoVisible:l=>{isChannelInfoVisible.value=l}}},useChannelDetails=()=>{const t=useRoute(),e=useStore(),s=computed(()=>{var o;return((o=t.params.channelId)==null?void 0:o.toString())||""}),n=computed(()=>selectors.tvChannels.channelByIdSelector(e,s.value)),i=computed(()=>parseRouteName(t.name).includes("channel-about")),r=computed(()=>parseRouteName(t.name).includes("channel-program"));return{channelId:s,channel:n,isChannelAboutRoute:i,isChannelProgramRoute:r}}
37,useSeo=()=>{const t=useStore();return{defaultMetaOgImage:computed(()=>{var n;const s=(n=t.cmsPages)==null?void 0:n.find(i=>i.path==="/");return s?s.dataObject.metaImages.ogFileKey:""})}},isTrailerPlaying=ref(!1),isTrailerVisible=ref(!1),isBackgroundVisible=ref(!0),isAnyVideoControlVisible=ref(!1),refTrailerVideo=ref(null),loadedMediaId=ref(""),playTimeoutId=ref(null),hideBackgroundTimeoutId=ref(null),showControlsTimeoutId=ref(null),log$2=logger$1("vod-trailer"),useVodTrailer=()=>{const t=useStore(),{currentMediaId:e}=useVod(),s=computed(()=>{var p,m;return((m=(p=t.siteConfig)==null?void 0:p.vodVideofication)==null?void 0:m.enabled)&&!!e.value}),n=()=>document.documentElement.clientWidth<=MOBILE_WINDOW_WIDTH_MAX,i=()=>n()||document.fullscreenElement,r=p=>{refTrailerVideo.value=p},o=async()=>{var p;s.value&&loadedMediaId.value!==e.value&&(await((p=refTrailerVideo.value)==null?void 0:p.loadVideo(e.value,VOD_DETAILS_TOP_BACKGROUND_WIDTH,VOD_DETAILS_TOP_BACKGROUND_HEIGHT)),loadedMediaId.value=e.value,log$2.info(`found trailer, mediaId = ${e.value}`))},a=()=>{hideBackgroundTimeoutId.value&&clearTimeout(hideBackgroundTimeoutId.value),playTimeoutId.value&&clearTimeout(playTimeoutId.value),showControlsTimeoutId.value&&clearTimeout(showControlsTimeoutId.value)},l=()=>{log$2.info("reset"),a(),isTrailerPlaying.value&&h(),isTrailerPlaying.value=!1,isTrailerVisible.value=!1,isBackgroundVisible.value=!0,loadedMediaId.value="",isAnyVideoControlVisible.value=!1},c=async()=>{isTrailerPlaying.value?h():await u(),isTrailerPlaying.value=!isTrailerPlaying.value},d=async()=>{a(),n()?(isTrailerVisible.value=!0,isTrailerPlaying.value=!0,await u(!0)):(hideBackgroundTimeoutId.value=setTimeout(()=>{isBackgroundVisible.value=!1},2600),showControlsTimeoutId.value=setTimeout(()=>{isTrailerPlaying.value=!0,isAnyVideoControlVisible.value=!0},2800),playTimeoutId.value=setTimeout(async()=>{isTrailerVisible.value=!0,await u()},3e3)),log$2.info("play trailer")},u=async(p=!1)=>{var m;try{await((m=refTrailerVideo.value)==null?void 0:m.play(p))}catch(v){log$2.error(v),l()}},h=()=>{var p;try{(p=refTrailerVideo.value)==null||p.pause()}catch(m){log$2.error(m)}};return{hasTrailer:s,isTrailerVisible,isBackgroundVisible,isAnyVideoControlVisible,isTrailerPlaying,loadTrailer:o,resetTrailer:l,onTrailerEnded:()=>{i()?(exitFullscreen$1(),isTrailerVisible.value=!0,isTrailerPlaying.value=!0):(isAnyVideoControlVisible.value=!1,setTimeout(()=>{isTrailerVisible.value=!1,isTrailerPlaying.value=!1},2e3),setTimeout(()=>{isBackgroundVisible.value=!0},2500),setTimeout(async()=>{await d()},6e3))},startPlayingTrailer:d,setRefTrailerVideo:r,hasTrailerAutoPlay:()=>!i()&&!isTrailerPlaying.value,togglePlayPause:c}},useSeoExperimentTitles=t=>{const e=useStore(),s=useRoute(),n=ref(!1),i=computed(()=>{var y;return(y=s==null?void 0:s.name)==null?void 0:y.toString()}),r=computed(()=>{var y,C;return((y=i.value)==null?void 0:y.includes("vod-title-season"))||((C=i.value)==null?void 0:C.includes("archive-title-season"))}),o=computed(()=>{var y;return(y=e.siteConfig)==null?void 0:y.seoExperiment}),a=computed(()=>{var y;return(y=o.value)==null?void 0:y.isEnabled}),l=computed(()=>{var y;return(y=o.value)==null?void 0:y.titles}),c=computed(()=>{var y;return(y=l.value)==null?void 0:y.find(C=>C.titleId===t)}),d=computed(()=>c.value&&c.value.experimentId==="type1_delete_content"),u=computed(()=>c.value&&c.value.experimentId==="type2_hide_google"),h=computed(()=>c.value&&c.value.experimentId==="type3_hide_js"),f=computed(()=>c.value&&c.value.variationId==="var_1_entire_card"),g=computed(()=>c.value&&c.value.variationId==="var_2_seasons_only"),p=computed(()=>c.value&&c.value.variationId==="var_3_main_page_only"),m=computed(()=>a.value&&u.value&&(f.value||g.value&&r.value||p.value&&!r.value)?!0:null),v=computed(()=>!f.value&&(g.value&&!r.value||p.value&&r.value)),S=computed(()=>!a.value||a.value&&!d.value&&!u.value&&!h.value||a.value&&(d.value&&v.value||u.value||h.value&&(f.value&&n.value||g.value&&!r.value||g.value&&r.value&&n.value||p.value&&r.value||p.value&&!r.value&&n.value)));return onMounted(()=>{n.value=!0}),{isSeoExperimentEnabled:a,hasSeoExperiment1:d,hasSeoExperiment2:u,hasSeoExperiment3:h,hasDataNosnippetForSeoExperiment2:m,hasVariation3:p,isVisibleWithSeoExperiment:S}},useTokens=()=>{const t=useStore(),e=computed(()=>{var h,f;return(f=(h=t.siteConfig)==null?void 0:h.tokens)==null?void 0:f.hasTokensV2}),s=computed(()=>t.tokensV1.analyticsToken),n=computed(()=>t.tokensV1.audienceToken),i=computed(()=>t.tokensV1.tvAssetToken);computed(()=>t.tokensV1.expiresAt);const r=computed(()=>{var h;return((h=t.tokensV2.assetTokens)==null?void 0:h.audienceToken)||""}),o=computed(()=>{var h;return((h=t.tokensV2.assetTokens)==null?void 0:h.tvAssetToken)||""}),a=computed(()=>{var h;return((h=t.tokensV2.assetTokens)==null?void 0:h.analyticsToken)||""}),l=computed(()=>{var h;return((h=t.tokensV2.assetTokens)==null?void 0:h.searchAssetToken)||""});computed(()=>t.tokensV2.contextToken),computed(()=>t.tokensV2.regularUpdate),computed(()=>{var h;
37return(h=t.tokensV2.regularUpdate)==null?void 0:h.etag}),computed(()=>{var h;return(h=t.tokensV2.regularUpdate)==null?void 0:h.intervalSec}),computed(()=>t.tokensV2.loaded),computed(()=>t.tokensV2.loading),computed(()=>t.tokensV2.timeout);const c=computed(()=>e.value?a.value:s.value),d=computed(()=>e.value?r.value:n.value),u=computed(()=>e.value?o.value:i.value);return{audienceToken:d,analyticsToken:c,tvAssetToken:u,searchAssetToken:l}},useTitleDetails=()=>{const{isAnonymous:t}=useAuth(),{playVodTitle:e,playArchiveTitle:s}=usePlay(),n=useStore(),i=useSSRContext(),{t:r}=useTranslation(),{sourceType:o,hasSeasons:a,seasons:l,seasonIndexFromRoute:c,seasonNumRoute:d,currentTitle:u,currentTitleId:h,isPlayingTitleEqualCurrentTitle:f,currentSourceId:g,nextEpisodeId:p,nextEpisode:m,episodesForNav:v}=useVod(),{audienceToken:S}=useTokens(),{isSeoExperimentEnabled:y,hasSeoExperiment2:C}=useSeoExperimentTitles(h.value),E=computed(()=>selectors.vod.titleH1Selector(n,u.value,d.value)),L=computed(()=>d.value>=0),T=computed(()=>l.value[c.value]),b=computed(()=>a.value&&(l.value.length>1||l.value.length===1&&l.value[0].id!=="0")),_=computed(()=>{var U;return((U=T.value)==null?void 0:U.description)||""}),I=computed(()=>{var U,Y;return((Y=(U=u.value)==null?void 0:U.details)==null?void 0:Y.description)||""}),P=ref("");onBeforeMount(async()=>{var U;P.value=((U=document.querySelector(".seo-title-description"))==null?void 0:U.textContent)||""}),watch(d,()=>{P.value=""});const R=computed(()=>{var le,ae;if(y.value&&C.value&&P.value)return P.value;const U=L.value&&_.value?_.value:I.value,Y=L.value?`<br/><br/>${r("vod_archive_title_description_with_season")}`:"",J=d.value>0?String(d.value):"",z=Y.replace(/%titleName%/g,((ae=(le=u.value)==null?void 0:le.preview)==null?void 0:ae.title)||"").replace(/%seasonNum%/g,J);return`${U}${z}`}),D=computed(()=>!!(O.value&&R.value)),O=computed(()=>{var U;return!!((U=u.value)!=null&&U.details)}),N=computed(()=>{var U,Y;return((Y=(U=u.value)==null?void 0:U.preview)==null?void 0:Y.years)||[]}),H=computed(()=>{var U,Y;return(Y=(U=u.value)==null?void 0:U.preview)==null?void 0:Y.hasSeries}),W=computed(()=>hasSavedPause(u.value)),M=computed(()=>{var U,Y;return(Y=(U=u.value)==null?void 0:U.pauses)==null?void 0:Y[0]}),A=computed(()=>{var U,Y,J;return((J=(Y=(U=v.value)==null?void 0:U[0])==null?void 0:Y.preview)==null?void 0:J.id)||""}),w=computed(()=>selectors.player.isPlayingSelector(n)),k=computed(()=>{var U,Y,J,z;return(z=(J=(Y=(U=n.siteConfig)==null?void 0:U.archiveCatalog)==null?void 0:Y.dvrDisclaimer)==null?void 0:J.movies)==null?void 0:z.isEnabled}),F=computed(()=>{var U,Y,J,z;return(z=(J=(Y=(U=n.siteConfig)==null?void 0:U.archiveCatalog)==null?void 0:Y.dvrDisclaimer)==null?void 0:J.series)==null?void 0:z.isEnabled}),B=computed(()=>H.value&&F.value||!H.value&&k.value),K=async()=>{await actions.vod.savePause(n,i,g.value)};return{isSeasonRoute:L,hasTitleSavedPause:W,currentTitleH1:E,isSeasonSelectorVisible:b,isDescriptionVisible:D,descriptionText:R,years:N,isPlayingTitleEqualCurrentTitle:f,hasSeries:H,titlePause:M,firstEpisodeIdFromChosenSeason:A,audienceToken:S,isTitleWithDetailsLoaded:O,isDvrDisclaimerVisible:B,playNextEpisode:async()=>{var Y,J,z,le,ae,ue;const U=((le=(z=(J=(Y=m.value)==null?void 0:Y.details)==null?void 0:J.mediaItems)==null?void 0:z[0])==null?void 0:le.id)||"";if(p.value){if(t.value){actions.notifications.showAuthAndRegNotification(n);return}
37w.value&&(await K(),await actions.vod.loadTitleVodPause(n,i,g.value,h.value)),g.value==="archive"?await s({titleId:h.value,episodeId:p.value,mediaItemId:U,withPreroll:!1}):await e({sourceId:g.value,titleId:h.value,episodeId:p.value,withPreroll:!1}),useGaEvent({category:o.value,action:"Клик по кнопке - Следующий эпизод",vod_name:g.value,title_id:(ue=(ae=u.value)==null?void 0:ae.preview)==null?void 0:ue.id})}}}},isWindowInIframe=window.self!==window.top,log$1=logger$1("marketing-external-code"),checkMarketingExternalCode=async store=>{const queryParams=new URLSearchParams(document.location.search),utmSourceParam=queryParams.get("utm_source"),lfstrmPartner=localStore.get(LOCAL_STORAGE_NAMES.lfstrmPartner),lfstrmPartnerTsFromStorage=localStore.get(LOCAL_STORAGE_NAMES.lfstrmPartnerTs),lfstrmPartnerCorrect=lfstrmPartner&&lfstrmPartnerTsFromStorage,utmSource=utmSourceParam||lfstrmPartner||"";if(!utmSource)return;const externalCode=await getMarketingExternalCode(utmSource);if(!externalCode)return;const now=Date.now(),isAnonymous=isAnonymousSelector(store),lfstrmPartnerTs=Number(lfstrmPartnerTsFromStorage)||now,utmSourceTimeLimit=lfstrmPartnerTs+externalCode.ttlDay*864e5,isCodeInsertionNeeded=()=>isAnonymous?utmSourceParam&&!lfstrmPartner||!utmSourceParam&&lfstrmPartner&&now<utmSourceTimeLimit||utmSource===utmSourceParam:now<=utmSourceTimeLimit;if(isCodeInsertionNeeded()){try{eval(externalCode.code)}catch(t){log$1.error(t)}isAnonymous&&(!lfstrmPartner||lfstrmPartnerCorrect)&&utmSourceParam&&!isWindowInIframe&&document.addEventListener("click",()=>{localStore.set(LOCAL_STORAGE_NAMES.lfstrmPartner,utmSourceParam),localStore.set(LOCAL_STORAGE_NAMES.lfstrmPartnerTs,now)},{once:!0})}lfstrmPartner&&now>utmSourceTimeLimit&&(localStore.remove(LOCAL_STORAGE_NAMES.lfstrmPartner),localStore.remove(LOCAL_STORAGE_NAMES.lfstrmPartnerTs))},useContent=()=>{var i;let t=null;const e=useStore(),s=getCurrentInstance(),n=(s==null?void 0:s.attrs["component-name"])||(s==null?void 0:s.attrs.componentName)||"";return n?t=((i=e.components[n])==null?void 0:i.content)||null:console.error("DID NOT PASS component-name to component attrs",s==null?void 0:s.attrs),t},providers=ref([]),regions=ref([]),useProviders=()=>{const t=useSSRContext(),e=useStore();return{providers,regions,getProvidersAndRegions:async()=>{var i,r;const n={ctx:t,languageCode:e.languageCode};regions.value=((i=await getRegions(n))==null?void 0:i.regions)||[],providers.value=((r=await getProviders(n))==null?void 0:r.providers)||[]}}},log=logger$1("phone-callback"),usePhoneCallback=()=>{const t=useStore(),e=useSSRContext(),{t:s}=useTranslation(),{isLoginSmotreshka:n,phoneUnsupported:i,phoneUnsupportedMessage:r,phoneTechnicalSim:o,recommendProvider:a,phoneInfoToken:l,registrationSettings:c}=useAuthAndReg();return{onCompletePhoneCallback:async h=>{if(!wlDetector().isMegacom)try{if(n.value){const f=await getPhoneInfoV2({languageCode:t.languageCode,ctx:e,params:{phone:cleanupPhone(h,t.authAndReg.usePlusInPhoneMethods.phoneInfo)}}).catch(g=>log.error("getPhoneInfoV2: ",g));if(!f.verificationSettings&&!f.registrationSettings&&!f.phoneInfoToken)return;o.value=f.verificationSettings.methods.includes(MEGAFON_IS_TECHNICAL_PARAM),a.value=f.registrationSettings.recommendProvider.externalProviderId,l.value=f.phoneInfoToken,c.value=f.registrationSettings.methods}else try{const f=await getPhoneInfoV1({languageCode:t.languageCode,ctx:e,data:{phone:cleanupPhone(h,t.authAndReg.usePlusInPhoneMethods.phoneInfo)}});i.value=(f==null?void 0:f.supportInfo.status)===PHONE_INFO_STATUSES.UNSUPPORTED,r.value=(f==null?void 0:f.supportInfo.reason)||s("phone_unsupported_message")}catch(f){i.value=f.resStatus>=HTTP_CODES.BAD_REQUEST,r.value=s("phone_unsupported_message")}}catch(f){log.error(f),r.value="",i.value=!1}},onIncompletePhoneCallback:()=>{r.value="",i.value=!1}}};function useVisibilityObserver(t,e=!1,s={threshold:.1}){const n=ref(!1);let i=null;const r=watch(t,a=>{a&&(o(),i=new IntersectionObserver(([l])=>{n.value=l.isIntersecting,l.isIntersecting&&e&&(o(),r())},s),i.observe(a))},{immediate:!0}),o=()=>
37{i&&(i.disconnect(),i=null)};return onUnmounted(()=>{o(),r()}),n}const useOffers=()=>{const t=useStore();return{getOfferVodSourcesListTitles:s=>s.reduce((n,i)=>{const r=t.vod.sources[i.trim()];return r&&n.push(r.title),n},[]).join(", ")||""}},useModalRoutes=()=>{const t=useStore(),e=useRoute(),s=useRouter(),n=ref("");onUpdated(()=>{const i=parseListRouteName(e.name);n.value!==i&&(deprioritizeRelatedRoutes(s,n.value),n.value=i,t.returnRoute={name:n.value},prioritizeRelatedRoutes(s,n.value))}),onMounted(()=>{n.value=parseListRouteName(e.name),t.returnRoute={name:n.value},prioritizeRelatedRoutes(s,n.value)}),onBeforeUnmount(()=>{t.returnRoute="",deprioritizeRelatedRoutes(s,n.value)})},useSearch=()=>{const{sendClickEvent:t}=useClientAnalytics();return{clientAnalyticsClick:async({item:s,block:n,flow:i,page:r})=>{const o={flow:i,page:r,item:s};n&&(o.block=n),await t(o)}}};class StopWatch{constructor(){$(this,"timestamp");this.timestamp=Date.now()}getMS(){return Date.now()-this.timestamp}start(){this.timestamp=Date.now()}}class TestChecks{constructor(e,s){$(this,"testName");$(this,"resource");this.testName=e.toLowerCase(),this.resource=s}checkAverageMs(e,s){const n=avg(flatten(s))||0,i=n<=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_average_ms")}checkMaxMs(e,s){const n=max(flatten(s))||0,i=n<=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_max_ms")}checkMinMs(e,s){const n=min(flatten(s))||0,i=n<=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_min_ms")}checkSuccessfulAttempts(e,s){const n=s>=e.threshold;return this.prepareResult(e,n,s,"diagnostics_check_successful_attempts")}checkFailedAttempts(e,s){const n=s<=e.threshold;return this.prepareResult(e,n,s,"diagnostics_check_failed_attempts")}checkMinChunkDownloadSpeed(e,s){const n=min(s)||0,i=n>=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_min_chunk_download_speed",!0)}checkAvgChunkDownloadSpeed(e,s){const n=avg(s)||0,i=n>=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_avg_chunk_download_speed",!0)}checkMinFileDownloadSpeed(e,s){const n=min(s)||0,i=n>=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_min_file_download_speed",!0)}checkAvgFileDownloadSpeed(e,s){const n=min(s)||0,i=n>=e.threshold;return this.prepareResult(e,i,n,"diagnostics_check_avg_file_download_speed",!0)}prepareResult(e,s,n,i,r=!1){if(s)return null;let o="",a="";return e.threshold&&(r?(o=formatToFixed2(bitsPerSToMbitPerS(e.threshold)),a=formatToFixed2(bitsPerSToMbitPerS(n))):(o=Math.round(e.threshold).toString(),a=Math.round(n).toString())),{...e,code:e.title,thresholdFormatted:o,result:n,resultFormatted:a,translationKey:i}}}class TestCore{constructor(e){$(this,"requestStopWatch");$(this,"payload");$(this,"requestTime");$(this,"successfulAttempts");$(this,"failedAttempts");$(this,"isChunksTest");this.requestStopWatch=new StopWatch,this.payload=e,this.requestTime=[],this.successfulAttempts=0,this.failedAttempts=0,this.isChunksTest=!!e.chunkSizeBytes&&!!e.numChunks}run(){const{attempts:e}=this.payload;return filledWithZeros(e).reduce((s,n,i)=>s.then(()=>this.sendRequest(i+1)).then(()=>{this.successfulAttempts+=1}).catch(()=>{this.failedAttempts+=1}),Promise.resolve()).then(()=>({...this.payload,stat:this.getStat(),failedChecks:this.doChecks()}))}doChecks(){const{title:e,humanReadableResource:s,checkList:n}=this.payload,i=new TestChecks(e,s),r={};return n.forEach(o=>{let a=null;switch(o.type){case"avg-ms":a=i.checkAverageMs(o,this.requestTime);break;case"max-ms":a=i.checkMaxMs(o,this.requestTime);break;case"min-ms":a=i.checkMinMs(o,this.requestTime);break;case"successful-attempts":a=i.checkSuccessfulAttempts(o,this.successfulAttempts);break;case"failed-attempts":a=i.checkFailedAttempts(o,this.failedAttempts);break;case"min-chunk-download-speed":a=i.checkMinChunkDownloadSpeed(o,this.getChunkDownloadSpeed());break;case"avg-chunk-download-speed":a=i.checkAvgChunkDownloadSpeed(o,this.getChunkDownloadSpeed());break;case"min-file-download-speed":a=i.checkMinFileDownloadSpeed(o,this.getFileDownloadSpeed());break;case"avg-file-download-speed":a=i.checkAvgFileDownloadSpeed(o,this.getFileDownloadSpeed());break}a&&(r[a.type]=a)}),Object.values(r)}sendRequest(e){return this.isChunksTest||this.recordRequestStartTime(),this.doSendRequest(e).finally(()=>{this.isChunksTest||this.recordRequestEndTime(e)})}doSendRequest(e){const{timeLimitMs:s,chunkSizeBytes:n,numChunks:i}=this.payload;return new Promise((r,o)=>{const a=new XMLHttpRequest;if(a.timeout=s,a.onerror=()=>o(new Error("Network error")),a.ontimeout=()=>o(new Error("Target host is not responding")),a.onload=()=>r(),a.open("GET",this.getUrl()),n&&i){this.recordRequestStartTime(),a.setRequestHeader("Range",`bytes=0-${n*i}`);let l=1,c=!0;a.onprogress=d=>{c&&d.loaded>=d.total?this.recordRequestEndTime(e):d.loaded>l*n&&(this.recordRequestEndTime(e),c=!1,d.loaded<d.total&&(c=!0,this.recordRequestStartTime(),l++))}}a.send()})}getUrl(){return`${this.payload.resource}?_=${new Date().getTime()}`}getChunkDownloadSpeed(){const e=this.payload.chunkSizeBytes||0,s=bytesToBits(e),n=[];return this.requestTime.forEach(i=>
37{i.forEach(r=>{const o=msToS(r);n.push(this.calcSpeed(s,o))})}),n}getFileDownloadSpeed(){const e=this.payload.chunkSizeBytes||0,s=bytesToBits(e),n=this.payload.numChunks||0,i=s*n;return this.requestTime.map(r=>{const o=sum(r)||0,a=msToS(o);return this.calcSpeed(i,a)})}getStat(){let e=[];this.requestTime.forEach(n=>{e=e.concat(n)});const s={resource:this.payload.resource,attempts:this.payload.attempts,successfulAttempts:this.successfulAttempts,failedAttempts:this.failedAttempts,requestTime:{max:max(e)||0,min:min(e)||0,avg:Math.round(avg(e)||0)}};return this.payload.type==="xhr-speed"?{...s,chunkDownloadSpeed:{max:max(this.getChunkDownloadSpeed())||0,min:min(this.getChunkDownloadSpeed())||0,avg:Math.round(avg(this.getChunkDownloadSpeed())||0)},fileDownloadSpeed:{max:max(this.getFileDownloadSpeed())||0,min:min(this.getFileDownloadSpeed())||0,avg:Math.round(avg(this.getFileDownloadSpeed())||0)}}:s}recordRequestStartTime(){this.requestStopWatch.start()}recordRequestEndTime(e){const s=e-1;this.requestTime[s]=this.requestTime[s]||[],this.requestTime[s].push(this.requestStopWatch.getMS())}calcSpeed(e,s){return s>0?Math.max(e/s,0):0}}const usePremiumPage=()=>{const t=useStore(),e=useGetByLanguage(),s=computed(()=>selectors.tvChannels.allChannelsSelector(t)),n=computed(()=>selectors.tvChannels.genresSelector(t)),i=computed(()=>{const d=groupBy(s.value,"relevantGenres[0].genreId");return d.undefined&&delete d.undefined,d});return{channels:s,allGenres:i,getFileUrl:d=>{var h;const u=typeof d=="object"&&((h=e(d))==null?void 0:h.url)||"";return matchUrlProtocolWithLocationProtocol(u,t.common.isHttps)},offerGenresFiltered:d=>Object.keys(i.value).reduce((u,h)=>{const f=i.value[h].filter(g=>d.includes(g.id));return f.length>0&&(u[h]=f),u},{}),getMappedGenres:d=>{var u;return(u=n.value)==null?void 0:u.reduce((h,f)=>(d!=null&&d[f.id]&&h.push({id:f.id||f.title,title:f.title}),h),[])},getChannelLogoUrl:(d,u=200)=>{const h=getChannelLogo(d);return h?`${h}?width=${Math.round(u*16/9)}&height=${u}`:""},getGenreIconPath:d=>selectors.tvChannels.genreIconSelector(t,d)}},sendPremiumRequest=async t=>oldFe.post(URLS.oldSmotreshkaPremiumPage,t);export{isUrlExternal as $,useScrollWatcher as A,BROWSERS as B,DESKTOP_WINDOW_WIDTH_MIN as C,DOM_SCROLL_CONTAINER_ID as D,enToRu as E,getDeviceFlags as F,COLOR_CLASS as G,useNotification as H,cookieStore as I,COOKIE_NAMES as J,KEY_CODE as K,LazyImage$1 as L,convertToMilliseconds as M,AUTH_AND_REG_URLS as N,localStore as O,PLATFORMS as P,MOBILE_WINDOW_WIDTH_MAX as Q,usePopupNotices as R,SequoiaComponent as S,TABLET_WINDOW_WIDTH_MIN as T,POPUP_NOTICE_IMAGE_TYPES as U,POPUP_NOTICE_RENDERING_METHODS as V,useGetByLanguage as W,LOCAL_STORAGE_NAMES as X,useWindowWidth as Y,getArchivedSubscriptions as Z,__vitePreload as _,useAuthAndReg as a,remove as a$,secondsToHMSelector as a0,BRANDING_METHODS_OPTIONS_ID as a1,getTitlePath as a2,parseRouteName as a3,sum as a4,sleep as a5,WithResizeListener as a6,Global as a7,DESKTOP_S_WINDOW_WIDTH_MAX as a8,useUa as a9,SUBSCRIPTION_STATUSES as aA,convertToDays as aB,RENDERING_METHOD_NAMES as aC,DateTime as aD,parseMd as aE,PROFILE_RESTRICTION_IDS as aF,ADULT_ONBOARDING_STEPS as aG,ADULT_ONBOARDING_PIN_ACTION as aH,ApiError as aI,ADULT_ONBOARDING_MAX_NUMBER_OF_TRIES as aJ,ADULT_ONBOARDING_PROFILE_CHANGE_TIMEOUT as aK,PROFILE_PIN_LENGTH as aL,create as aM,getProfile as aN,QS_SOURCE_TYPES as aO,REGISTRATION_CAPTCHA_LENGTH as aP,contactsVerification as aQ,VERIFICATION_METHODS as aR,useGaEventOnce as aS,useVerification as aT,additionalActionsGoToPreviousStep as aU,REGISTRATION_SMS_CODE_LENGTH as aV,cleanupPhone as aW,QS_VERIFICATION_PHONE_STEPS as aX,getChannelById as aY,getChannelTitle as aZ,PROFILE_ACTIONS as a_,getPlaybackLsHlsVideo as aa,useHttpsProtocol as ab,getOsFlags as ac,Hls as ad,requestFullscreen as ae,useSeoExperimentTitles as af,useVod as ag,PROMO_ELEMENTS_INTERNAL_REFERENCE_MAPPING as ah,handleOffersSet as ai,PROMO_ELEMENTS_ACTION_METHODS as aj,BANNER_VIDEO_RENDERING_METHODS_NAMES as ak,getChannelLogo as al,HTTP_CODES as am,sessionStore as an,managing as ao,managingWithVerifiedContacts as ap,managingMethods as aq,MANAGING_LOGIN_METHODS as ar,RESEND_SMS_CODE_TIMEOUT as as,useEvents as at,managingLogout as au,EVENTS as av,useSubscriptions as aw,useChannels as ax,MANAGEMENT_METHOD_NAMES as ay,yakassaSubscriptionsSelector as az,getContactsVerificationCaptchaData as b,useEpgHelpers as b$,dateAfterNDays as b0,goToNextStep as b1,renewSubscriptionWithExistedPm as b2,getLastPayment as b3,isPaymentSuccessful as b4,renewSubscriptionWithNewPm as b5,renewSubscription as b6,PaymentSystem as b7,useWelcomeScreen as b8,WELCOME_SCREEN_STEPS as b9,useUnsubscriptionRetention as bA,RETENTION_OFFER_RESULT as bB,UNSUBSCRIPTION_RESULTS as bC,UNSUBSCRIPTION_RETENTION_STEPS as bD,hasModalInRouteName as bE,hasPlayerInRouteName as bF,getPromoCodeCookie as bG,getProfileConfirmationPeriodCookie as bH,getProfileConfirmedCookie as bI,getWelcomeScreenConfirmedCookie as bJ,getAppVersionParams as bK,SequoiaPage as bL,PLAYER_ERROR_CODES as bM,useShaka as bN,useHls as bO,useNative as bP,getBrowserFlags as bQ,PLAYBACK_METHODS as bR,getIsFullscreen as bS,boundMinMax as bT,checkNumberWithDefault as bU,PLAYER_DEFAULT_VOLUME as bV,isDvrDisabled as bW,usePlayerVideo as bX,usePlayerPlaying as bY,formatTimeHM as bZ,convertToSeconds as b_,showErrorNotification as ba,MTS_AUTH_SMS_CODE_LENGTH as bb,formatPhone as bc,QS_VERIFICATION_SUBSCRIPTION_STEPS as bd,useProfileProtected as be,PROFILE_PROTECTED_STEPS as bf,SUBSCRIBE_STEP_WITH_BACK_BUTTON as bg,hasWatchInRoutePath as bh,parseListRouteName as bi,QS_CALLBACK_TIMEOUT as bj,getEnvVars as bk,isOkUrl as bl,useChangeLanguage as bm,useGetLanguageIcon as bn,getLanguages as bo,isAutologinEnabled as bp,useSearchHistory as bq,SEARCH_STRING_SOURCE as br,DEFAULT_VOD_CATEGORIES as bs,storage as bt,STORE_KEYS as bu,ScrollWatcher as bv,Vod as bw,DEFAULT_TILES_AMOUNT as bx,getTitlePosterUrl as by,getTitlePosterType as bz,getContactsVerificationCaptchaImage as c,getTitlePathWithSeason as c$,getChannelAboutPath as c0,getRecentAndFavChannels as c1,useEpgSchedule as c2,useTvPauses as c3,hasSavedPause as c4,getTitlePauseEpisode as c5,getTitlePauseEpisodeName as c6,hasDvr as c7,THRESHOLDS as c8,MOUSE_EVENT_BUTTONS as c9,loadScript as cA,isEmptyObject as cB,getChannelNumberPadded as cC,Metrics as cD,Channel as cE,DEFAULT_CHANNELS_AMOUNT as cF,TV_SORTING as cG,sortChannels as cH,LethargyService as cI,getScrollPosition as cJ,WithModalRoutes as cK,PopupNotices as cL,useChannelDetails as cM,getChannelGenres as cN,getChannelDescription as cO,useVodTrailer as cP,VOD_DETAILS_TOP_BACKGROUND_HEIGHT as cQ,VOD_DETAILS_TOP_BACKGROUND_WIDTH as cR,useSeo as cS,channelsFromCollectionSelector as cT,setMetaTitle as cU,Seo as cV,getRouteNameForPlayer as cW,transliterate as cX,getCategoryTitles as cY,useTitleDetails as cZ,getFirstSentence as c_,isDvrRestricted as ca,HIDE_PLAYER_ALERT_DELAY as cb,getChannelNumber as cc,isFullscreenAvailable as cd,useThumbnails as ce,TV_PLAYER_TICK_OFFSET as cf,ARCHIVE_PLAYER_TICK_OFFSET as cg,usePlayerSmokingWarning as ch,usePauses as ci,usePlayerStats as cj,usePlaybackSession as ck,CONTENT_RATING_DEFAULT_AGE as cl,errorSelector as cm,PREROLL_TIME as cn,PLAYER_OFFSET_DURATION as co,scrollEverythingToTop as cp,IVI_FORBIDDEN_CODES as cq,useFullScreenPlayer as cr,TV_SPECIAL_GENRES as cs,EPG_TOP_MARGIN as ct,useEpgCalendar as cu,EPG_SLIDER_LEFT_COUNT as cv,EPG_SLIDER_RIGHT_COUNT as cw,getChannelLogoResized as cx,getDvrAvailability as cy,clientPlatformSelector as cz,useSSRContext as d,useTokens as d$,getHboMaxUrl as d0,getTitle as d1,DEFAULT_SLIDES_AMOUNT as d2,AUTO_LOGIN_MEGAFON_ROUTES_NAMES as d3,getRouteNameForModal as d4,isChannelIdValid as d5,isTitleIdValid as d6,isSourceIdValid as d7,isVodMegaCollectionSlugValid as d8,isVodCollectionIdValid as d9,usePhoneCallback as dA,useAuthAndRegCheckboxes as dB,registerByPhone as dC,AUTH_STEPS as dD,showModal as dE,MODALS as dF,CORRECT_PHONE_LENGTH as dG,AUTH_METHODS as dH,registerSimPassword as dI,CONTACT_VERIFICATION_OUTDATED_ERROR_CODE as dJ,CONTACT_VERIFICATION_ERROR_CODE as dK,useProviders as dL,useOffers as dM,useVisibilityObserver as dN,validatePromoCodeOffer as dO,autoTrialDurationSelector as dP,wasAutoTrialCreatedSelector as dQ,PHONE_INFO_VERIFICATION_METHODS as dR,yaMetrikaGoal as dS,GET_TRIAL_STATUS_ERROR_CODE as dT,contactsVerificationSimPassword as dU,REGISTRATION_TIMEOUT_AFTER_SIGN_IN as dV,currentOfferSelector as dW,currentOfferIdSelector as dX,restorePasswordByLink as dY,DEFAULT_SEARCH_TEXT_BANNERS_BLOCK_ID as dZ,useClientAnalytics as d_,isSeasonNumValid as da,registrationPath as db,hasBadSymbols as dc,useContent as dd,bytesToKiloBytes as de,PROMO_ELEMENTS_PLACEMENT_BLOCKS as df,isBannersDataLoadedSelector as dg,INTERNAL_PROMO_ELEMENTS_ACTION_METHODS as dh,BANNER_STRIP_RENDERING_METHODS_NAMES as di,TV_SORTING_GENRE_CHANNELS_BLOCK as dj,getMyCollectionPath as dk,getTitles as dl,DEFAULT_VOD_SCREEN_CONFIG as dm,DEFAULT_SEARCH_BANNERS_BLOCK_ID as dn,DEFAULT_SEARCH_SCREEN_CONFIG as dp,LokiLogger as dq,getUserAgent as dr,checkMarketingExter
37nalCode as ds,getEnvironment as dt,SENTRY_DSN as du,isEveryEnvVarValidOnClientSide as dv,store$1 as dw,getOsName as dx,isAndroidWebview as dy,GTM_EVENT_TIMEOUT as dz,getPlatformType as e,useSearch as e0,useModalRoutes as e1,TClientAnalyticsUiEvent as e2,AUTO_RENEW_DISABLED_CUSTOM_ERROR_CODE as e3,gaParamsSelector as e4,showQsQr as e5,getTokenData as e6,qsStateForTransaction as e7,SUBSCRIPTION_STATUSES_REASONS as e8,checkPaymentStatusTrials as e9,getOffer as ea,expireDate as eb,getVodSubscriptionOptions as ec,changePassword as ed,ADULT_OFFER_ID as ee,ADULT_CHANNELS as ef,getSpeedTests as eg,createLinkTag as eh,URLS as ei,TestCore as ej,bitsPerSToMbitPerS as ek,formatToFixed2 as el,hasAdBlock as em,usePremiumPage as en,sendPremiumRequest as eo,loadFiles as ep,getPremiumPageProvider as eq,getOfferShowcaseChannels as er,promoCodeCheck as es,PROMO_CODE_METHODS as et,ADDITIONAL_SUBSCRIPTIONS_DEFAULT_CATEGORY_ID as eu,gaEvent as ev,TABLET_WINDOW_WIDTH_MAX as ew,imageServerUrl as ex,getBrowserName as f,getCaptchaImage as g,getByLanguage as h,removePortFromServerUrl as i,matchUrlProtocolWithLocationProtocol as j,getResizedImageUrl as k,logger$1 as l,makePath as m,BLANK_IMAGE as n,lazy as o,findScrollableParent as p,useAuth as q,replaceAt as r,selectors as s,usePlay as t,useStore as u,useMetrics as v,wlDetector as w,actions as x,useTranslation as y,useGaEvent as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.