SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("0Jw_Y6qiJT",["C42E8rVVpA","CsxDAjmHZE"],(async(e,t)=>{let n=class extends t.s{constructor(){super(...arguments),this.open=!1,this._eventsDefined=!1,this.updated=e=>{e.has("open")&&(this.open&&(this.details.open=!0),this._animator.open=this.open,this._summary.setAttribute("aria-expanded",this.open.toString()))},this._onClick=e=>{e.target&&this._summary?.contains(e.target)&&(e.preventDefault(),this.open=!this.open,this._animator.open=this.open)},this._onTransitionEnd=e=>{e.target&&this._animator?.contains(e.target)&&(this.details.open=this.open)}}get details(){return this.querySelector("details")}get _summary(){return this.details?this.details.querySelector("summary"):null}get _animator(){return this.querySelector("faceplate-auto-height-animator")}connectedCallback(){super.connectedCallback(),this._eventsDefined||(this.addEventListener("click",this._onClick),this.addEventListener("transitionend",this._onTransitionEnd),this._eventsDefined=!0),async function(){return new Promise((e=>{"loading"===document.readyState?document.addEventListener("readystatechange",(()=>{e(!0)}),{once:!0}):e(!0)}))}().then((()=>{null!=this.details&&null!=this._summary&&null!=this._animator&&(this.open=this.details.open)}))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("click",this._onClick),this.removeEventListener("transitionend",this._onTransitionEnd),this._eventsDefined=!1}createRenderRoot(){return this}};e._([e.n({type:Boolean,reflect:!0})],n.prototype,"open",void 0),n=e._([e.e("faceplate-expandable-section-helper")],n);var i=Object.freeze({__proto__:null,get FaceplateExpandableSectionHelper(){return n}});return{get f(){return i}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("1i4g9fLWHY",["C42E8rVVpA","CsxDAjmHZE","DUzIBJc2in"],(async(e,a,t)=>{let r=class extends e.h4{constructor(){super(...arguments),this._fullscreenBlurEl=document.createElement("div"),this._appliedBlurFilter=null,this._blurElement=null,this.shouldContentScroll=!1,this.isFooterEmpty=!0,this.render=()=>{const t=a.x``,r=a.x``,n=a.x` `;return a.x` ${e.cA(this.modal?"\n \n":"\n \n")}
${t}
${r}
`}}static get styles(){return a.i`${e.h4.styles}:host{--content-padding:var(--spacer-md);box-sizing:border-box;max-width:none;border-radius:var(--rem16);padding:0;overflow:hidden}#wrapper{display:flex;flex-direction:column;align-items:center;height:100%;position:relative;font-size:16px;box-sizing:border-box;max-height:inherit;min-height:inherit;overflow:hidden}slot[name=closeButton]{display:inline-flex;position:absolute;position:absolute;top:0;inset-inline-end:0;margin:var(--content-padding)}#header{display:flex;flex-direction:column;gap:var(--spacer-sm);align-items:center;text-align:start;width:100%;box-sizing:border-box}#header.with-icon{text-align:center;padding:0 var(--rem40)}slot[name=title]{font-size:var(--rem18);font-weight:700}slot:not([name]){display:flex;flex-grow:1;width:100%;padding:var(--spacer-xs) 0;font-size:var(--rem14)}#footer{display:flex;flex-direction:column;gap:var(--spacer-sm);width:100%;background:var(--color-ui-modalbackground);padding:var(--spacer-md);box-sizing:border-box}slot[name=tertiaryButton]{display:inline-flex;justify-content:center;font-size:14px}#footer.empty{display:none}@media (min-width:640px){#content{padding:var(--content-padding)}#header,#header.with-icon{flex-direction:row;padding-inline:0 var(--spacer-2xl)}#footer{flex-direction:row-reverse;align-items:center;justify-content:end}slot[name=tertiaryButton]{margin-inline-end:auto}slot[name=title]{text-align:start}}#content{height:100%;max-height:100%;width:100%;overflow:auto;position:relative;--content-padding:var(--spacer-md);padding:var(--content-padding);box-sizing:border-box;flex:1}.overflowing-content{max-height:100%;overflow-y:auto}.sticky-footer{box-shadow:var(--elevation-md)}slot[name=closeButton].floating{box-shadow:var(--elevation-sm);border-radius:999px}`}connectedCallback(){super.connectedCallback(),Object.assign(this._fullscreenBlurEl.style,{position:"fixed",top:"0",bottom:"0",right:"0",left:"0",backdropFilter:n(4)})}disconnectedCallback(){this._fullscreenBlurEl.remove(),e.g_.remove(this),this.resizeObserver?.disconnect()}firstUpdated(){this.resizeObserver=new ResizeObserver((()=>{this.measureShouldContentScroll()})),this.resizeObserver.observe(this.content)}calcFooterChildren(){this.isFooterEmpty=!(this._footerSlot?.length||this._primaryButtonSlot?.length||this._secondaryButtonSlot?.length||this._tertiaryButtonSlot?.length)}measureShouldContentScroll(){this.shouldContentScroll=Boolean(this.content?.scrollHeight&&this.content?.scrollHeight>this.content.offsetHeight)}showModal(a){if(e.g_.add(this),super.showModal(),null!=a?.blur){const e=!0===a.blur?4:Number(a.blur);this._appliedBlurFilter=n(e),a?.blurElement?(this._blurElement=a.blurElement,t=this._blurElement,r=this._appliedBlurFilter,t.style.filter=t.style.filter+" "+r):(Object.assign(this._fullscreenBlurEl.style,{backdropFilter:this._appliedBlurFilter}),document.body.append(this._fullscreenBlurEl))}var t,r}close(){this.open&&(super.close(),e.g_.remove(this),null!=this._blurElement&&null!=this._appliedBlurFilter?(!function(e,a){const t=e.style.filter.split(" ").filter(Boolean).reverse(),r=t.indexOf(a);if(-1===r)return;t.splice(r,1),e.style.filter=t.reverse().join(" ")}(this._blurElement,this._appliedBlurFilter),this._appliedBlurFilter=null,this._blurElement=null):this._fullscreenBlurEl.remove())}};function n(e){return`blur(${e}px)`}e._([e.v()],r.prototype,"shouldContentScroll",void 0),e._([e.l({slot:"titleGraphic"})],r.prototype,"_titleGraphic",void 0),e._([e.Q("#content")],r.prototype,"content",void 0),e._([e.Q("#footer")],r.prototype,"footer",void 0),e._([e.v()],r.prototype,"isFooterEmpty",void 0),e._([e.av({slot:"footer",flatten:!0})],r.prototype,"_footerSlot",void 0),e._([e.av({slot:"primaryButton",flatten:!0})],r.prototype,"_primaryButtonSlot",void 0),e._([e.av({slot:"secondaryButton",flatten:!0})],r.prototype,"_secondaryButtonSlot",void 0),e._([e.av({slot:"tertiaryButton",flatten:!0})],r.prototype,"_tertiaryButtonSlot",void 0),r=e._([e.e("faceplate-modal")],r);const i=()=>"Something went wrong saving the avatar.",o=()=>"Something went wrong while saving the banner.";function l(e){return e?.[0]?.message??"Something went wrong";}const s=e=>({error:e||"There was an error uploading the file."});async function d(a,r){const n=t.U.get(a.type);if(!n)throw new Error(`${a.type} files are not supported.`);try{const i=await async function(a){const t=await e.C({operation:e.H.CreateSubredditStructuredStylesUploadLease,variables:{input:a}});if(t.errors?.length)throw new Error(l(t.errors));const r=t.data.createSubredditStructuredStylesUploadLease;if(r?.ok&&r.uploadLease)return{uploadLeaseUrl:r.uploadLease.uploadLeaseUrl,uploadLeaseHeaders:r.uploadLease.uploadLeaseHeaders};throw new Error(l(r?.errors))}({...r,filepath:a.name,mimetype:n}),o=await t.X(a,i);return o?{url:o}:s()}catch(e){return i=e.message,window.Sentry?.captureMessage?.(`Media file upload failed with error: ${i}`),s(e.message)}var i}return {C:class{constructor(){this.url=void 0}async makeGQLRequest(...a){return e.C(...a)}async uploadMedia(...e){return d(...e)}async saveImage({subredditId:e,url:a,fileContent:t,uploadType:r,gqlOperation:n}){if(t)try{const n=await this.uploadMedia(t,{subredditId:e,imagetype:r});if(a=n.url?decodeURIComponent(n.url):a,n.error)return this.handleError(r);this.url=a}catch(e){return this.handleError(r)}try{await this.makeGQLRequest({operation:n,variables:{input:{subredditId:e,[this.getOperationArg(r)]:a??""}}})}catch(e){return this.handleError(r)}return null}async saveCommunityIcon(a,t,r){return this.saveImage({subredditId:a,url:t,fileContent:r,uploadType:e.h5.CommunityIcon,gqlOperation:e.H.UpdateSubredditIcon})}async saveBanner(a,t,r){return this.saveImage({subredditId:a,url:t,fileContent:r,uploadType:e.h5.BannerBackgroundImage,gqlOperation:e.H.UpdateSubredditBanner})}async saveMobileBanner(a,t,r){return this.saveImage({subredditId:a,url:t,fileContent:r,uploadType:e.h5.MobileBannerImage,gqlOperation:e.H.UpdateSubredditBanner})}handleError(a){switch(a){case e.h5.BannerBackgroundImage:return o();case e.h5.MobileBannerImage:return "Something went wrong while saving the mobile banner.";case e.h5.CommunityIcon:default:return i()}}getOperationArg(a){switch(a){case e.h5.BannerBackgroundImage:return"bannerBackgroundImage";case e.h5.MobileBannerImage:return"mobileBannerImage";case e.h5.CommunityIcon:default:return"communityIcon"}}},E:o,get F(){return r},O:"mod-show-post-level-crowd-control-modal",a:i,u:d};})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("Af5s1GVSm3",["C42E8rVVpA","DUzIBJc2in","CsxDAjmHZE"],(async(e,t)=>{class i extends HTMLElement{constructor(){super(),this.childAnchor=null,this.chatUrl=null,this.mobilePermalink=null,this.handleAnchorClick=async e=>{if(!this.chatUrl)return;if(e.preventDefault(),this.mobilePermalink){const e=new URL(this.mobilePermalink,window.location.href).searchParams.get("r"),i=document.querySelector(`faceplate-modal[name="${t.cD}"]`),a=i?.querySelector("a.app-link");if(a?.href){const t=new URL(a.href);e&&t.searchParams.set("r",e),t.searchParams.set("$android_deeplink_path",`reddit${this.mobilePermalink}`),t.searchParams.set("$deeplink_path",this.mobilePermalink),t.searchParams.set("$og_redirect",`${CLIENT_CONFIG.ORIGIN}${this.mobilePermalink}`),t.searchParams.set("base_url",this.mobilePermalink),a.setAttribute("href",t.toString())}return void this.dispatchEvent(new CustomEvent(t.cD,{bubbles:!0}))}let i=document.querySelector("reddit-chat-host");i||(await this.activateFeature(),i=document.querySelector("reddit-chat-host")),i.openChatUrl(this.chatUrl)}}async activateFeature(){try{await e.j({name:e.au})}catch(t){if(!t.message?.endsWith(`${e.au} not found`))throw t}}connectedCallback(){const e=this.querySelector(":scope > a, :scope > li > a"),i=e?.href;this.mobilePermalink=this.getAttribute("permalink");((e,i=!1)=>!!e&&(e.startsWith(t.aE)||e.startsWith(t.cC)||i&&e.startsWith("/c/")))(i||this.mobilePermalink||void 0,!!this.mobilePermalink)&&(this.childAnchor=e,!i&&this.mobilePermalink?this.chatUrl=this.mobilePermalink:i&&i.startsWith(t.aE)?this.chatUrl="/"+i.replace(t.aE,""):i&&(this.chatUrl="/"+i.replace(t.cC,"")),this.childAnchor?.addEventListener("click",this.handleAnchorClick))}disconnectedCallback(){this.childAnchor?.removeEventListener("click",this.handleAnchorClick)}}return customElements.define("reddit-chat-anchor",i),{a:e=>`${t.aE}room/${e}`,g:(e,i)=>`${t.aE}room/${e}/event/${i}`}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("B-LM1r1oJd",["CsxDAjmHZE"],(async n=>{var e;!function(n){n.NEUTRAL="NEUTRAL",n.SUCCESS="SUCCESS",n.WARNING="WARNING",n.ALERT="ALERT",n.PLAIN="PLAIN",n.DISABLED="DISABLED",n.DANGER="DANGER",n.INVERTED="INVERTED",n.SECONDARY="SECONDARY",n.MEDIA="MEDIA",n.BRAND="BRAND"}(e||(e={}));const r="bg-brand-background text-brand-onBackground",t="bg-secondary-background text-secondary-onBackground",a={[e.WARNING]:"bg-warning-background text-neutral-background",[e.SUCCESS]:"bg-success-background text-primary-onBackground",[e.NEUTRAL]:"bg-neutral-content text-neutral-background",[e.PLAIN]:t,[e.ALERT]:r,[e.BRAND]:r,[e.DANGER]:"bg-danger-background text-primary-onBackground",[e.DISABLED]:"bg-interactive-content-disabled text-neutral-background",[e.INVERTED]:"bg-inverted-neutral-background text-neutral-background",[e.SECONDARY]:t,[e.MEDIA]:"bg-media-background text-media-onBackground"};return{get B(){return e},b:({attributes:r,appearance:t=e.NEUTRAL,content:o,outline:c=!1})=>{const{html:d,createElement:E}=n.g(),u=d`${o}`;let b="rounded-full inline-flex";return o||(b+=" h-xs w-xs"),c&&(b+=" border-md border-solid border-neutral-background"),E("span",{...r,className:`${[a[t]]} ${b} ${r?.className}`,rpl:!0},u)}}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./B7xOUSlR-V.js",import.meta.url,"B7xOUSlR-V"); SML.dm("B-LgD4K8b5",["CsxDAjmHZE","C42E8rVVpA","B7xOUSlR-V"],(async(t,e,i)=>{const{svg:l}=t.g(),s=t.m(l``,"0 0 20 20","gif"),{svg:a}=t.g(),h=t.m(a``,"0 0 20 20","play-fill");var r=Object.freeze({__proto__:null,ToggleableVideoAdController:class{constructor(t,i){this.expandVideoPlayer=()=>{this.toggleElVisibility(this.videoPlayerEl,!0),this.toggleElVisibility(this.thumbnailContainerEl,!1),this.toggleElVisibility(this.thumbnailImageEl,!1),this.toggleElVisibility(this.thumbnailPlayBtnEl,!1),setTimeout((()=>{this.shredditPlayer&&this.updateVideoAdMeasurerDimensions(this.shredditPlayer.offsetHeight,this.shredditPlayer.offsetWidth)}),300)},this.hideVideoPlayer=()=>{this.toggleElVisibility(this.videoPlayerEl,!1),this.toggleElVisibility(this.thumbnailContainerEl,!0),this.toggleElVisibility(this.thumbnailImageEl,!0),this.toggleElVisibility(this.thumbnailPlayBtnEl,!0),this.shredditPlayer?.mediaUI?.hasAttribute(e.gt.PLAYING)&&this.host.dispatchEvent(new CustomEvent(e.eF,{detail:{currentTime:this.shredditPlayer?.videoElement.currentTime,duration:this.shredditPlayer?.videoElement.duration}}))},(this.host=t).addController(this),this.updateVideoAdMeasurerDimensions=i}get videoPlayerEl(){return this.host.querySelector(`.${i.E}`)}get videoPlayerCloseBtnEl(){return this.host.querySelector(`.${i.V}`)}get thumbnailContainerEl(){return this.host.querySelector(`.${i.T}`)}get thumbnailImageEl(){return this.host.querySelector(`.${i.a}`)}get thumbnailPlayBtnEl(){return this.host.querySelector(`.${i.b}`)}get shredditPlayer(){return e.bj.map((t=>this.host.querySelector(t))).find((t=>null!==t))||null}toggleElVisibility(t,e){if(null===t)return;const l=e?t.dataset[i.c]:t.dataset[i.d];l&&l?.split(" ").forEach((e=>{t.classList.remove(e)}));const s=e?t.dataset[i.d]:t.dataset[i.c];s&&s?.split(" ").forEach((e=>{t.classList.add(e)}))}async hostConnected(){this.host.adType===e.eB.VIDEO&&(this.thumbnailContainerEl?.addEventListener("click",this.expandVideoPlayer),this.videoPlayerCloseBtnEl?.addEventListener("click",this.hideVideoPlayer))}hostDisconnected(){this.host.adType===e.eB.VIDEO&&(this.thumbnailContainerEl?.removeEventListener("click",this.expandVideoPlayer),this.videoPlayerCloseBtnEl?.removeEventListener("click",this.hideVideoPlayer))}}});return{g:s,get i(){return r},p:h}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("B7v2ktuRzR",["CsxDAjmHZE"],(async a=>{const{svg:c}=a.g();return{a:a.m(c``,"0 0 20 20","answers")}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("B7xOUSlR-V",["CsxDAjmHZE"],(async e=>{const{svg:a}=e.g();return{C:"product-carousel-item",E:"toggleable-video-player-element",G:"gallery-images-container",T:"thumbnail-video-toggle-container",V:"toggleable-video-player-close-btn",a:"thumbnail-image-video-toggle",b:"thumbnail-playback-action-circle",c:"hiddenClassnames",d:"visibleClassnames",r:e.m(a``,"0 0 20 20","refresh",!0)}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("BBh_AjASYm",["C42E8rVVpA","CsxDAjmHZE","DUzIBJc2in"],(async(t,e,s)=>{let n=class extends e.s{async connectedCallback(){super.connectedCallback();if(this.querySelector("faceplate-carousel")){const t=this.querySelectorAll(".hidden");for(const e of t)e.classList.remove("hidden")}}render(){return e.x` `}};n=t._([t.e("community-spotlight")],n);const i="discover",o="subreddit_card";const c=e.s;let r=class extends c{constructor(){super(),this._handleCommunityJoin=this.handleCommunityJoin.bind(this),this._subscribed=!1,this.handleView=()=>{var e;t.f(this,(e=this.trackingArgs,t.b({source:i,action:"view",noun:o},e)))},new s.V(this,{consumeThreshold:2e3,onView:this.handleView})}get joinButton(){return this.querySelector("shreddit-join-button")}connectedCallback(){super.connectedCallback(),this.joinButton?.addEventListener("click",this._handleCommunityJoin)}disconnectedCallback(){super.disconnectedCallback(),this.joinButton?.removeEventListener("click",this._handleCommunityJoin)}handleCommunityJoin(){var e,s;t.f(this,(e=this._subscribed,s=this.trackingArgs,t.b({source:i,action:e?"unsubscribe":"subscribe",noun:o},s))),this._subscribed=!this._subscribed}render(){return e.x``}};r.styles=[t.t],t._([t.n({type:Object,attribute:"tracking-args"})],r.prototype,"trackingArgs",void 0),r=t._([t.e("community-spotlight-card")],r)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("BFDJQElz9q",["C42E8rVVpA","DUzIBJc2in"],(async(e,t)=>{var o,n;!function(e){e.SubredditFeed="SubredditFeed",e.CustomFeed="CustomFeed",e.AggregateFeed="AggregateFeed",e.BestOfRedditPage="BestOfRedditPage",e.CommentsPage="CommentsPage",e.Comment="Comment",e.DynamicFeed="DynamicFeed",e.ListingBelowSubredditPosts="ListingBelowSubredditPosts",e.ListingBelowLinkedPosts="ListingBelowLinkedPosts",e.PopularFeed="PopularFeed",e.PostStatsPage="PostStatsPage",e.ProfileFeed="ProfileFeed",e.ProfileFeed2="ProfileFeed2",e.ProfileTrendingConvos="ProfileTrendingConvos",e.BrandMentionFeed="BrandMentionFeed",e.BrandPostPerformanceFeed="BrandPostPerformanceFeed",e.ArticleFeed="ArticleFeed",e.SearchResultsPage="SearchResultsPage",e.RightRail="RightRail",e.ModChatChannels="ModChatChannels",e.ModQueue="ModQueue",e.ModQueueAll="ModQueueAll",e.ModNotesRail="ModNotesRail",e.ModLog="ModLog",e.ModTrainingQueue="ModTrainingQueue",e.UserManagement="UserManagement",e.ModRules="ModRules",e.ModRecruitment="ModRecruitment",e.ModWiki="ModWiki",e.ArticleDetails="ArticleDetails",e.RelatedPosts="RelatedPosts"}(o||(o={})),function(e){e.Scheduled="scheduled",e.Live="live",e.Ended="ended"}(n||(n={}));const a=e=>`${e}`.startsWith("t3_")?`${e}`:`t3_${e}`;function i(e){return e===o.ListingBelowLinkedPosts||e===o.ListingBelowSubredditPosts}const s=/^.*?\/(?:u|user|r)\/(?:[a-zA-Z0-9_-]+)\/comments\/(?[a-zA-Z0-9]+)(?:(?:\/|\?).*|$)/;const r=t=>c(t,e.f3)?t:void 0,c=(e,t)=>Object.values(t).includes(e),d=(e,t)=>void 0===e?void 0:t(e);function u(e){return e&&i(e)?"post_detail":"post"}function l(e){return u(e.viewContext??null)}const _=({archived:t,authorId:o,createdTimestamp:n,domain:a,id:i,feedIndex:s,nsfw:c,isStickied:u,isHighlighted:l,postTitle:_,postType:m,promoted:p,recommendationSource:b,recommendationSubredditId:f,recommendationSubredditName:g,score:w,spoiler:v,subredditId:h,subredditPrefixedName:T,viewType:P,commentCount:k,permalink:I,awardId:E,interactionFromHotkey:M})=>{const S=d(m,r),A=d(n,e.cv),L={name:T?.toLowerCase(),id:h},R=E?{id:E}:void 0,O=M?e.cO.HOTKEY:void 0;return{...R,post:{archived:t,author_id:o,created_timestamp:A,domain:a,id:i,nsfw:c,pinned:u,highlighted:l,promoted:p,score:w,spoiler:v,subreddit_id:h,subreddit_name:L.name,title:_,type:S,recommendation_source:b?.toLowerCase(),recommendation_source_subreddit_id:f,recommendation_source_subreddit_name:g,number_comments:k,url:I},screen:{view_type:e.ew(P)},subreddit:L,action_info:{position:s,trigger_type:O}}},m=t=>({..._(t),feed:e.ev()}),p=({fields:e,post:t,postIsTranslated:o,reason:n})=>{const{isMTSEOUserPage:a,postLanguage:i,translationLanguage:s}=t;return e={...e,post:{...e.post,language:i,translation_language:o?s:"original",translation_state:o,translation_reason:o?a?"mt_seo":"immersive_auto":"original",translatable_state:t.isTranslatable?"is_translatable":"is_not_translatable"},...n&&{action_info:{...e.action_info,reason:n}}}};function b(e,t){return e&&t?{ad_metadata:{impression_id:e,placement:t}}:void 0}function f(e){return{...p({fields:m(e),post:e,postIsTranslated:!!e.isPostTranslated,withTranslationMetrics:!0}),new_award:{id:e.awardId,is_content_eligible:Boolean(e.isAwardable)}}}const g=(t,o,n={})=>e.b({source:l(t),action:"click",noun:o},{...t.viewContext&&i(t.viewContext)?f(t):n,feed:e.ev()}),w=/^.*\/r\/.*\/comments\/(?[a-zA-Z0-9]+)\/.*\/?$/;const v=/\/r\/([^/]+)\/$/;return{$:function(e){const t=(e?.getAttribute("href")||"").match(v);return t?t[1]:""},A:t=>e.b({source:u(t),action:"click",noun:"post_overflow_menu"}),B:"max-h-[253px] overflow-hidden s:max-h-[318px] m:max-h-[337px] l:max-h-[352px] xl:max-h-[452px]",C:"hidden",D:t=>e.b({source:"translate_button",action:"view",noun:"translation_settings"},f(t)),get E(){return n},F:t=>{const o=f(t);return e.b({source:"overflow_menu",action:"click",noun:"translate_post"},{...o,action_info:{...o.action_info,reason:t.isPostTranslated?e.bI.SEE_ORIGINAL:e.bI.SEE_TRANSLATION}})},G:(t,o)=>e.b({source:u(t),action:"click",noun:"report"},o),H:t=>e.b({source:"ad_overflow",action:"hide",noun:"ad"},t),I:(t,o)=>e.b({source:u(t),action:"click",noun:"overflow_show_less"},o),J:t=>e.b({source:u(t),action:"click",noun:"edit"}),K:(t,o,n,a)=>e.b({source:u(t),action:"click",noun:o?"edit_post_flair":"add_post_flair"},{post:{id:n,author_id:a}}),L:t=>e.b({source:u(t),action:"click",noun:"update_post_flair"}),M:"overflow-hidden h-[60px] embed-xs:h-[80px]",N:t=>e.b({source:u(t),action:"click",noun:"save"}),O:t=>e.b({source:u(t),action:"click",noun:"overflow_rec_context"}),get P(){return o},Q:(t,o)=>e.b({source:u(t),action:o?"undo":"click",noun:"follow"}),R:"read-more-click",S:t=>e.b({source:u(t),action:"click",noun:"unpin"}),T:"h-[316px]",U:t=>e.b({source:u(t),action:"click",noun:"pin"}),V:t=>e.b({source:u(t),action:"click",noun:"delete"}),W:({markedAsSpoiler:t,viewContext:o})=>e.b({source:u(o),action:"click",noun:t?"mark_spoiler":"unmark_spoiler"}),X:({markedAsNsfw:t,viewContext:o})=>e.b({source:u(o),action:"click",noun:t?"mark_nsfw":"unmark_nsfw"}),Y:({markedAsBrandAffiliate:t,viewContext:o})=>e.b({source:u(o),action:"click",noun:t?"mark_brand_affiliate":"unmark_brand_affiliate"}),Z:({turnNotificationsOn:t,viewContext:o})=>e.b({source:u(o),action:"click",noun:t?"turn_notifications":"unsend_reply_notifications"}),_:t=>e.b({source:u(t),action:"click",noun:"hide"}),a:e=>`${e}`.startsWith("t1_")?`${e}`:`t1_${e}`,a0:(t,o)=>e.b({source:"post"===o?"post":"post_detail",action:t,noun:"post"===o?"post":"comment"},{action_info:{trigger_type:e.cO.HOTKEY}}),a1:t=>e.b({source:"post",action:"leave",noun:"post",visibility:{on_screen_timestamp:t.becameVisibleOnScreenTimestamp,off_screen_timestamp:Date.now()}},m(t)),a2:t=>e.b({source:"post",action:"consume",noun:"post"},{...p({fields:m(t),post:t,postIsTranslated:!!t.isPostTranslated,withTranslationMetrics:!0}),new_award:{id:t.awardId,is_content_eligible:Boolean(t.isAwardable)}}),a3:t=>e.b({source:l(t),action:"click",noun:"read_more"},m(t)),a4:function(t){return t===e.ah.Popular},a5:function(t){return t===e.ah.Home},a6:i,a7:e=>g(e,"share",_(e)),a8:e=>g(e,"share_copy",_(e)),a9:(o,n)=>{switch(t.H(o,"postClickLocation")){case e.f6.SUBREDDIT_LINK:return(e=>g(e,"subreddit",_(e)))(n);case e.f6.JOIN:return(e=>g(e,"subscribe",_(e)))(n);case e.f6.OVERFLOW_BUTTON:case e.f6.COMMENTS_BUTTON:case e.f6.VOTE:case e.f6.SHARE:case e.f6.VIDEO_PLAYER:return null;case e.f6.TEXT_BODY:return(e=>g(e,"text",_(e)))(n);case e.f6.DEVVIT_SURFACE:return(e=>g(e,"custom_post",_(e)))(n);default:return(e=>g(e,"post",_(e)))(n)}},aa:t=>e.b({source:l(t),action:"click",noun:"vote_try"},_(t)),ab:t=>e.b({source:"subreddit_hovercard",action:"view",noun:"hover_subreddit_hovercard"},m(t)),ac:t=>e.b({source:"user_hovercard",action:"view",noun:"hover_user_hovercard"},m(t)),ad:function(e){const t=e.match(s),o=t?.groups?.postId;if(o)return a(o)},ae:(t,o)=>{const n=o?f(o):{};return e.b({source:"overflow_menu",action:"click",noun:"translate_comment"},{...n,comment:{...t,translation_language:t.translation_state?t.translation_language:"original"},action_info:{...n.action_info,reason:t.translation_state?e.bI.SEE_ORIGINAL:e.bI.SEE_TRANSLATION}})},b:t=>{const o=f(t);return e.b({source:"translate_button",action:"view",noun:"post"},{...o,action_info:{...o.action_info,reason:t.isPostTranslated?e.b9:e.ba}})},c:2e3,d:function(e){switch(e){case o.AggregateFeed:case o.SubredditFeed:case o.CustomFeed:case o.ListingBelowLinkedPosts:case o.ListingBelowSubredditPosts:case o.PopularFeed:case o.ProfileFeed:case o.ProfileFeed2:case o.BrandMentionFeed:case o.BrandPostPerformanceFeed:case o.ArticleDetails:case o.ModQueue:case o.ModQueueAll:case o.ModLog:case o.ModNotesRail:return!0;case o.CommentsPage:default:return!1}},e:a,f:"partial-update",g:_,h:function(e){return`https://www.redditmedia.com/mediaembed/${e.replace("t3_","")}/`},i:function(e){return e===o.CommentsPage},j:e=>e.startsWith("t3_"),k:p,l:m,m:t=>e.b({source:l(t),action:"click",noun:"clearvote"},m(t)),n:t=>e.b({source:l(t),action:"click",noun:"downvote"},{...p({fields:m(t),post:t,postIsTranslated:!!t.isPostTranslated,withTranslationMetrics:!0})}),o:t=>e.b({source:l(t),action:"view",noun:"post"},f(t)),p:(t,o)=>e.b({source:"translate_button",action:"view",noun:"post"},p({fields:m(t),post:t,postIsTranslated:o,reason:o?"on":"off"})),q:t=>{const o=f(t);return e.b({source:"translate_button",action:"click",noun:"post_indicator"},{...o,action_info:{...o.action_info,reason:t.isPostTranslated?e.bI.SEE_ORIGINAL:e.bI.SEE_TRANSLATION}})},r:function(e){const t=(e?.getAttribute("href")||"").match(w),o=t?.groups?.postId;return o?a(o):""},s:e=>g(e,"view_all_comments",_(e)),t:t=>e.b({source:"event_post",action:"click",noun:"rsvp"},{..._(t),...b(t.impressionId,t.placement)}),u:t=>e.b({source:l(t),action:"click",noun:"upvote"},{...p({fields:m(t),post:t,postIsTranslated:!!t.isPostTranslated,withTranslationMetrics:!0})}),v:t=>e.b({source:"event_post",action:"click",noun:"un_rsvp"},{..._(t),...b(t.impressionId,t.placement)}),w:e=>g(e,"comments",_(e)),x:"flex",y:t=>e.b({source:"translate_button",action:"view",noun:"post_banner"},f(t.post)),z:t=>{const o=f(t.post);return e.b({source:"translate_button",action:"click",noun:"post_banner"},{...o,action_info:{...o.action_info,reason:t?.isPostTranslated?e.bI.SEE_ORIGINAL:e.bI.SEE_TRANSLATION},is_mod:t.isMod})}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CHpnYscvgU.js",import.meta.url,"CHpnYscvgU");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q"); SML.dm("BG8P3or1N1",["C42E8rVVpA","CHpnYscvgU","BFDJQElz9q"],(async(e,t,a)=>{const n={get:()=>{if(!e.a0.isAvailable())return;const t=e.a0.getItem(e.a1.I18nPostTranslationBanner);return t?JSON.parse(t):void 0},set:t=>{e.a0.isAvailable()&&e.a0.setItem(e.a1.I18nPostTranslationBanner,JSON.stringify(t))},update:e=>{const t=n.get()||{};n.set({...t,...e})}},r="shreddit_mt_immersive_en",o=new Set,s=t=>{if(o.has(t))return;o.add(t);const a=e.am(t);return e.an({experimentName:t,variant:a??"",experimentVersion:""})};return{P:n,i:function(){const e=window.location?.search??"";return new URLSearchParams(e).has("tl")},l:t=>{const{error:a,ids:n,element:r,componentName:o}=t,s=e.b({source:"translate_button",action:"error",noun:"app"},{action_info:{reason:a,type:o},setting:{value:n.toString(),values:n}});e.f(r,s)},o:{post:(t,n)=>{if(s(r),t.id){const r=a.b({archived:n?.archived,authorId:n?.authorId,createdTimestamp:n?.createdTimestamp,domain:n?.domain,id:n?.id??"",nsfw:n?.nsfw,promoted:n?.promoted,score:n?.score,spoiler:n?.spoiler,subredditId:n?.subredditId,subredditPrefixedName:n?.subredditPrefixedName,postTitle:n?.postTitle,postType:n?.postType,recommendationSource:n?.recommendationSource,commentCount:n?.commentCount,permalink:n?.permalink,postLanguage:n?.postLanguage,translationLanguage:n?.translationLanguage,isPostTranslated:n?.isPostTranslated});e.f(t,r)}},comment:(a,n)=>{s(r);const o=t.b(n);e.f(a,o)}}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("BHU9gAlx9d",["C42E8rVVpA","CsxDAjmHZE"],(async(t,e)=>{let s=class extends e.s{constructor(){super(...arguments),this.open=!1,this._events=new t.E(this),this._firstUpdate=!0,this.updated=t=>{t.has("open")&&!this._firstUpdate&&(this.open?this._expand():this._collapse()),this._firstUpdate=!1},this._expand=()=>{this._content.style.display="block",this.offsetHeight!==this._content.offsetHeight&&(i(this,this._content.offsetHeight),this._content.style.opacity="1")},this._collapse=()=>{0!==this.offsetHeight&&(i(this,0),this._content.style.opacity="0")},this._onTransitionEnd=()=>{this.open?this.style.height="":(this.open=!1,this._content.style.display="none"),this.style.overflowY="visible"},this._handler=this._events.define("transitionend",this._onTransitionEnd)}connectedCallback(){super.connectedCallback(),this._content=this.querySelector("[faceplate-auto-height-animator-content]"),null!=this._content&&(this.style.transition="height 222ms ease",this._content.style.transition="opacity 222ms ease",this.open||(this.style.height="0px",this._content.style.display="none"),this.setAttribute("connected",""))}createRenderRoot(){return this}};function i(t,e){t.style.height=`${t.offsetHeight}px`,t.style.overflowY="hidden",window.requestAnimationFrame((()=>{t.style.height=`${e}px`}))}return t._([t.n({type:Boolean,reflect:!0})],s.prototype,"open",void 0),s=t._([t.e("faceplate-auto-height-animator")],s),{get FaceplateAutoHeightAnimator(){return s}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("BI1JuD5RPj",["C42E8rVVpA","CsxDAjmHZE"],(async(e,r)=>{let i=class extends r.s{constructor(){super(...arguments),this.revealed=!1,this.blockRevealOnClick=!1}static get styles(){return r.i`.outer{background:var(--color-category-spoiler);border-radius:2px;cursor:pointer;line-height:21px;transition:background ease-out 1s;border:none;padding:0;font:inherit;color:inherit;margin-right:.25rem}.inner{opacity:0;transition:opacity ease-out 1s;margin-right:-.25rem}.revealed.outer{background:0 0}.revealed .inner{opacity:1}`}revealSpoiler(e){this.revealed||e.preventDefault(),this.revealed=!0}handleKeyPress(e){"Enter"!==e.key&&" "!==e.key||this.revealSpoiler(e)}render(){return this.blockRevealOnClick?r.x` `:r.x` `;}};e._([e.v()],i.prototype,"revealed",void 0),e._([e.n({type:Boolean,attribute:"block-reveal-on-click"})],i.prototype,"blockRevealOnClick",void 0),i=e._([e.e("shreddit-spoiler")],i)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("BIrqd8tOEI",["C42E8rVVpA"],(async e=>{const a="devplatform",r=a=>{switch(a){case e.ah.PostDetail:return"pdp";case e.ah.Profile:return"profile";case e.ah.Community:return"subreddit";case e.ah.Embed:return"embed";case e.ah.Home:case e.ah.Popular:case e.ah.All:case e.ah.CustomFeed:case e.ah.GeoCuratedFeed:case e.ah.UserPosts:case e.ah.ModQueue:case e.ah.ModQueueAll:case e.ah.SearchResults:return"feed";default:return""}};var t;!function(e){e.all="all",e.arena="arena",e.conversation="conversation",e.custom="custom",e.embed="embed",e.home="home",e.modQueue="mod_queue",e.modQueueAll="mod_queue_all",e.news="news",e.popular="popular",e.profile="profile",e.promotedSearchTrend="promoted_search_trend",e.read="read",e.search="search",e.subreddit="subreddit",e.user="user",e.watch="watch"}(t||(t={}));const o=a=>{switch(a){case e.ah.All:return t.all;case e.ah.ArenaFeed:return t.arena;case e.ah.Community:return t.subreddit;case e.ah.CustomFeed:case e.ah.GeoCuratedFeed:return t.custom;case e.ah.Embed:return t.embed;case e.ah.Home:return t.home;case e.ah.ModQueue:return t.modQueue;case e.ah.ModQueueAll:return t.modQueueAll;case e.ah.Popular:return t.popular;case e.ah.Profile:return t.profile;case e.ah.SearchResults:return t.search;case e.ah.UserPosts:return t.user;default:return""}};return{D:a,a:(e,a)=>{if(URL.canParse(e)){const r=new URL(e);return r.searchParams.set("entry_point",a),r.toString()}return e},c:e=>({source:a,action:e.action,noun:e.noun,devplatform_custom_post_info:{post_id:e.postId,subreddit_id:e.subredditId,block_type:e.blockType,presentation_context:e.pageType?r(e.pageType):"",feed_type:e.pageType?o(e.pageType):"",watermark:e.watermark,post_chrome:e.post_chrome},devplatform:{runtime:"web",installation_id:e.appInstallationId,app_id:e.appId,app_slug:e.appSlug,app_name:e.appSlug,app_version_number:e.appVersionNumber,public_api_version:e.appPublicApiVersion,internal_entry_point:e.internalEntryPoint||"",app_recommendation_criteria:e.appRecommendationCriteria||""},init_info:e.init_info,request:{user_agent:e.userAgent},post:e.post,definition:e.definition})}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("BJn-lERYAs",["C42E8rVVpA","CsxDAjmHZE","BFDJQElz9q","DUzIBJc2in"],(async(e,t,i)=>{var a=t.i`.image-caption-container-collapsed{background:rgba(0,0,0,.6)}.image-caption-container-expanded{background:rgba(0,0,0,.8)}.text-primary-blue{color:#629fff}`;let o=class extends t.s{constructor(){super(...arguments),this.imageCaption="",this.outboundUrl="",this.shortenedUrl="",this.imageIndex="",this.isMore=!0,this.shouldShowMoreLessButton=()=>{const e=this.shadowRoot?.querySelector("figCaption")?.querySelector(`#gallery-image-caption-text-${this.imageIndex}`);if((e?.scrollWidth||0)>(e?.clientWidth||0)||(e?.scrollHeight||0)>(e?.clientHeight||0)){const e=this.shadowRoot?.querySelector("figCaption")?.querySelector(`#caption-more-button-${this.imageIndex}`);e?.classList?.remove(i.C),e?.classList?.add(i.x)}}}static get styles(){return[e.t,a]}getTruncateTextOverFlow(){return this.outboundUrl?"truncate":"line-clamp-2"}showMoreLessButtonText(){return this.isMore?"more":"less";}updateCaptionContainer(){const e=this.shadowRoot?.querySelector("figCaption"),t=e?.querySelector(`#gallery-image-caption-container-${this.imageIndex}`),i=e?.querySelector(`#gallery-image-caption-text-container-${this.imageIndex}`),a=e?.querySelector(`#gallery-image-caption-text-${this.imageIndex}`);this.isMore?(i?.classList?.remove("overflow-auto"),a?.classList?.add(this.getTruncateTextOverFlow()),t?.classList?.remove("image-caption-container-expanded"),t?.classList?.add("image-caption-container-collapsed")):(i?.classList?.add("overflow-auto"),a?.classList?.remove(this.getTruncateTextOverFlow()),t?.classList?.remove("image-caption-container-collapsed"),t?.classList?.add("image-caption-container-expanded"))}handleMoreLessButtonClicked(e){e.stopPropagation(),e.preventDefault(),this.isMore=!this.isMore,this.updateCaptionContainer();const t=this.shadowRoot?.querySelector("figCaption")?.querySelector(`#caption-more-button-${this.imageIndex}`),i=t?.querySelector(`#caption-more-button-text-${this.imageIndex}`);i&&(i.textContent=this.showMoreLessButtonText())}showMoreLessButton(){return t.x`${e.Z({appearance:"primary",size:e.ac.Small,attributes:{className:"text-primary-blue not-italic font-bold text-12 flex items-end bg-transparent\n hover:bg-transparent focus:bg-transparent active:bg-transparent visited:bg-transparent\n hidden rounded-none",onclick:this.handleMoreLessButtonClicked,id:`caption-more-button-${this.imageIndex}`},children:t.x`
${this.showMoreLessButtonText()}
`})}`}firstUpdated(){this.shouldShowMoreLessButton()}render(){return t.x`
`}};return e._([e.n({type:String,attribute:"image-caption"})],o.prototype,"imageCaption",void 0),e._([e.n({type:String,attribute:"outbound-url"})],o.prototype,"outboundUrl",void 0),e._([e.n({type:String,attribute:"shortened-url"})],o.prototype,"shortenedUrl",void 0),e._([e.n({type:String,attribute:"image-index"})],o.prototype,"imageIndex",void 0),o=e._([e.e("gallery-caption")],o),{get GalleryCaption(){return o}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("BUnsiaD7oQ",["C42E8rVVpA","DUzIBJc2in"],(async(e,a)=>{var t,n,o,r,i,c,d,s,u,l,p,f,m,_,y,h;function w(e){window.Sentry?.captureMessage?.(e)}function g(e){return e?.[0]?.message??a.cc.genericErrorMessage()}async function v(t,n){const o=a.U.get(t);if(!o)throw new Error(a.cc.unsupportedMimetype(t));const r={mimetype:o},i=n?await async function(a,t){try{const n=await fetch("https://gql-fed.reddit.com",{method:"POST",headers:{Accept:"application/json",Authorization:`bearer ${t}`,"Content-Type":"application/json","X-Reddit-Loid":e.ad.get("loid")??""},body:JSON.stringify({extensions:{persistedQuery:{version:1,sha256Hash:"cd9afac180f0cc91f6b6a4be46385de14fc328090a59b2cdc5e9666cb18779f1"}},operationName:e.H.CreateMediaUploadLease,variables:{input:a}})});if(n.ok)return n.json();const o=await n.text();throw w(`Media upload lease request to gql-fed.reddit.com failed with status ${n.status}: ${o}`),new Error(o)}catch(e){throw w(`Unable to complete the media upload lease grant: ${e}`),e}}(r,n):await e.C({operation:e.H.CreateMediaUploadLease,variables:{input:r}});if(i.errors?.length)throw new Error(g(i.errors));const c=i.data.createMediaUploadLease;if(c?.ok)return{mediaId:c.mediaId,uploadLeaseUrl:c.uploadLease.uploadLeaseUrl,uploadLeaseHeaders:c.uploadLease.uploadLeaseHeaders};throw new Error(g(c?.errors))}!function(e){e.Unknown="unknown",e.VOD="vod",e.Gif="gif",e.LiveVideo="live-video",e.Image="image",e.Video="video"}(t||(t={})),function(e){e.Landscape="landscape",e.Portrait="portrait"}(n||(n={})),function(e){e.DirectUpload="direct_upload",e.ScrapedLink="scraped_link",e.ImageOptimizer="image_optimizer"}(o||(o={})),function(e){e.Hls="hls",e.SingleFile="single_file"}(r||(r={})),function(e){e.Hls="hls",e.Mp4="mp4"}(i||(i={})),function(e){e.Autoplay="autoplay",e.Click="click"}(c||(c={})),function(e){e.Buffering="buffering",e.Paused="paused",e.Playing="playing"}(d||(d={})),function(e){e.CommentPlayer="comment_player",e.InFeedPlayer="in_feed_player",e.PostDetailScreen="post_detail_screen",e.GalleryMode="gallery_mode",e.VideoFeedV1="video_feed_v1",e.LiveFeedV1="live_feed_v1",e.TheaterMode="theater_mode",e.DiscoveryUnit="discovery_unit"}(s||(s={})),function(e){e.Videoplayer="videoplayer"}(u||(u={})),function(e){e.Auto="auto",e.Background="background",e.Click="click",e.End="end",e.Error="error",e.Scroll="scroll",e.Served="served",e.Start="start",e.Switch="switch",e.Trace="trace",e.View="view"}(l||(l={})),function(e){e.Autoplay="autoplay",e.Bitrate="bitrate",e.CaptionsDisabled="overflow_captions_disabled",e.CaptionsEnabled="overflow_captions_enabled",e.Download="download",e.Pause="pause",e.Performance="performance",e.Play="play",e.Rebuffer="rebuffer",e.RecommendationOverlay="recommendation_overlay",e.Replay="replay",e.Video="video"}(p||(p={})),function(e){e.Videoplayer="videoplayer"}(f||(f={})),function(e){e.Click="click",e.Continue="continue",e.IsFullyViewable="is_fully_viewable",e.IsViewable="is_viewable",e.Pause="pause",e.PlayExpanded="play_expanded",e.PlayWithSound="play_with_sound",e.Start="start",e.Watch="watch",e.WatchPercent25="watch_25_percent",e.WatchPercent50="watch_50_percent",e.WatchPercent75="watch_75_percent",e.WatchPercent95="watch_95_percent",e.WatchPercent100="watch_100_percent",e.WatchSeconds2="watch_2_seconds",e.WatchSeconds3="watch_3_seconds",e.WatchSeconds5="watch_5_seconds",e.WatchSeconds10="watch_10_seconds"}(m||(m={})),function(e){e.Pause="pause",e.Play="play",e.Seek="seek",e.Mute="mute",e.Unmute="unmute",e.Replay="replay",e.Video="video"}(_||(_={})),function(e){e.Autoplay="autoplay",e.Manual="manual"}(y||(y={})),function(e){e.Auto="auto",e.Buffer="buffer",e.Manual="manual"}(h||(h={}));const b=e=>({error:e||a.cc.uploadErrorMessage()});return{get A(){return c},get F(){return i},get M(){return n},get P(){return r},get Q(){return u},get T(){return m},get a(){return t},get b(){return l},get c(){return p},get d(){return d},get e(){return _},u:async function(n,o={}){const{bearerToken:r,trackEvent:i,eventSource:c}=o,d=!!i&&!!c;let s,u;try{try{s=await v(n.type,r),u=n.type.includes("video")?t.Video:t.Image,d&&i(e.b({source:c,action:"get",noun:"media_lease"},{media:{id:s.mediaId,type:u},action_info:{success:!!s.mediaId}}))}catch(a){throw d&&i(e.b({source:c,action:"get",noun:"media_lease"},{action_info:{success:!1,reason:a?.message}})),new Error(a)}const o=n.size,l=n.type.split("/")[1];d&&i(e.b({source:c,action:"upload_start",noun:u},{media:{id:s.mediaId,type:u,size:o,format:l}}));const p=await a.X(n,s);return p?(d&&i(e.b({source:c,action:"upload",noun:u},{media:{id:s.mediaId},action_info:{success:!0}})),{url:p,mediaId:s.mediaId}):(d&&i(e.b({source:c,action:"upload",noun:u},{media:{id:s.mediaId},action_info:{success:!1}})),b())}catch(a){return l=a.message,window.Sentry?.captureMessage?.(`Media file upload failed with error: ${l}`),d&&u&&i(e.b({source:c,action:"upload",noun:u},{media:{id:s?.mediaId},action_info:{success:!1,reason:a?.message}})),b(a.message)}var l}}})); SML.dm("BWUv70NGv2",[],(async()=>{var t,T,S;return function(t){t.MODERATOR="moderator",t.COMMUNITY_STATUS="community_status"}(t||(t={})),function(t){t.VIEW="view",t.CLICK="click"}(T||(T={})),function(t){t.STATUS_EDIT="status_edit",t.STATUS_CANCEL="status_cancel",t.STATUS_CREATE="status_create",t.STATUS_DELETE="status_delete",t.STATUS_LINK="status_link",t.STATUS_DISPLAY="status_display",t.STATUS_SUB_LINK="subreddit_link"}(S||(S={})),{get A(){return T},get N(){return S},get S(){return t}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DMLIZ0D7jc.js",import.meta.url,"DMLIZ0D7jc");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("BYmwHsayzU",["C42E8rVVpA","CsxDAjmHZE","DMLIZ0D7jc","DUzIBJc2in"],(async(e,t,s,a)=>{let n=class extends t.s{constructor(){super(...arguments),this.id="",this.searchBase=null,this.isExpanded=!1,this.pubsub=new e.m(this),this.handleFlairExpansionStateChanged=e=>{this.isExpanded=e.isExpanded,this.updateExpandedState()},this.handleExpandClick=()=>{this.isExpanded=!this.isExpanded,this.updateExpandedState(),this.searchBase&&this.searchBase.updateFlairExpansionState(this.isExpanded)}}connectedCallback(){super.connectedCallback(),this.isExpanded=!1,this.pubsub.subscribe(e.T.SearchFlairExpansionStateChanged,this.handleFlairExpansionStateChanged),this.searchBase=document.querySelector("reddit-search-large")||document.querySelector("reddit-search-small")}disconnectedCallback(){super.disconnectedCallback();const e=this.shadowRoot?.querySelector('slot[name="expand-button"]');e&&e.removeEventListener("click",this.handleExpandClick)}updateExpandedState(){const e=this.shadowRoot?.querySelector('slot[name="content"]'),t=this.shadowRoot?.querySelector('slot[name="expand-button"]');if(e){e.assignedElements().forEach((e=>{this.isExpanded?(e.classList.add("!max-h-none","!overflow-visible"),e.classList.remove("max-h-[2em]","overflow-hidden")):(e.classList.add("max-h-[2em]","overflow-hidden"),e.classList.remove("!max-h-none","!overflow-visible"))}))}if(t){t.assignedElements().forEach((e=>{this.isExpanded?e.classList.add("hidden"):e.classList.remove("hidden");const t=e.querySelector("button");t&&t.setAttribute("aria-expanded",this.isExpanded.toString())}))}}setupEventListeners(){const e=this.shadowRoot?.querySelector('slot[name="expand-button"]');e&&e.addEventListener("click",this.handleExpandClick)}firstUpdated(){this.setupEventListeners(),this.updateExpandedState()}render(){return t.x` `}};e._([e.n({type:String})],n.prototype,"id",void 0),e._([e.v()],n.prototype,"searchBase",void 0),e._([e.v()],n.prototype,"isExpanded",void 0),n=e._([e.e("search-flair-expandable-list")],n);let d=class extends t.s{constructor(){super(...arguments),this.open=!1,this.id="",this.handleClick=()=>{const e=!this.open;this.updateLocalStorage(e),this.open=e,this.toggleHeaderTrackers()}}toggleHeaderTrackers(){this.trackers?.forEach((e=>{e.disabled=!e.disabled}))}updateLocalStorage(t){const s=a.v(e.a1.SearchTypeaheadExpanded)??{};s[this.id]=!!t,a.u(e.a1.SearchTypeaheadExpanded,s)}connectedCallback(){super.connectedCallback(),this.closest("summary")?.addEventListener("click",this.handleClick)}disconnectedCallback(){super.disconnectedCallback(),this.closest("summary")?.removeEventListener("click",this.handleClick)}createRenderRoot(){return this}};e._([e.aY(s.S)],d.prototype,"trackers",void 0),e._([e.n({reflect:!0,type:Boolean,attribute:"open"})],d.prototype,"open",void 0),e._([e.n({type:String})],d.prototype,"id",void 0),d=e._([e.e("search-typeahead-expandable-section")],d)})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("BeSXmWRKRU",["CsxDAjmHZE"],(async a=>{const{svg:n}=a.g();return{c:a.m(n``,"0 0 20 20","comment"),i:a=>!!a&&(a.indexOf("profileIcon_snoo")>-1||a.indexOf("snoovatar/avatars")>-1||a.endsWith("snoovatar_anonymous.svg"))}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CvOrQNTrjb.js",import.meta.url,"CvOrQNTrjb");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DMFEgBklTz.js",import.meta.url,"DMFEgBklTz");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./7ymiBBk8xO.js",import.meta.url,"7ymiBBk8xO");SML.di("./CZFRGXDPUQ.js",import.meta.url,"CZFRGXDPUQ");SML.di("./Ceb0ABsHlF.js",import.meta.url,"Ceb0ABsHlF");SML.di("./BUnsiaD7oQ.js",import.meta.url,"BUnsiaD7oQ");SML.di("./CMwQRCekeQ.js",import.meta.url,"CMwQRCekeQ");SML.di("./UD2pUVjMzE.js",import.meta.url,"UD2pUVjMzE");SML.di("./B-LgD4K8b5.js",import.meta.url,"B-LgD4K8b5");SML.di("./B7xOUSlR-V.js",import.meta.url,"B7xOUSlR-V");SML.di("./By3M4InPRM.js",import.meta.url,"By3M4InPRM");SML.di("./ChVzN5arel.js",import.meta.url,"ChVzN5arel"); SML.dm("BgXAJ8KoWz",["C42E8rVVpA","CvOrQNTrjb","CsxDAjmHZE","DMFEgBklTz","DUzIBJc2in","7ymiBBk8xO","CZFRGXDPUQ","Ceb0ABsHlF","BUnsiaD7oQ","CMwQRCekeQ","UD2pUVjMzE","B-LgD4K8b5","B7xOUSlR-V","By3M4InPRM","ChVzN5arel"],(async(t,e,i)=>{const o=e.W(i.s);let r=class extends o{constructor(){super(...arguments),this.adEvents=[],this.impressionId="0",this.isBlank=!1,this.adType=t.eB.DISPLAY,this.placement=t.a8.BLANK_ONLY,this.hasToggleableVideo=!1,this._isConnected=!1,this.toggleableVideoAdController=null}async connectedCallback(){super.connectedCallback(),this._isConnected||(this.enableAdObserver({postElement:this,adType:this.adType,events:e.e(this.adEvents),postId:this.postId,impressionId:this.impressionId,dimensions:this.dimensions}),this._isConnected=!0,await this.resolveVideoAdDependencies())}async resolveVideoAdDependencies(){if(this.adType!==t.eB.VIDEO||!this.hasToggleableVideo)return;const{ToggleableVideoAdController:e}=await SML.di("./B-LgD4K8b5.js",import.meta.url,"B-LgD4K8b5").then((function(t){return t.i}));this.toggleableVideoAdController=new e(this,((t,e)=>{this.adMeasurer&&(this.adMeasurer.dimensions={height:t,width:e})}))}disconnectedCallback(){this.adMeasurer&&this.adMeasurer.handleUnload(),super.disconnectedCallback()}render(){return i.x``}};t._([t.n({type:Array,attribute:"ad-events"})],r.prototype,"adEvents",void 0),t._([t.n({type:String,attribute:"post-id"})],r.prototype,"postId",void 0),t._([t.n({type:String,attribute:"impression-id"})],r.prototype,"impressionId",void 0),t._([t.n({type:String,attribute:"outbound-link-url",reflect:!0})],r.prototype,"outboundLinkUrl",void 0),t._([t.n({type:Boolean,attribute:"is-blank"})],r.prototype,"isBlank",void 0),t._([t.n({type:String,attribute:"ad-type"})],r.prototype,"adType",void 0),t._([t.n({type:Object,attribute:!0})],r.prototype,"dimensions",void 0),t._([t.n({type:String,attribute:"encrypted-tracking-payload"})],r.prototype,"encryptedTrackingPayload",void 0),t._([t.n({type:Array,attribute:"additional-event-metadata"})],r.prototype,"additionalEventMetadata",void 0),t._([t.n({type:String,attribute:"ad-transparency-encoded-data"})],r.prototype,"adTransparencyEncodedData",void 0),t._([t.n({type:String,attribute:"placement"})],r.prototype,"placement",void 0),t._([t.n({type:String,attribute:"ads-correlation-id"})],r.prototype,"adsCorrelationId",void 0),t._([t.n({type:Object,attribute:"ad-user-targeting-info"})],r.prototype,"adUserTargeting",void 0),t._([t.n({type:Boolean,attribute:"has-toggleable-video"})],r.prototype,"hasToggleableVideo",void 0),r=t._([t.e("ad-event-tracker")],r)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("Bo8KKK1jP_",["C42E8rVVpA","BFDJQElz9q","CsxDAjmHZE"],(async(e,t,s)=>{class n{constructor(e,t){this.hasPageUnloaded=!1,this.handleIntersectionObserverEnter=()=>{this.isPostInViewport||(this.isPostInViewport=!0,this.becameVisibleOnScreenTimestamp=Date.now())},this.handleIntersectionObserverLeave=()=>{const e=this.isPostInViewport;this.isPostInViewport=!1,e&&this.handleConsume()},this.handleDocumentVisibilityChange=e=>{this.isPostInViewport&&(e?(this.hasPageUnloaded=!1,this.becameVisibleOnScreenTimestamp=Date.now()):e||this.hasPageUnloaded||this.handleConsume())},this.onBeforeUnloadCallback=()=>{this.hasPageUnloaded=!0,this.isPostInViewport&&this.handleConsume()},this.elementToTrack=e,this.SAN=t}handleConsume(){this.becameVisibleOnScreenTimestamp&&Date.now()-this.becameVisibleOnScreenTimestamp>t.c&&e.f(this.elementToTrack,this.SAN)}}class o{constructor(e){this.host=e,this.postConsumeTrackingController=new n(e,{source:"post",action:"consume",noun:"post"}),this.host.addController(this)}hostConnected(){new e.ar(this.host,this.host,{rootMargin:"0px"}),this.host.addEventListener("faceplate-enter",this.postConsumeTrackingController.handleIntersectionObserverEnter),this.host.addEventListener("faceplate-leave",this.postConsumeTrackingController.handleIntersectionObserverLeave),e.ax.subscribe(this.postConsumeTrackingController.onBeforeUnloadCallback,{shouldBeCalledFirst:!0}),e.ay(this.postConsumeTrackingController.handleDocumentVisibilityChange,{immediate:!0})}hostDisconnected(){this.host.removeEventListener("faceplate-enter",this.postConsumeTrackingController.handleIntersectionObserverEnter),this.host.removeEventListener("faceplate-leave",this.postConsumeTrackingController.handleIntersectionObserverLeave),e.ax.unsubscribe(this.postConsumeTrackingController.onBeforeUnloadCallback),e.az(this.postConsumeTrackingController.handleDocumentVisibilityChange)}}let i=class extends s.s{connectedCallback(){super.connectedCallback(),this.postConsumeTrackingController=new o(this)}disconnectedCallback(){super.disconnectedCallback(),this.postConsumeTrackingController&&e.s(this,this.postConsumeTrackingController)}render(){return s.x``}};return i=e._([e.e("post-consume-tracker")],i),{C:n}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./BVwlQhSoPB.js",import.meta.url,"BVwlQhSoPB");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("BoLhyQBLVt",["C42E8rVVpA","CsxDAjmHZE","BVwlQhSoPB","DUzIBJc2in"],(async(t,e,o,i)=>{let a=class extends e.s{constructor(){super(...arguments),this.position="bottom",this.mouseEnterDelay=750,this.triggerEvent="hover",this.appearance="neutral",this.emitter=i.l(this),this._timeoutID=null,this._popperController=new o.P(this,{position:this.position,variantFlipOrder:{start:"s",middle:"m",end:"e"},referenceElementKey:"referenceElement",popperElementKey:"_tooltip"}),this._eventUsedMap=new WeakMap,this.updated=t=>{t.has("position")&&this._popperController.updateOptions({position:this.position})},this.handleDocumentClick=t=>{if(!(t.target instanceof HTMLElement)||this.hidden)return;if(t.target.closest(this.tagName.toLowerCase())===this)return;this._eventUsedMap.has(t)||this.close()},this.handleEscape=t=>{"Escape"===t.key&&this.close()},this.addListenersWhileOpened=()=>{document.addEventListener("click",this.handleDocumentClick),document.addEventListener("keydown",this.handleEscape)},this.cleanupListenersWhileOpened=()=>{document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("keydown",this.handleEscape)}}get referenceElement(){return this.triggers[0]??this}static get styles(){return[e.i`:host{display:inline-block;position:relative;color:var(--tooltip-content)}:host([appearance=neutral]){--tooltip-background:var(--color-tooltip-bg-neutral);--tooltip-content:var(--color-tooltip-text-neutral)}:host([appearance=inverted]){--tooltip-background:var(--color-tooltip-bg-inverted);--tooltip-content:var(--color-tooltip-text-inverted)}:host([appearance=primary]){--tooltip-background:var(--color-tooltip-bg-primary);--tooltip-content:var(--color-tooltip-text-primary)}#faceplate-tooltip{font:var(--font-12-16-semibold);background-color:var(--tooltip-background);color:var(--tooltip-content);border-radius:.25rem;box-shadow:var(--boxshadow-tooltip);justify-content:center;align-items:center;padding:.5rem;display:inline-flex;width:max-content;isolation:isolate;z-index:var(--faceplate-tooltip-z-index,1)}article{display:flex;gap:.375rem}#faceplate-tooltip::after{display:block;content:'';width:8px;height:8px;position:absolute;background-color:var(--tooltip-background)}#faceplate-tooltip[position=bottom-end]::after,#faceplate-tooltip[position=bottom-start]::after,#faceplate-tooltip[position=top-end]::after,#faceplate-tooltip[position=top-start]::after{--max-arrow-x-travel-tooltip:calc(var(--tooltip-width, 2rem) - 1rem);--max-arrow-x-travel-target:calc(var(--target-width, 1rem) / 2);--max-arrow-x-distance:max( min(var(--max-arrow-x-travel-target), var(--max-arrow-x-travel-tooltip)), 0.5rem )}#faceplate-tooltip[position=bottom-start]::after,#faceplate-tooltip[position=top-start]::after{inset-inline-start:var(--max-arrow-x-distance)}#faceplate-tooltip[position=bottom-end]::after,#faceplate-tooltip[position=top-end]::after{inset-inline-end:var(--max-arrow-x-distance)}#faceplate-tooltip[position=left-end]::after,#faceplate-tooltip[position=left-start]::after,#faceplate-tooltip[position=right-end]::after,#faceplate-tooltip[position=right-start]::after{--max-arrow-y-travel-tooltip:calc(var(--tooltip-height, 2rem) - 1rem);--max-arrow-y-travel-target:calc(var(--target-height, 2rem) / 2);--max-arrow-y-distance:max( min(var(--max-arrow-y-travel-target), var(--max-arrow-y-travel-tooltip)), 0.5rem )}#faceplate-tooltip[position=left-start]::after,#faceplate-tooltip[position=right-start]::after{top:var(--max-arrow-y-distance)}#faceplate-tooltip[position=left-end]::after,#faceplate-tooltip[position=right-end]::after{bottom:var(--max-arrow-y-distance)}#faceplate-tooltip[position|=bottom]::after{top:0;transform:translateY(-50%) rotate(45deg);box-shadow:-1px -1px 2px rgba(0,0,0,.05)}#faceplate-tooltip[position|=top]::after{bottom:0;transform:translateY(50%) rotate(45deg);box-shadow:1px 1px 2px rgba(0,0,0,.05)}#faceplate-tooltip[position|=right]::after{inset-inline-start:0;transform:translateX(-38%) rotate(45deg);box-shadow:-2px 0 2px rgba(0,0,0,.05)}#faceplate-tooltip[position|=left]::after{inset-inline-end:0;transform:translateX(38%) rotate(45deg);box-shadow:0 -2px 2px rgba(0,0,0,.05)}#faceplate-tooltip[position^=auto]::after{display:none}`,o.P.defaultPopperContentStyles]}get hidden(){return"closed"===this._popperController.currentState.state}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this.cleanupListenersWhileOpened()}updateCustomProperties(){if("faceplate-tooltip"!==this.tagName.toLocaleLowerCase())return;const{clientHeight:t=null,clientWidth:e=null}=this.referenceElement,{clientHeight:o=null,clientWidth:i=null}=this._tooltip;t&&e&&o&&i&&(this.style.setProperty("--target-width",`${Math.round(e)}px`),this.style.setProperty("--target-height",`${Math.round(t)}px`),this.style.setProperty("--tooltip-width",`${Math.round(i)}px`),this.style.setProperty("--tooltip-height",`${Math.round(o)}px`))}show(){this.emitter.dispatch("open"),this.updateCustomProperties(),this._popperController.open().then((()=>{this.hidden||(this.addListenersWhileOpened(),this.emitter.dispatch("opened"))}))}close(){return this.cleanupListenersWhileOpened(),this.emitter.dispatch("close"),this._popperController.close().then((()=>{this.hidden&&this.emitter.dispatch("closed")}))}handleClick(t){this._eventUsedMap.set(t,!0),"click"===this.triggerEvent&&(this.hidden?this.show():this.close())}handleMouseenter(){"hover"===this.triggerEvent&&(this.cleanupTooltips(),this._timeoutID=window.setTimeout((()=>{this.querySelector(":focus, :hover")&&this.show()}),this.mouseEnterDelay))}handleMouseleave(){this.close(),this.cleanupTooltips()}cleanupTooltips(){this._timeoutID&&(window.clearTimeout(this._timeoutID),this._timeoutID=null)}render(){const t=this._popperController.actualPosition||this.position;return e.x` `}};return t._([t.n({type:String})],a.prototype,"position",void 0),t._([t.n({type:Number,attribute:"enter-delay"})],a.prototype,"mouseEnterDelay",void 0),t._([t.n({type:String,attribute:"trigger-event"})],a.prototype,"triggerEvent",void 0),t._([t.n({type:String,reflect:!0})],a.prototype,"appearance",void 0),t._([t.av({slot:"trigger",flatten:!0})],a.prototype,"triggers",void 0),t._([t.av({slot:"icon",flatten:!0})],a.prototype,"icons",void 0),t._([t.Q("#faceplate-tooltip")],a.prototype,"_tooltip",void 0),a=t._([t.e("faceplate-tooltip")],a),{get FaceplateTooltip(){return a}}})); SML.dm("Bv2UEnJP_M",[],(async()=>{var e,a,r;return function(e){e.GoldPurchasePaymentForm="award-gold-purchase-payment-form",e.GoldTopupPaymentForm="award-gold-topup-payment-form"}(e||(e={})),function(e){e.SelectionSheet="selection-sheet",e.Leaderboard="leaderboard",e.GoldPurchase="gold-purchase",e.GoldTopUp="gold-top-up"}(a||(a={})),Object.values(a),function(e){e.Limited="award:limited",e.Free="award:free",e.Community="award:community",e.Highlighted="award:highlighted",e.Iconic="award:iconic",e.Branded="award:branded"}(r||(r={})),{get A(){return r},get a(){return a}}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("BxXMRtW0Ao",["CsxDAjmHZE"],(async a=>{const{svg:l}=a.g();return{n:a.m(l``,"0 0 20 20","nsfw")}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("By3M4InPRM",["CsxDAjmHZE"],(async t=>{const{svg:e}=t.g(),i=t.m(e``,"0 0 20 20","volume-off-fill"),s={LoadFail:0,BadSignature:1,BadTimestamp:2,BadSettingValue:3,BadFormat:4,UnknownSetting:5};class r extends Error{code;line;constructor(t){super(t.reason),this.code=t.code,this.line=t.line}}const n=/\r?\n|\r/gm;class a{writable;readable;constructor(t){const e=new o(t);this.writable=new WritableStream({write(t){e.transform(t)},close(){e.close()}}),this.readable=new ReadableStream({start(t){e.onLine=e=>t.enqueue(e),e.onClose=()=>t.close()}})}}class o{x="";y;onLine;onClose;constructor(t){this.y=new TextDecoder(t)}transform(t){this.x+=this.y.decode(t,{stream:!0});const e=this.x.split(n);this.x=e.pop()||"";for(let t=0;t=0&&e<=100?e:null}function b(t){if(!t.includes(","))return null;const[e,i]=t.split(",").map(m);return null!==e&&null!==i?[e,i]:null}function y(t){const e=parseFloat(t);return Number.isNaN(e)?null:e}const w=/[:=]/,v=/^[\s\t]*(region|vertical|line|position|size|align)[:=]/,k=/^REGION:?[\s\t]+/,x=/[\s\t]+/,T=/[\s\t]*-->[\s\t]+/,A=/start|center|end|left|right/,j=/start|center|end/,M=/line-(?:left|right)|center|auto/,S=/^(?:(\d{1,2}):)?(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;var E=(t=>(t[t.None=0]="None",t[t.Header=1]="Header",t[t.Cue=2]="Cue",t[t.Region=3]="Region",t[t.Note=4]="Note",t))(E||{});class O{f;c=0;g={};h={};j=[];a=null;b=null;k=[];d;l="";async init(t){this.f=t,t.strict&&(this.c=1),t.errors&&(this.d=(await SML.di("./ChVzN5arel.js",import.meta.url,"ChVzN5arel").then((function(t){return t.e}))).ParseErrorBuilder)}parse(t,e){if(""===t)this.a?(this.j.push(this.a),this.f.onCue?.(this.a),this.a=null):this.b?(this.h[this.b.id]=this.b,this.f.onRegion?.(this.b),this.b=null):1===this.c&&(this.i(t,e),this.f.onHeaderMetadata?.(this.g)),this.c=0;else if(this.c)switch(this.c){case 1:this.i(t,e);break;case 2:if(this.a){const i=this.a.text.length>0;!i&&v.test(t)?this.m(t.split(x),e):this.a.text+=(i?"\n":"")+t}break;case 3:this.n(t.split(x),e)}else if(t.startsWith("NOTE"))this.c=4;else if(t.startsWith("REGION"))this.c=3,this.b=new f,this.n(t.replace(k,"").split(x),e);else if(t.includes("--\x3e")){const i=this.o(t,e);i&&(this.a=new d(i[0],i[1],""),this.a.id=this.l,this.m(i[2],e)),this.c=2}else 1===e&&this.i(t,e);this.l=t}done(){return{metadata:this.g,cues:this.j,regions:Object.values(this.h),errors:this.k}}i(t,e){if(e>1){if(w.test(t)){const[e,i]=t.split(w);e&&(this.g[e]=(i||"").replace(x,""))}}else t.startsWith("WEBVTT")?this.c=1:this.e(this.d?.p())}o(t,e){const[i,s=""]=t.split(T),[r,...n]=s.split(x),a=L(i),o=L(r);if(null!==a&&null!==o&&o>a)return[a,o,n];null===a&&this.e(this.d?.q(i,e)),null===o&&this.e(this.d?.r(r,e)),null!=a&&null!==o&&o>a&&this.e(this.d?.s(a,o,e))}n(t,e){let i;for(let s=0;s59||r>59?null:3600*i+60*s+r+n/1e3}var C=Object.freeze({__proto__:null,VTTBlock:E,VTTParser:O,default:function(){return new O},parseVTTTimestamp:L});const N=/[0-9]/,$=/[\s\t]+/,P={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span",timestamp:"span"},z={"&":"&","<":"<",">":">",""":'"',"'":"'"," ":"ย ","‎":"โ€Ž","‏":"โ€"},I=/&(?:amp|lt|gt|quot|#(0+)?39|nbsp|lrm|rlm);/g,F=new Set(["white","lime","cyan","red","yellow","magenta","blue","black"]),V=new Set(Object.keys(P));function R(t){let e,i="",s=1,r=[],n=[];for(let r=0;r":a(),s=1;break;default:!i&&N.test(c)&&(s=6),i+=c}break;case 3:switch(c){case"\t":case" ":case"\n":o(),e&&e.class?.trim(),s=4;break;case".":o();break;case">":o(),e&&e.class?.trim(),s=1;break;default:i+=c}break;case 4:">"===c?(i=i.replace($," "),"v"===e?.type?e.voice=B(i):"lang"===e?.type&&(e.lang=B(i)),i="",s=1):i+=c;break;case 5:">"===c&&(i="",e=n.pop(),s=1);break;case 6:if(">"===c){const r=L(i);null!==r&&r>=t.startTime&&r<=t.endTime&&(i="timestamp",a(),e.time=r),i="",s=1}else i+=c}}function a(){if(V.has(i)){const s=e;e={tagName:P[t=i],type:t,children:[]},s?(n[n.length-1]!==s&&n.push(s),s.children.push(e)):r.push(e)}var t;i="",s=1}function o(){if(e&&i){const t=i.replace("bg_","");F.has(t)?e[i.startsWith("bg_")?"bgColor":"color"]=t:e.class=e.class?e.class+" "+i:i}i=""}function l(){if(!i)return;const t={type:"text",data:B(i)};e?e.children.push(t):r.push(t),i=""}return 1===s&&l(),r}function B(t){return t.replace(I,(t=>z[t]||"'"))}function _(t,e,i){t.style.setProperty(`--${e}`,i+"")}function H(t,e,i=!0){t.setAttribute(`data-${e}`,!0===i?"":i+"")}function D(t,e){t.setAttribute("data-part",e)}function q(t,e=0){return W(R(t),e)}function W(t,e=0){let i,s="";for(const r of t)if("text"===r.type)s+=r.data;else{const t="timestamp"===r.type;i={},i.class=r.class,i.title="v"===r.type&&r.voice,i.lang="lang"===r.type&&r.lang,i["data-part"]="v"===r.type&&"voice",t&&(i["data-part"]="timed",i["data-time"]=r.time,i["data-future"]=r.time>e,i["data-past"]=r.timet[1])).map((t=>`${t[0]}="${!0===t[1]?"":t[1]}"`)).join(" ");s+=`<${r.tagName}${n?" "+n:""}>${W(r.children)}`}return s}function Y(t,e){if(!u)for(const i of t.querySelectorAll('[data-part="timed"]')){const t=Number(i.getAttribute("data-time"));Number.isNaN(t)||(t>e?H(i,"future"):i.removeAttribute("data-future"),t=s.left&&i.top<=s.bottom&&i.bottom>=s.top)return e[r];var i,s;return null}function J(t,e){return e.top>=0&&e.bottom<=t.height&&e.left>=0&&e.right<=t.width}function K(t,e,i){switch(i){case"+x":return e.left<0;case"-x":return e.right>t.width;case"+y":return e.top<0;case"-y":return e.bottom>t.height}}function Z(t,e){return Math.max(0,Math.min(t.width,e.right)-Math.max(0,e.left))*Math.max(0,Math.min(t.height,e.bottom)-Math.max(0,e.top))/(t.height*t.width)}function tt(t,e){return{top:e.top/t.height,left:e.left/t.width,right:(t.width-e.right)/t.width,bottom:(t.height-e.bottom)/t.height}}function et(t,e){return e.top=e.top*t.height,e.left=e.left*t.width,e.right=t.width-e.right*t.width,e.bottom=t.height-e.bottom*t.height,e}const it=["top","left","right","bottom"];function st(t,e,i,s){const r=tt(e,i);for(const e of it)_(t,`${s}-${e}`,100*r[e]+"%")}function rt(t,e,i,s){let r,n=1,a={...e};for(let o=0;ol&&(r={...e},n=l),e={...a}}return r||a}const nt=Symbol(0);function at(t,e,i,s){let r,n=i.firstElementChild,a=function(t){if("auto"===t.line)return t.snapToLines?-1:100;return t.line}(e),o=[];if(i[X]||(i[X]=function(t,e){const i=G(e),s=function(t){const e={};for(const i of it)e[i]=parseFloat(t.style.getPropertyValue(`--cue-${i}`));return e}(e);e[nt]=!1,s.top&&(i.top=s.top,i.bottom=s.top+i.height,e[nt]="top");if(s.bottom){const r=t.height-s.bottom;i.top=r-i.height,i.bottom=r,e[nt]="bottom"}s.left&&(i.left=s.left);s.right&&(i.right=t.width-s.right);return tt(t,i)}(t,i)),r=et(t,{...i[X]}),i[nt])o=["top"===i[nt]?"+y":"-y","+x","-x"];else if(e.snapToLines){let i;switch(e.vertical){case"":o=["+y","-y"],i="height";break;case"rl":o=["+x","-x"],i="width";break;case"lr":o=["-x","+x"],i="width"}let s=parseFloat(getComputedStyle(n).lineHeight)||0,l=s*Math.round(a),c=t[i]+s,h=o[0];Math.abs(l)>c&&(l=l<0?-1:1,l*=Math.ceil(c/s)*s),a<0&&(l+=""===e.vertical?t.height:t.width,o=o.reverse()),U(r,h,l)}else{const i=""===e.vertical,s=i?"+y":"+x",n=i?r.height:r.width;U(r,s,(i?t.height:t.width)*a/100),U(r,s,"center"===e.lineAlign?n/2:"end"===e.lineAlign?n:0),o=i?["-y","+y","-x","+x"]:["-x","+x","-y","+y"]}return r=rt(t,r,s,o),st(i,t,r,"cue"),r}const ot=["-y","+y","-x","+x"];function lt(t,e,i,s){let r=Array.from(i.querySelectorAll('[data-part="cue-display"]')),n=0,a=Math.max(0,r.length-e.lines);for(let t=r.length-1;t>=a;t--)n+=r[t].offsetHeight;_(i,"region-height",n+"px"),i[X]||(i[X]=tt(t,G(i)));let o={...i[X]};return o=et(t,o),o.width=i.clientWidth,o.height=n,o.right=o.left+o.width,o.bottom=o.top+n,o=rt(t,o,s,ot),st(i,t,o,"region"),o}var ct=Object.freeze({__proto__:null,CaptionsRenderer:class{overlay;z;A=0;C="ltr";B=[];D=!1;E;h=new Map;j=new Map;get dir(){return this.C}set dir(t){this.C=t,H(this.overlay,"dir",t)}get currentTime(){return this.A}set currentTime(t){this.A=t,this.update()}constructor(t,e){this.overlay=t,this.dir=e?.dir??"ltr",t.setAttribute("translate","yes"),t.setAttribute("aria-live","off"),t.setAttribute("aria-atomic","true"),D(t,"captions"),this.G(),this.E=new ResizeObserver(this.I.bind(this)),this.E.observe(t)}changeTrack({regions:t,cues:e}){this.reset(),this.J(t);for(const t of e)this.j.set(t,null);this.update()}addCue(t){this.j.set(t,null),this.update()}removeCue(t){this.j.delete(t),this.update()}update(t=!1){this.H(t)}reset(){this.j.clear(),this.h.clear(),this.B=[],this.overlay.textContent=""}destroy(){this.reset(),this.E.disconnect()}I(){this.D=!0,this.K()}K=function(t,e){let i,s=null;function r(){n(),t(...i),i=void 0}function n(){clearTimeout(s),s=null}return function(){i=[].slice.call(arguments),n(),s=setTimeout(r,e)}}((()=>{this.D=!1,this.G();for(const t of this.h.values())t[X]=null;for(const t of this.j.values())t&&(t[X]=null);this.H(!0)}),50);G(){this.z=G(this.overlay),_(this.overlay,"overlay-width",this.z.width+"px"),_(this.overlay,"overlay-height",this.z.height+"px")}H(t=!1){if(!this.j.size||this.D)return;let e,i=[...this.j.keys()].filter((t=>this.A>=t.startTime&&this.A<=t.endTime)).sort(((t,e)=>t.startTime!==e.startTime?t.startTime-e.startTime:t.endTime-e.endTime)),s=i.map((t=>t.region));for(let r=0;rH(n,"active"))),t=!0),r.isConnected||((n||this.overlay).append(r),t=!0)}if(t){const t=[],s=new Set;for(let r=i.length-1;r>=0;r--){if(e=i[r],s.has(e.region||e))continue;const n=this.F(e),a=n?this.h.get(e.region.id):this.j.get(e);n?t.push(lt(this.z,e.region,a,t)):t.push(at(this.z,e,a,t)),s.add(n?e.region:e)}}Y(this.overlay,this.A),this.B=i}J(t){if(t)for(const e of t){const t=this.M(e);this.h.set(e.id,t),this.overlay.append(t)}}M(t){const e=document.createElement("div");return D(e,"region"),H(e,"id",t.id),H(e,"scroll",t.scroll),_(e,"region-width",t.width+"%"),_(e,"region-anchor-x",t.regionAnchorX),_(e,"region-anchor-y",t.regionAnchorY),_(e,"region-viewport-anchor-x",t.viewportAnchorX),_(e,"region-viewport-anchor-y",t.viewportAnchorY),_(e,"region-lines",t.lines),e}L(t){const e=document.createElement("div"),i=function(t){if("auto"===t.position)switch(t.align){case"start":case"left":return 0;case"right":case"end":return 100;default:return 50}return t.position}(t),s=function(t,e){if("auto"===t.positionAlign)switch(t.align){case"start":return"ltr"===e?"line-left":"line-right";case"end":return"ltr"===e?"line-right":"line-left";case"center":return"center";default:return`line-${t.align}`}return t.positionAlign}(t,this.C);if(D(e,"cue-display"),""!==t.vertical&&H(e,"vertical"),_(e,"cue-text-align",t.align),t.style)for(const i of Object.keys(t.style))e.style.setProperty(i,t.style[i]);if(this.F(t))_(e,"cue-offset",i-("line-right"===s?100:"center"===s?50:0)+"%");else if(_(e,"cue-writing-mode",""===t.vertical?"horizontal-tb":"lr"===t.vertical?"vertical-lr":"vertical-rl"),!t.style?.["--cue-width"]){let r=i;"line-left"===s?r=100-i:"center"===s&&i<=50?r=2*i:"center"===s&&i>50&&(r=2*(100-i));const n=t.size=4&&(l=d>=7?"top":"center"),d%3){case 1:o="start";break;case 2:o="center";break;case 3:o="end"}}}if(a.S=l,a["--cue-white-space"]="normal",a["--cue-line-height"]="normal",a["--cue-text-align"]=o,"center"===l?(a["--cue-top"]="50%",u.push("translateY(-50%)")):a[`--cue-${l}`]=(i||0)+"px",1===h&&(a["--cue-padding-y"]="0"),(1===h||r)&&(a["--cue-bg-color"]=1===h?"none":r),3===h&&s&&(a["--cue-outline"]=`${e}px solid ${s}`),1===h&&"number"==typeof e){const t=r??"#000";a["--cue-text-shadow"]=[s&&vt(1.2*e,1.2*c,s),s?vt(e*(e/2),c*(e/2),t):vt(e,c,t)].filter(Boolean).join(", ")}u.length&&(a["--cue-transform"]=u.join(" ")),this.Q[n]=a}U(t,e){const i=this.V(t),s=this.o(i.Start,i.End,e);if(!s)return;const r=new d(s[0],s[1],""),n={...this.Q[i.Style]||{}},a=i.Name?``:"",o=n.S,l=i.MarginL&&parseFloat(i.MarginL),c=i.MarginR&&parseFloat(i.MarginR),h=i.MarginV&&parseFloat(i.MarginV);return l&&(n["--cue-width"]="auto",n["--cue-left"]=l+"px"),c&&(n["--cue-width"]="auto",n["--cue-right"]=c+"px"),h&&"center"!==o&&(n[`--cue-${o}`]=h+"px"),r.text=a+t.slice(this.O.length-1).join(", ").replace(ft,"").replace(gt,"\n"),delete n.S,Object.keys(n).length&&(r.style=n),r}V(t){const e={};for(let i=0;is)return[s,r];null===s&&this.e(this.d?.q(t,i)),null===r&&this.e(this.d?.r(e,i)),null!=s&&null!==r&&r>s&&this.e(this.d?.s(s,r,i))}e(t){if(t){if(this.k.push(t),this.f.strict)throw this.f.cancel(),t;this.f.onError?.(t)}}}function wt(t){const e=parseInt(t.replace("&H",""),16);if(e>=0){return"rgba("+[255&e,e>>8&255,e>>16&255,(e>>24&255^255)/255].join(",")+")"}return null}function vt(t,e,i){const s=Math.ceil(2*Math.PI*t);let r="";for(let n=0;n{const t={[e.a8.FEED]:e.a9.Feed,[e.a8.FULL_BLEED_VIDEO_FEED]:e.a9.FullBleedVideoFeed,[e.a8.COMMENTS_PAGE]:e.a9.CommentsPage,[e.a8.COMMENT_TREES]:e.a9.CommentTrees,[e.a8.SIDEBARS]:e.a9.Sidebars,[e.a8.TRENDING_DISCOVERY]:e.a9.TrendingDiscovery,[e.a8.TRENDING_SEARCH_RESULT]:e.a9.TrendingSearchResult,[e.a8.BLANK_ONLY]:e.a9.BlankOnly,[e.a8.RELATED_POSTS]:e.a9.ListingBelow};return{m:e=>e&&t[e]||null,s:(e,t={})=>{const{includeFeedChecks:a=!1,includeCommentsPageChecks:n=!1}=t;return e.composedPath().some((e=>{const t=e;if("AD-REMINDER-BUTTON"===t.tagName||"AD-EVENT-STATUS"===t.tagName||"SHREDDIT-POST-OVERFLOW-MENU"===t.tagName||"CLICK-LOCATION-TRACKER"===t.tagName||"SHREDDIT-DYNAMIC-AD-LINK"===t.tagName&&"promoted_label"===t.getAttribute?.("click-location")&&t.hasAttribute?.("promoted-label-experiment"))return!0;if(a){if(t.hasAttribute?.("upvote")||t.hasAttribute?.("downvote")||"comments-action-button"===t.getAttribute?.("name")||t.matches?.("button.toggle__expando-button")||t.matches?.("div#unpacked-actions")||t.matches?.("faceplate-dropdown-menu#defaultActions")||"SHREDDIT-POST-SHARE-BUTTON"===t.tagName)return!0}if(n){if("SHREDDIT-SLIDER-ELEMENT"===t.tagName||"VIDEO"===t.tagName||t.matches?.("img.thumbnail-image-video-toggle")||t.matches?.("button.toggleable-video-player-close-btn")||t.matches?.("button.thumbnail-playback-action-circle"))return!0}return!1}))}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("C2YcjZKws8",["C42E8rVVpA","DUzIBJc2in","CsxDAjmHZE"],(async(t,e,o)=>{let l=class extends o.s{constructor(){super(...arguments),this.clickLocation=t.w.UNKNOWN,this.enableAdPostHydration=!1,this.storageController=null}async connectedCallback(){await super.connectedCallback(),await this.resolveAdStorageControllerDependencies()}async resolveAdStorageControllerDependencies(){if(!this.enableAdPostHydration)return;const{AdStorageController:t}=await SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in").then((function(t){return t.d8}));this.storageController=new t(this)}async disconnectedCallback(){await super.disconnectedCallback()}handleClick(t){this.storageController&&this.enableAdPostHydration&&this.storageController.storeAdDataInStorage();"auxclick"===t.type&&1!==t.button||e.t({el:this,clickLocation:this.clickLocation})}render(){return o.x``}};l.styles=[t.t],t._([t.n({type:String,attribute:"click-location"})],l.prototype,"clickLocation",void 0),t._([t.n({type:Boolean,attribute:"enable-ad-post-hydration"})],l.prototype,"enableAdPostHydration",void 0),l=t._([t.e("click-location-tracker")],l)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("C9S3A50Ur_",["C42E8rVVpA","CsxDAjmHZE"],(async(e,t)=>{var i=t.i`${e.Y}a,button{background:0 0;border-radius:inherit;color:inherit;border:none;padding:0;margin:inherit;font:inherit;cursor:pointer;outline:inherit;display:inherit;width:inherit;height:inherit;text-decoration:none}a:focus-visible,button:focus-visible{outline:2px solid var(--color-global-focus)}`;class r extends e.R{constructor(){super(...arguments),this.disabled=!1,this.selected=!1}renderLeadingContent(){return t.x` `}renderTrailingContent(){return t.x` `}handleDisabledLinkClick(e){this.disabled&&(e.preventDefault(),e.stopPropagation())}render(){const e=t.x`${this.renderLeadingContent()} ${this.renderTrailingContent()}`;return this.href?t.x`${e}`:t.x``}}r.styles=i,e._([e.n({type:Boolean})],r.prototype,"disabled",void 0),e._([e.n({type:Boolean,reflect:!0})],r.prototype,"selected",void 0),e._([e.n({type:String})],r.prototype,"href",void 0);var n=t.i`${e.Y}:host{display:inline-flex;border:1px solid transparent;cursor:pointer}.container{display:inherit;align-items:center}slot:not([name]){display:inline-flex;line-height:var(--rem16);font-size:var(--rem12)}`;class s extends r{}return s.styles=[r.styles,n],{R:s}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("CABnEiuNLc",["C42E8rVVpA","DUzIBJc2in","CsxDAjmHZE"],(async(e,i,t)=>{var s;!function(e){e.Discover="discover",e.ListingBelowCommunityRecommendations="listing_below_community_recommendations",e.RecommendationChaining="recommendation_chaining"}(s||(s={}));const n={[s.RecommendationChaining]:{handleJoin:function({isSubscribed:e,subredditId:i}){return{source:"feed_chain_unit",action:e?"unsubscribe":"subscribe",noun:"subreddit",action_info:{...i&&{subreddit_id:i}}}}},[s.ListingBelowCommunityRecommendations]:{handleJoin:function({isSubscribed:e,subredditId:i}){return{source:"feed_experience",action:e?"unsubscribe":"subscribe",noun:"subreddit",action_info:{...i&&{subreddit_id:i}}}},handleView:i.f},[s.Discover]:{handleJoin:function({isSubscribed:e}){return{source:"discover",action:e?"unsubscribe":"subscribe",noun:"subreddit_card"}},handleConsume:i.h,handleView:i.f}};let d=class extends t.s{constructor(){super(),this.useCase=s.Discover,this.subredditId="",this._subscribed=!1,this.handleView=()=>{this.trackers.handleView&&e.f(this,this.trackers.handleView({subredditId:this.subredditId}))},this.handleConsume=()=>{this.trackers.handleConsume&&e.f(this,this.trackers.handleConsume({subredditId:this.subredditId}))},this.handleCommunityJoin=()=>{e.f(this,this.trackers.handleJoin({isSubscribed:this._subscribed,subredditId:this.subredditId})),this._subscribed=!this._subscribed},new i.V(this,{consumeThreshold:2e3,onView:this.handleView,onConsume:this.handleConsume})}connectedCallback(){super.connectedCallback(),this.joinButton?.addEventListener("click",this.handleCommunityJoin)}disconnectedCallback(){super.disconnectedCallback(),this.joinButton?.removeEventListener("click",this.handleCommunityJoin)}get joinButton(){return this.querySelector("shreddit-join-button")}get trackers(){return n[this.useCase]}createRenderRoot(){return this}};d.styles=[e.t],e._([e.n({type:String,attribute:"use-case"})],d.prototype,"useCase",void 0),e._([e.n({type:String,attribute:"subreddit-id"})],d.prototype,"subredditId",void 0),d=e._([e.e("community-card")],d)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("CEuDX0j-qf",["C42E8rVVpA"],(async t=>{var p;function e(p){const e={q:p.query};return p.pane&&(e.type=p.pane),p.source&&(e.source=p.source),p.sort&&(e.sort=p.sort),p.time&&(e.t=p.time),p.referrer&&(e.referrer=p.referrer),p.cursor[t.da.All]&&(e.cursor=p.cursor[t.da.All]),p.cursor[t.da.Posts]&&(e.postsCursor=p.cursor[t.da.Posts]),p.cursor[t.da.Comments]&&(e.commentsCursor=p.cursor[t.da.Comments]),p.cursor[t.da.Subreddits]&&(e.communitiesCursor=p.cursor[t.da.Subreddits]),p.cursor[t.da.Users]&&(e.peopleCursor=p.cursor[t.da.Users]),p.ad&&(e.ad=p.ad),p.conversationId&&(e.cId=p.conversationId),p.impressionId&&(e.iId=p.impressionId),p.flair&&(e.flair=encodeURIComponent(p.flair)),p.disableSpellCorrection&&(e.disableSpellCorrection=p.disableSpellCorrection),p.disableLocation&&(e.disableLocation=p.disableLocation),e}!function(t){t.Ad="ad",t.AllCursor="cursor",t.CommentsCursor="commentsCursor",t.CommunitiesCursor="communitiesCursor",t.ConversationId="cId",t.ImpressionId="iId",t.Pane="type",t.PeopleCursor="peopleCursor",t.PostsCursor="postsCursor",t.Query="q",t.Referrer="referrer",t.Sort="sort",t.Source="source",t.Time="t",t.Flair="flair",t.DisableSpellCorrection="disableSpellCorrection",t.DisableLocation="disableLocation"}(p||(p={}));var a;!function(t){t.SearchBarPill="search_bar_scope_pill",t.SerpScopeSwitcher="serp_scope_switcher"}(a||(a={}));const h=/^\//,y=/\/$/,r=(t="")=>t.replace(h,"").replace(y,""),s=/^\/user\/([\w+-]+)\/m\//,i=/\/$/,d=(t="")=>t.replace(s,"").replace(i,""),$=/^\/u(?:ser)?\//,o=/\/$/,n=(t="")=>t.replace($,"u/").replace(o,""),u=({type:p,path:e})=>({[t.a2.GLOBAL]:t=>t,[t.a2.COMMUNITY]:r,[t.a2.CUSTOM_FEED]:d,[t.a2.PROFILE]:n}[p](e));return {get S(){return p},a:"search-media-post-unit",b:function(t){const p=new URLSearchParams({...e(t)});return`${(t=>t.endsWith("/")?t:`${t}/`)((t=>t.startsWith("/")?t:`/${t}`)(t.scope.path))}search/?${p.toString()}`},c:(p,e=!1,a,h)=>{if((h||a)&&p?.type===t.a2.GLOBAL)return "Find anything";switch(p?.type){case t.a2.COMMUNITY:case t.a2.CUSTOM_FEED:return e?`${u({type:p?.type,path:p.path})}`:`Search in ${u({type:p?.type,path:p.path})}`;case t.a2.PROFILE:return e?`${u({type:p?.type,path:p.path})}`:`Search in ${u({type:p?.type,path:p.path})}`;default:return "Search Reddit";}},get d(){return a},g:u,s:e};})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("CHpnYscvgU",["C42E8rVVpA"],(async t=>{var n;!function(t){t.MULTILINGUAL_ON="multilingual_on",t.ACCOUNT_AGE="account_age",t.BACKEND="backend",t.DEFAULT_OFF="default_off",t.REGULAR_SEO="regular_seo",t.MT_SEO="mt_seo"}(n||(n={}));const o="on",a="off",e="initiated",s=t=>!1===t.isEligibleForImmersive?e:t.isImmersiveTranslationsActive?o:a;return{get T(){return n},a:n=>{const o=n?{post:{id:n}}:{};return t.b({source:"translate_button",action:"view",noun:"post_composer"},{action_info:{reason:"on"},...o})},b:n=>t.b({source:"translate_button",action:"view",noun:"comment"},{comment:{...n,translation_state:n.translation_state,translation_language:n.translation_language?n.translation_language:"original"},post:{id:n.post_id??""},action_info:{reason:n.translation_language?t.b9:t.ba}}),c:(n,o)=>t.b({source:"translate_button",action:"click",noun:"comment_composer"},{action_info:{reason:n?"on":"off"},...o?{comment:{id:o}}:{}}),d:(n,o)=>{const a=o?{post:{id:o}}:{};return t.b({source:"translate_button",action:"click",noun:"post_composer"},{action_info:{reason:n?"on":"off"},...a})},e:n=>t.b({source:"translate_button",action:"click",noun:"comment_indicator"},{comment:{...n,translation_state:n.translation_state,translation_language:n.translation_language?n.translation_language:"original"},post:{id:n.post_id??""},action_info:{reason:n.translation_state?t.bI.SEE_ORIGINAL:t.bI.SEE_TRANSLATION}}),f:n=>t.b({source:"translate_button",action:"dismiss",noun:"translation_intervention"},{action_info:{reason:s(n)},comment:{...n.comment},post:n.post}),g:n=>t.b({source:"translate_button",action:"click",noun:"translation_intervention"},{action_info:{reason:s(n),type:n.actionType},comment:{...n.comment},post:n.post}),h:()=>t.b({source:"translate_button",action:"hide",noun:"comment_composer"}),i:()=>t.b({source:"translate_button",action:"hide",noun:"post_composer"}),j:n=>t.b({source:"translate_button",action:"dismiss",noun:"post_banner"},{action_info:{reason:s(n)},post:{...n.post,translation_state:n.isPostTranslated}}),k:(n,o)=>t.b({source:"translate_button",action:"submit",noun:"post_composer"},{action_info:{reason:n?"on":"off"},...o?{post:{id:o.id,subreddit_id:o.subredditId,subreddit_name:o.subredditPrefixedName,url:o.permalink}}:{}}),l:n=>t.b({source:"overflow_menu",action:"click",noun:"translate_survey"},{post:n?.post,comment:n?.comment}),m:n=>t.b({source:"translate_button",action:"view",noun:"survey"},{post:n?.post,comment:n?.comment}),n:n=>t.b({source:"translate_button",action:"dismiss",noun:"survey"},{post:n?.post,comment:n?.comment}),o:n=>t.b({source:"translate_button",action:"submit",noun:"survey"},{action_info:{reason:n.reason},post:n.post,comment:n.comment,survey:{text:n.survey_text}}),p:({comment:n,post:o})=>t.b({source:"translate_button",action:"view",noun:"feedback"},{post:o,comment:n}),q:(n,o,a)=>t.b({source:"translate_button",action:"click",noun:"toggle"},{action_info:{reason:n?"off":"on"},translation_metrics:{translation_setting_state:n?"off":"on",target_language:o},post:a}),r:({comment:n,post:o})=>t.b({source:"translate_button",action:"click",noun:"feedback"},{post:o,comment:n}),s:(n,o)=>t.b({source:"translate_button",action:"click",noun:"show_post_banner"},{action_info:{reason:n?"on":"off"},post:o}),t:n=>t.b({source:"translate_button",action:"view",noun:"comment_composer"},{action_info:{reason:"on"},...n?{comment:{id:n}}:{}}),u:n=>t.b({source:"translate_button",action:"default",noun:"known_lang"},{action_info:{reason:n.reason,type:n.error,source_name:n.sourceName},setting:{value:n.languages.toString(),values:n.languages,old_value:n.old_languages.toString()}}),v:n=>t.b({source:"translate_button",action:"enabled",noun:"status"},{action_info:{reason:n}}),w:n=>t.b({source:"translate_button",action:"disabled",noun:"status"},{action_info:{reason:n}}),x:n=>t.b({source:"overflow_menu",action:"view",noun:"translate_post"},{action_info:{reason:s(n)},post:{...n.post,translation_state:n.isPostTranslated}}),y:(n,o,a)=>t.b({source:"translate_button",action:"submit",noun:"comment_composer"},{action_info:{reason:n?"on":"off"},...o?{post:{id:o.id,language:o.postLanguage,subreddit_id:o.subredditId,subreddit_name:o.subredditPrefixedName,type:o.postType,url:o.permalink}}:{},...a?{comment:{id:a}}:{}}),z:n=>t.b({source:"overflow_menu",action:"view",noun:"translate_comment"},{action_info:{reason:s(n)},comment:{...n.comment,translation_state:n.isCommentTranslated},post:n.post})}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("CMwQRCekeQ",["CsxDAjmHZE","C42E8rVVpA"],(async(l,a)=>{const{svg:o}=l.g(),e=l.m(o``,"0 0 20 20","collapse-left"),s=()=>document.getElementById(a.gs);return{a:async({leadGenInfo:l})=>{l&&!s()&&await a.j({name:a.gr})},c:e,s:({leadGenInfo:l,postId:a,impressionId:o,onSuccess:e})=>{l&&s()?.showModal({...l,postId:a,impressionId:o,onSuccess:e,prompt:l.prompt??"",privacyPolicyUrl:l.privacyPolicyUrl??"",leadFormFields:l.leadFormFields??[],formId:l.formId??null,publicEncryptionKey:l.publicEncryptionKey??null})}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("CPd-IV5dE-",["C42E8rVVpA"],(async t=>{class e{constructor(t){this.shouldOverrideId=!1,this.activeIds={},this.update=t=>this.set(t),this.reset=()=>this.clear(),this.getKey=t}get(...t){const e=this.getKey(...t);return this.activeIds[e]?this.activeIds[e]:this.generate(e)}set(t,e){return e?(this.activeIds[t]=e,this.activeIds[t]):this.generate(t)}clear(t){t?delete this.activeIds[t]:this.activeIds={}}getUUID(){return this.shouldOverrideId?"id":t.a3()}generate(t){return this.activeIds[t]=this.getUUID(),this.activeIds[t]}}const s=t=>t,i=new e(((e,s)=>`${s}-${function(e){let s=`[q:${e.query}]`;return e.scope.type!==t.a2.GLOBAL&&(s=`${s}--[scope:${e.scope.type}-${e.scope.path}]`),e.sort&&(s=`${s}--[sort:${e.sort}]`),e.time&&(s=`${s}--[time:${e.time}]`),e.pane&&(s=`${s}--[pane:${e.pane}]`),s}(e)}`));return{S:new e(s),a:new e(s),b:i}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("CU5rE0Nzqh",["C42E8rVVpA","CsxDAjmHZE"],(async(e,s)=>{var r;!function(e){e.Search="search",e.PostDetail="post_detail"}(r||(r={}));class t{constructor(s,t,i=r.Search){this.checkAndSendImpressionEvent=s=>{if(!s.search?.impression_id)return;const{search:r,action_info:t}=s,i=JSON.parse(sessionStorage.getItem("search_impression_cache")||"[]"),o=new Set([...i]);if(o.has(r.impression_id)||!this.searchTelemetrySource)return;o.add(r.impression_id),sessionStorage.setItem("search_impression_cache",JSON.stringify([...o]));const c=e.b({source:this.source,action:"create",noun:"impression_id"},{...s,search:{...r,impression_id:r.impression_id},action_info:{...t,type:this.searchTelemetrySource}});e.f(this.host,c)},(this.host=s).addController(this),this._v2Events=new e.gA(this.host,(e=>{this.checkAndSendImpressionEvent(e)})),this.source=i,this.searchTelemetrySource=t}hostConnected(){}}let i=class extends s.s{constructor(){super(...arguments),this.isPdpSeekerM2=!1,this._searchDynamicIdCacheController=new t(this,this.searchTelemetrySource,this.source)}get source(){return this.isPdpSeekerM2?r.PostDetail:r.Search}willUpdate(e){e.has("searchTelemetrySource")&&(this._searchDynamicIdCacheController.searchTelemetrySource=this.searchTelemetrySource),e.has("isPdpSeekerM2")&&(this._searchDynamicIdCacheController.source=this.source)}createRenderRoot(){return this}};return e._([e.n({attribute:"search-telemetry-source",type:String})],i.prototype,"searchTelemetrySource",void 0),e._([e.n({attribute:"is-pdp-seeker-m2",type:Boolean})],i.prototype,"isPdpSeekerM2",void 0),i=e._([e.e("search-dynamic-id-cache-controller")],i),{S:t}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("CUdNoUn2BN",["CsxDAjmHZE"],(async c=>{const{svg:l}=c.g();return{c:c.m(l``,"0 0 20 20","clock")}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./BYUKEbOT4E.js",import.meta.url,"BYUKEbOT4E");SML.di("./BZFHJN-Awe.js",import.meta.url,"BZFHJN-Awe");SML.di("./RDJ1iNIxln.js",import.meta.url,"RDJ1iNIxln");SML.di("./C2YcjZKws8.js",import.meta.url,"C2YcjZKws8");SML.di("./DMFEgBklTz.js",import.meta.url,"DMFEgBklTz");SML.di("./PJJ5-f-jpV.js",import.meta.url,"PJJ5-f-jpV");SML.di("./CvOrQNTrjb.js",import.meta.url,"CvOrQNTrjb");SML.di("./CMwQRCekeQ.js",import.meta.url,"CMwQRCekeQ");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./BeSXmWRKRU.js",import.meta.url,"BeSXmWRKRU");SML.di("./hidyRU_yeg.js",import.meta.url,"hidyRU_yeg");SML.di("./BVeqrhRSRj.js",import.meta.url,"BVeqrhRSRj");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q");SML.di("./Cj45kFzx5i.js",import.meta.url,"Cj45kFzx5i");SML.di("./C-mIupZfvy.js",import.meta.url,"C-mIupZfvy");SML.di("./Dx9vhrNXWR.js",import.meta.url,"Dx9vhrNXWR");SML.di("./7ymiBBk8xO.js",import.meta.url,"7ymiBBk8xO");SML.di("./CZFRGXDPUQ.js",import.meta.url,"CZFRGXDPUQ");SML.di("./Ceb0ABsHlF.js",import.meta.url,"Ceb0ABsHlF");SML.di("./BUnsiaD7oQ.js",import.meta.url,"BUnsiaD7oQ");SML.di("./UD2pUVjMzE.js",import.meta.url,"UD2pUVjMzE");SML.di("./B-LgD4K8b5.js",import.meta.url,"B-LgD4K8b5");SML.di("./B7xOUSlR-V.js",import.meta.url,"B7xOUSlR-V");SML.di("./By3M4InPRM.js",import.meta.url,"By3M4InPRM");SML.di("./ChVzN5arel.js",import.meta.url,"ChVzN5arel");SML.di("./hqZhqS6qH4.js",import.meta.url,"hqZhqS6qH4");SML.di("./CXhXPoA40F.js",import.meta.url,"CXhXPoA40F");SML.di("./C-4AJ2Y78L.js",import.meta.url,"C-4AJ2Y78L");SML.di("./wDRHyxVKtb.js",import.meta.url,"wDRHyxVKtb");SML.di("./cjhvxMuwOm.js",import.meta.url,"cjhvxMuwOm");SML.di("./5YOkNVVwii.js",import.meta.url,"5YOkNVVwii");SML.di("./CZU1X6W5t6.js",import.meta.url,"CZU1X6W5t6");SML.di("./DCTgJU864D.js",import.meta.url,"DCTgJU864D");SML.di("./PaIPteKyLX.js",import.meta.url,"PaIPteKyLX");SML.di("./0Z5i5741wq.js",import.meta.url,"0Z5i5741wq");SML.di("./BkjgI35gdl.js",import.meta.url,"BkjgI35gdl");SML.di("./D5IdwQBwqd.js",import.meta.url,"D5IdwQBwqd");SML.di("./CuC-xwr_mY.js",import.meta.url,"CuC-xwr_mY");SML.di("./CbrVzpDtc2.js",import.meta.url,"CbrVzpDtc2");SML.di("./Hw1PFKH8z9.js",import.meta.url,"Hw1PFKH8z9");SML.di("./Da-UYDWSOS.js",import.meta.url,"Da-UYDWSOS");SML.di("./BVwlQhSoPB.js",import.meta.url,"BVwlQhSoPB");SML.di("./sXKB1kTPf8.js",import.meta.url,"sXKB1kTPf8");SML.di("./HWzb-DWZS3.js",import.meta.url,"HWzb-DWZS3");SML.di("./DIb1irMc8d.js",import.meta.url,"DIb1irMc8d");SML.di("./CrfIEMT3YQ.js",import.meta.url,"CrfIEMT3YQ");SML.di("./eO3FsZKN3d.js",import.meta.url,"eO3FsZKN3d");SML.di("./Bv2UEnJP_M.js",import.meta.url,"Bv2UEnJP_M");SML.di("./BaFXWsm32y.js",import.meta.url,"BaFXWsm32y");SML.di("./clzw02fdiy.js",import.meta.url,"clzw02fdiy");SML.di("./Cm1OoSEr5r.js",import.meta.url,"Cm1OoSEr5r");SML.di("./DYzo2YMMuI.js",import.meta.url,"DYzo2YMMuI");SML.di("./CHpnYscvgU.js",import.meta.url,"CHpnYscvgU");SML.di("./1i4g9fLWHY.js",import.meta.url,"1i4g9fLWHY");SML.di("./CKuUwv2_dV.js",import.meta.url,"CKuUwv2_dV");SML.di("./BtqmVQuPYp.js",import.meta.url,"BtqmVQuPYp");SML.di("./BIrqd8tOEI.js",import.meta.url,"BIrqd8tOEI");SML.di("./CsrVq94Zej.js",import.meta.url,"CsrVq94Zej");SML.di("./FcQsMjK8eg.js",import.meta.url,"FcQsMjK8eg");SML.di("./K26PgUrfyw.js",import.meta.url,"K26PgUrfyw");SML.di("./BG8P3or1N1.js",import.meta.url,"BG8P3or1N1");SML.di("./tmkhvHLxT3.js",import.meta.url,"tmkhvHLxT3");SML.di("./B-LM1r1oJd.js",import.meta.url,"B-LM1r1oJd");SML.di("./DrM-WGXCsZ.js",import.meta.url,"DrM-WGXCsZ"); SML.dm("CZr9WQkJMA",["C42E8rVVpA","CsxDAjmHZE","BYUKEbOT4E","BZFHJN-Awe","CvOrQNTrjb","CMwQRCekeQ","DUzIBJc2in","BeSXmWRKRU","hidyRU_yeg","BVeqrhRSRj","BFDJQElz9q","Cj45kFzx5i","C-mIupZfvy","RDJ1iNIxln","C2YcjZKws8","DMFEgBklTz","PJJ5-f-jpV","Dx9vhrNXWR","7ymiBBk8xO","CZFRGXDPUQ","Ceb0ABsHlF","BUnsiaD7oQ","UD2pUVjMzE","B-LgD4K8b5","B7xOUSlR-V","By3M4InPRM","ChVzN5arel","hqZhqS6qH4","CXhXPoA40F","C-4AJ2Y78L","wDRHyxVKtb","cjhvxMuwOm","5YOkNVVwii","CZU1X6W5t6","DCTgJU864D","PaIPteKyLX","0Z5i5741wq","BkjgI35gdl","D5IdwQBwqd","CuC-xwr_mY","CbrVzpDtc2","Hw1PFKH8z9","Da-UYDWSOS","BVwlQhSoPB","sXKB1kTPf8","HWzb-DWZS3","DIb1irMc8d","CrfIEMT3YQ","eO3FsZKN3d","Bv2UEnJP_M","BaFXWsm32y","clzw02fdiy","Cm1OoSEr5r","DYzo2YMMuI","CHpnYscvgU","1i4g9fLWHY","CKuUwv2_dV","BtqmVQuPYp","BIrqd8tOEI","CsrVq94Zej","FcQsMjK8eg","K26PgUrfyw","BG8P3or1N1","tmkhvHLxT3","B-LM1r1oJd","DrM-WGXCsZ"],(async(t,e,i,s,a,r,n,o,E,d,l,T,m)=>{const p=[t.w.BACKGROUND,t.w.PROMOTED_LABEL,t.w.CREDIT_BAR_WHITESPACE,t.w.TITLE,t.w.TEXT_BODY,t.w.ACTION_BAR_WHITESPACE];class h{constructor(t){this._currGalleryIndex=0,this.handleGalleryNavEvent=t=>{const{noun:e,action:i,source:s,post:a}=t.detail;a?.id===this.host.postId&&"gallery"===s&&"click"===i&&("forward"===e&&this._currGalleryIndex+1=0&&this._currGalleryIndex--,this.host.querySelectorAll("call-to-action-gallery-links").forEach((t=>t.handleGalleryNavEvent(this._currGalleryIndex))),this.host.querySelectorAll("shreddit-dynamic-ad-link").forEach((t=>{p.includes(t.clickLocation)&&(t.galleryIndex=this._currGalleryIndex)})))},(this.host=t).addController(this)}hostConnected(){this.host.galleryItems?.length&&this.host.addEventListener("faceplate-track",this.handleGalleryNavEvent)}hostDisconnected(){this.host.removeEventListener("faceplate-track",this.handleGalleryNavEvent)}}class D{constructor(t){(this.host=t).addController(this)}hostConnected(){this.host.impressionId||this.host.hasAdEvents||(this.hydrateAdEventsFromStorage(),this.hydrateAdUserTargetingFromStorage(),this.host.hasAdEvents&&(this.updateDynamicLinkUrls(),this.host.setupAdObserver()))}updateDynamicLinkUrls(){this.host.querySelectorAll("shreddit-dynamic-ad-link").forEach((e=>{const i="/"===e.outboundLinkOverride?.charAt(0),s=!!this.host.galleryItems,a=!!this.host.isReminderAd;i||a||!s&&e.outboundLinkOverride===t.f4||(e.outboundLinkOverride=this.host.galleryItems?this.host.galleryItems[e.galleryIndex??0]?.outboundUrl:this.host.outboundLinkUrl)}))}hydrateAdEventsFromStorage(){const e=new URL(t.e4.href).searchParams.get(t.f5);this.host.impressionId=e||"";const i=n.bq(this.host.impressionId);i&&(this.host.adEvents=i.adEvents,this.host.outboundLinkUrl=i.clickRedirectUrl,this.host.galleryItems&&i.galleryAdData&&(this.host.galleryItems=i.galleryAdData?.map(((t,e)=>({...(this.host.galleryItems||[])[e],adEvents:t.adEvents,outboundUrl:t.clickRedirectUrl})))),this.host.encryptedTrackingPayload=i.encryptedTrackingPayload,this.host.additionalEventMetadata=i.additionalEventMetadata)}hydrateAdUserTargetingFromStorage(){const t=n.br();t&&(this.host.adUserTargeting=t)}}const u=a.W(d.S);let _=class extends u{constructor(){super(...arguments),this.adEvents=[],this.impressionId="0",this.isBlank=!1,this.isCommentingDisabled=!1,this.isSharingDisabled=!1,this.isSurveyAd=!1,this.isPromotedCommunityPost=!1,this.isReminderAd=!1,this.placement=t.a8.FEED,this.AdPostHydrationController=new D(this),this.AdPostGalleryLinksController=new h(this),this.pubSub=new t.m(this),this._trackAdClick=this._events.define("observe-ad-click",(async e=>{const i=this.postType===t.f3.Image,s=this.postType===t.f3.Video,a=s&&this.viewType!==t.a6.CompactView&&e.detail.clickLocation!==t.w.MEDIA,n=s&&this.viewType===t.a6.CompactView;(i||n||a)&&(await this._activateLeadGenDialog(),r.s({leadGenInfo:this.leadGenInfo,postId:this.id,impressionId:this.impressionId,onSuccess:()=>this.dispatchEvent(t.c(t.eA))}))})),this.onAdUpdateAction=({action:t,impressionId:e})=>{"hide"===t&&e===this.impressionId&&(this.hidden=!0)}}static get styles(){return[...super.styles,t.K(":host {\n position: relative;\n}\n.ad-link-bar {\n grid-column: 1 / 13;\n height: 40px;\n border-top: transparent;\n}\n.meta-row {\n grid-column: 1 / 4;\n}\n.grid-template-col-inherit {\n grid-template-columns: inherit;\n}\n")]}_activateLeadGenDialog(){return r.a({leadGenInfo:this.leadGenInfo})}get hasAdEvents(){return this.adEvents?.length>0}handleCarouselArrowClick(t){t.preventDefault();const e=t;T.h(this,e,this.impressionId)}handleClickPost(e){if(!this.isReminderAd)return void super.handleClickPost(e);const i=this.querySelector("ad-reminder-button");if(i?.isReminderSet||!1)return void super.handleClickPost(e);m.s(e,{includeFeedChecks:!0})?super.handleClickPost(e):(e.preventDefault(),this.pubSub.publish(t.T.TriggerAdReminderModal,{postId:this.id}))}async handleUpvote(e){if(super.handleUpvote(e),this.isUserLoggedIn&&this.isReminderAd){super.getCurrentVoteType()===i.V.Upvote&&this.pubsub.publish(t.T.TriggerAdReminderModal,{postId:this.id})}}async connectedCallback(){super.connectedCallback(),this.pubSub.subscribe(t.T.AdUpdated,this.onAdUpdateAction),this.setupAdObserver(),await this.resolveCarouselDependencies()}setupAdObserver(){!this.isAdObserved&&this.hasAdEvents&&this.enableAdObserver({postElement:this,events:a.e(this.adEvents),postId:this.id,impressionId:this.impressionId,adType:this.adType,dimensions:this.dimensions,galleryItems:this.galleryItems?.map((t=>({...t,adEvents:a.e(t.adEvents||[])})))})}async resolveCarouselDependencies(){const t=this.querySelector("shreddit-gallery-carousel");t&&(await SML.di("./DoxwPPD-eF.js",import.meta.url,"DoxwPPD-eF"),t.classList.remove("flex"))}handleView(t,e){super.handleView(t,e,this.galleryItems?.length)}handleShareClick(){if(this.isSharingDisabled){const e=t.c("faceplate-alert",{level:t.X.notice,message:"Sharing has been disabled for this post"});this.dispatchEvent(e)}else this.handleShareButtonInteraction()}handleClickCommentsButton(e){if(this.isSurveyAd)super.handleClickCommentsButton(e);else if(this.isCommentingDisabled){const e=t.c("faceplate-alert",{level:t.X.notice,message:"Comments have been disabled for this post"});this.dispatchEvent(e)}else this.isFeed?(this.isPromotedCommunityPost&&!this.outboundLinkUrl.includes("alb.reddit.com")&&this.dispatchEvent(t.c("observe-ad-click",{postId:this.postId,impressionId:this.impressionId,outboundUrl:this.outboundLinkUrl,clickLocation:t.w.COMMENTS_BUTTON})),n.ao({impressionId:this.impressionId,adEvents:this.adEvents,clickRedirectUrl:this.outboundLinkUrl,galleryAdData:this.galleryItems?.map((t=>({adEvents:t.adEvents,clickRedirectUrl:t.outboundUrl}))),encryptedTrackingPayload:this.encryptedTrackingPayload,additionalEventMetadata:this.additionalEventMetadata}),n.ap(this.adUserTargeting),t.f(this,l.w(this))):super.handleClickCommentsButton(e)}renderCommentsButton(){if(this.isCommentingDisabled)return e.x`${s.c({size:d.D,appearance:n.aq()?"bordered":"secondary",attributes:{type:"button",className:d.a,onclick:this.handleClickCommentsButton,name:"comments-action-button","data-post-click-location":t.f6.COMMENTS_BUTTON},leadingIcon:o.c({attributes:{className:"icon-comment","aria-hidden":"true"},size:s.I[d.D]}),screenReaderContent:"comments",children:e.x``})}`;{const e=new URL(this.permalink,window.location.origin);return e.searchParams.set(t.bX,"1"),e.searchParams.set(t.f5,this.impressionId),this.leadGenInfo?.campaignId&&e.searchParams.set(t.f7,this.leadGenInfo.campaignId),this.isPromotedCommunityPost&&e.searchParams.set(t.f8,this.postId),this.permalink=e.pathname+e.search,super.renderCommentsButton()}}renderShareButton(){if(this.isSharingDisabled){const t="Share";return e.x`${s.c({size:d.D,appearance:n.aq()?"bordered":"secondary",attributes:{type:"button",onclick:this.handleShareClick,onkeydown:this.handleShareClick,className:d.a},leadingIcon:E.s({attributes:{className:"icon-share","aria-hidden":"true"},size:s.I[d.D]}),screenReaderContent:t,children:t})}`}return this.shareButtonSSR=!1,super.renderShareButton()}renderHiddenPost(){return e.x`

${"Ad hidden"}

`;}renderActionRow(){return this.isSurveyAd?e.x``:super.renderActionRow()}render(){return this.hidden?this.renderHiddenPost():e.x`${this.isBlank?null:super.render()}`}};t._([t.n({type:String,attribute:"post-id"})],_.prototype,"postId",void 0),t._([t.n({type:Array,attribute:"ad-events",reflect:!0})],_.prototype,"adEvents",void 0),t._([t.n({type:Array,attribute:"gallery-items",reflect:!0})],_.prototype,"galleryItems",void 0),t._([t.n({type:Object,attribute:!0})],_.prototype,"dimensions",void 0),t._([t.n({type:String,attribute:"ad-type"})],_.prototype,"adType",void 0),t._([t.n({type:String,attribute:"outbound-link-url",reflect:!0})],_.prototype,"outboundLinkUrl",void 0),t._([t.n({type:String,attribute:"impression-id",reflect:!0})],_.prototype,"impressionId",void 0),t._([t.n({type:Object,attribute:"ad-user-targeting",reflect:!0})],_.prototype,"adUserTargeting",void 0),t._([t.n({type:Boolean,attribute:"is-blank"})],_.prototype,"isBlank",void 0),t._([t.n({type:Boolean,attribute:"is-commenting-disabled"})],_.prototype,"isCommentingDisabled",void 0),t._([t.n({type:Boolean,attribute:"is-sharing-disabled"})],_.prototype,"isSharingDisabled",void 0),t._([t.n({type:Boolean,attribute:"is-survey-ad"})],_.prototype,"isSurveyAd",void 0),t._([t.n({type:Boolean,attribute:"is-promoted-community-post"})],_.prototype,"isPromotedCommunityPost",void 0),t._([t.n({type:Boolean,attribute:"is-reminder-ad"})],_.prototype,"isReminderAd",void 0),t._([t.n({type:String,attribute:"country-code"})],_.prototype,"countryCode",void 0),t._([t.n({type:String,attribute:"placement"})],_.prototype,"placement",void 0),t._([t.n({type:Object,attribute:"lead-gen-info"})],_.prototype,"leadGenInfo",void 0),t._([t.n({type:String,attribute:"campaign-id"})],_.prototype,"campaignId",void 0),t._([t.n({type:String,attribute:"encrypted-tracking-payload"})],_.prototype,"encryptedTrackingPayload",void 0),t._([t.n({type:Array,attribute:"additional-event-metadata"})],_.prototype,"additionalEventMetadata",void 0),t._([t.n({type:String,attribute:"ad-transparency-encoded-data"})],_.prototype,"adTransparencyEncodedData",void 0),t._([t.n({type:String,attribute:"ads-correlation-id"})],_.prototype,"adsCorrelationId",void 0),_=t._([t.e("shreddit-ad-post")],_)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./Cj45kFzx5i.js",import.meta.url,"Cj45kFzx5i"); SML.dm("Cc7ygtnSSj",["C42E8rVVpA","DUzIBJc2in","CsxDAjmHZE","Cj45kFzx5i"],(async(t,e,r,E)=>{const s=e.W(r.s);let T=class extends s{constructor(){super(...arguments),this.id="",this.subreddit=""}pageIndexChangedCallback(e){super.pageIndexChangedCallback(e);const r=this.pageIndex>e?E.G.Forward:E.G.Backward;t.f(this,E.g(this,r))}};t._([t.n({type:String})],T.prototype,"id",void 0),t._([t.n({type:String})],T.prototype,"subreddit",void 0),T=t._([t.e("shreddit-gallery-listener")],T)})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./JaGlTj3I-9.js",import.meta.url,"JaGlTj3I-9");SML.di("./BI1JuD5RPj.js",import.meta.url,"BI1JuD5RPj"); SML.dm("CcDgzSlONg",["CsxDAjmHZE","C42E8rVVpA","DUzIBJc2in","JaGlTj3I-9","BI1JuD5RPj"],(async(e,t,r,s)=>{function i(e){let t=0,r=0;const s=[];for(const i of e)s[t]=r,t++,r+=i.length;return s[t]=r,s}const a={[s.F.bold]:t=>e.x`${t}`,[s.F.italic]:t=>e.x`${t}`,[s.F.underline]:t=>e.x`${t}`,[s.F.strikethrough]:t=>e.x`${t}`,[s.F.subscript]:t=>e.x`${t}`,[s.F.superscript]:t=>e.x`${t}`,[s.F.monospace]:t=>e.x`${t}`},n=(e,t)=>{try{if(t)return new URL(e,t).toString()}catch{}return e},o=e=>{const t=[];for(const r in s.F){if(isNaN(Number(r)))continue;Number(r)&e&&t.push(r)}return t},c=(e,t)=>{let r=e;for(const e of t){const t=a[e];t&&(r=t(r))}return r},d=t=>{const r=function(e,t=[]){const r=i(e),s=[];let a=0;for(const[i,n,o]of t){const t=n+o,c=r[n]??n,d=r[t]??t;ae.x`${t}`))}`},u=e=>"R "===e?"align-right":"C"===e?"align-center":"align-left",l=(t,r)=>{switch(t.e){case s.j:return(e=>d(e))(t);case s.R:return(t=>e.x`${t.t}`)(t);case s.i:return((t,r)=>{const s=r.targetBlankLinks?"_blank":"_self",i=t.u.startsWith("/")?n(t.u,r.baseUrlForRelativeLinks):t.u;return e.x`${t.t}`})(t,r);case s.h:return((t,r)=>{const s=r.targetBlankSubredditAndUserLinks?"_blank":"_self",i=n(`/${t.e}${t.t}/`,r.baseUrlForRelativeLinks);return e.x`r/${t.t}`})(t,r);case s.g:return((t,r)=>{const s=r.targetBlankSubredditAndUserLinks?"_blank":"_self",i=n(`/user/${t.t}/`,r.baseUrlForRelativeLinks);return e.x`u/${t.t}`})(t,r);case s.P:return((t,r)=>e.x`

${t.c.map((e=>l(e,r)))}

`)(t,r);case s.f:return((t,r)=>{const s=t.c.map((e=>l(e,r)));return t.o?e.x`
    ${s}
`:e.x`
    ${s}
`})(t,r);case s.e:return((t,r)=>e.x`
  • ${t.c?.map((e=>l(e,r)))??""}
  • `)(t,r);case s.d:return((t,r)=>{const s=t.c?.map((e=>l(e,r)))??"";switch(t.l){case 1:return e.x`

    ${s}

    `;case 2:return e.x`

    ${s}

    `;case 3:return e.x`

    ${s}

    `;case 4:return e.x`

    ${s}

    `;case 5:return e.x`
    ${s}
    `;case 6:return e.x`
    ${s}
    `}})(t,r);case s.B:return((t,r)=>e.x`
    ${t.c.map((e=>l(e,r)))}
    `)(t,r);case s.S:return((t,r)=>e.x`${t.c.map((e=>l(e,r)))} `)(t,r);case s.c:return(t=>{const r=t.c.map((e=>e.t)).join("\n");return e.x`
    ${r}
    `})(t);case s.b:return(t=>e.x` `)(t);case s.H:return e.x`
    `;case s.L:return e.x`
    `;case s.I:case s.A:case s.V:return e.x`${t.c}`;case s.C:case s.a:case s.U:return e.x`${t.e}${t.t}`;case s.E:return e.x`${t.c}`;case s.T:return((t,r)=>{const s=t.h;return e.x` ${t.h.map((t=>e.x``))} ${t.c.map((t=>e.x` ${t.map(((t,i)=>e.x``))} `))}
    ${t.c?.map((e=>l(e,r)))??""}
    ${t.c?.map((e=>l(e,r)))??""}
    `})(t,r);default:return e.x``}},m=({richtext:t,wrapperClassName:r="",targetBlankLinks:s=!1,targetBlankSubredditAndUserLinks:i=!1,baseUrlForRelativeLinks:a=""})=>null===t?e.x``:"string"==typeof t?e.x`

    ${t}

    `:e.x`
    ${e.Q(t.document,(e=>l(e,{targetBlankLinks:s,targetBlankSubredditAndUserLinks:i,baseUrlForRelativeLinks:a})))}
    `,h=/:(.*?):/g;const p=(t,r)=>e.x`
    ${t?.match(h)&&r?m({richtext:{document:JSON.parse(r)},wrapperClassName:"max-w-full overflow-hidden whitespace-nowrap text-ellipsis"}):t}
    `;return {M:class{constructor(s){this.userName="",this.subredditId="",this.currentUserName="",this.subredditName="",this.prefixedName="",this.currentRichtext=null,this.isPreviewOpen=!1,this.selectedReplyOption=t.dL.ParticipantSubreddit,this.requestClientGQL=t.C,this.trackEvent=t.f,this.modTeamTooltipText="Send as mod team",this.modNoteTooltipText="Send to mods only",this.updateSubmitTooltip=e=>{this.trackClickEvent("send_as",{action_info:{type:e}}),this.submitTooltipContent&&(e===t.dL.ParticipantSubreddit?this.submitTooltipContent.textContent=this.modTeamTooltipText:e===t.dL.Moderator?this.submitTooltipContent.textContent=this.modUsernameTooltipText():e===t.dL.Unknown&&(this.submitTooltipContent.textContent=this.modNoteTooltipText))},this.renderSavedResponseTemplateBySubredditId=r.b_,this.onSavedResponseItemSelect=async e=>{const{responseId:t}=e.detail;this.onSavedResponseItemClick({responseId:t})},this.onSavedResponseItemClick=async({responseId:e})=>{let t="";const r="prefixedConversationId"in this.host?this.host.prefixedConversationId:null,s=this.userName?{recipientUsernameOverride:this.userName}:{};this.trackClickEvent("saved_response",{action_info:{type:e}});try{t=(await this.renderSavedResponseTemplateBySubredditId({responseId:e,subredditId:this.subredditId,modmailVariables:{modmailConversationId:r,...s}}))?.response?.markdown||""}catch{return}const i=this.getShredditComposerValue();await this.setShredditComposerValue(`${i?`${i}\n`:""}${t}\n`),this.updateComposerValue()},this.onSavedResponsesDropdownSearchInputChange=r.T((e=>{e.preventDefault(),e.stopImmediatePropagation();const t=e.target,r=t?.value,s=this.host.querySelector("#modmail-saved-responses-dropdown");if(s){s.querySelectorAll("rpl-menu-item").forEach((e=>{e.style.display=e.textContent?.toLowerCase().includes(r.toLowerCase())?"block":"none"}))}}),100),this.onKeyDown=(e,t,r=!1)=>{"Enter"!==e.key&&"Space"!==e.code||(r&&(e.preventDefault(),e.stopPropagation()),t())},this.scrollToBottom=e=>{const t=this.host.shadowRoot?.querySelector("#scroll-to-container");t&&t.scrollIntoView({behavior:e?"smooth":"instant"})},this._activateFeature=async e=>t.j(e),this.onKeyDownSavedResponsesClick=e=>this.onKeyDown(e,this.onSavedResponsesClick),this.onSavedResponsesClick=async()=>{await this._activateFeature({name:t.h7,routeParams:{subredditId:this.subredditId},renderMode:t.P.Contents});const e=this.host.querySelector("#modmail-saved-responses-dropdown-search-input");e&&e.addEventListener("input",this.onSavedResponsesDropdownSearchInputChange);const r=this.host.querySelector("#modmail-saved-responses-dropdown-close-button");r&&r.addEventListener("click",this.onSavedResponsesDropdownCloseButtonClick)},this.onSavedResponsesDropdownCloseButtonClick=()=>{const e=this.host.querySelector("#modmail-saved-responses-dropdown");e&&e.hide()},this.updateComposerValue=r.T((async()=>{await this.getRichTextComposerValue().then((e=>{this.currentRichtext=e,0===e?.document.length&&(this.isPreviewOpen=!1)})),this.host.requestUpdate()}),100),this.getShredditComposerValue=()=>this.composer?this.composer.value:"",this.getRichTextComposerValue=async()=>{const e=document.querySelector("shreddit-composer");return (await (e?.getValueAs(t.gj.RichText)))??null;},this.setShredditComposerValue=e=>{this.composer&&(this.composer.value=e)},this.getReplyOptionIcon=e=>{if(e===t.dL.Moderator){const e=document.querySelector('div[slot="reply-user-icon"]')?.cloneNode(!0);return e?.classList.remove("hidden"),e}return e===t.dL.ParticipantSubreddit?document.querySelector('div[slot="reply-subreddit-icon"]')?.cloneNode(!0):""},this.onTogglePreview=async()=>{this.trackClickEvent("message_preview",{action_info:{type:this.isPreviewOpen?"close_preview":"open_preview"}}),this.isPreviewOpen=!this.isPreviewOpen,await this.host.requestUpdate(),this.isPreviewOpen&&this.scrollToBottom(!0)},this.renderPreview=()=>{const r=this.getReplyOptionIcon(this.selectedReplyOption===t.dL.Unknown?t.dL.Moderator:this.selectedReplyOption),s=this.selectedReplyOption===t.dL.ParticipantSubreddit;return e.x`
    ${"Preview"}
    ${r}
    ${s?this.prefixedName:`u/${this.currentUserName}`}
    ${s?e.x`${`u/${this.currentUserName}`} ${" (hidden)"}`:e.x``}
    ${m({richtext:this.currentRichtext,targetBlankLinks:!0,targetBlankSubredditAndUserLinks:!0,baseUrlForRelativeLinks:"https://www.reddit.com"})}
    `;},this.renderPreviewPlacement=()=>e.x` ${this.isPreviewOpen&&this.currentRichtext&&this.currentRichtext?.document?.length>0?this.renderPreview():""}`,this.trackClickEvent=(e,r,s)=>{this.trackEvent(s??this.host,t.b({source:"modmail",action:"click",noun:e},{subreddit:{id:this.subredditId},modmail_conversation:{id:"prefixedConversationId"in this.host?this.host.prefixedConversationId:this.host.conversationId},...r}))},this.renderComposer=()=>e.x` `,this.host=s,s.addController(this)}hostConnected(){this.host.addEventListener("saved-response-click",this.onSavedResponseItemSelect)}hostDisconnected(){this.host.removeEventListener("saved-response-click",this.onSavedResponseItemSelect)}get messageSubmitButton(){return this.host.querySelector("#modmail-message-submit-button")}get composer(){return this.host.querySelector("shreddit-composer")}get submitTooltip(){return this.host.querySelector("rpl-tooltip")}get submitTooltipContent(){return this.submitTooltip?.querySelector('span[slot="content"]')}modUsernameTooltipText(){return `Send as u/${this.currentUserName}`;}},_:l,a:({color:t,backgroundColor:r,text:s="",richText:i,className:a,flairContentRenderer:n=p})=>{if(!s)return"";const o=function(e,t){return!e||!t||"transparent"===t}(t??"",r??"");return e.x` ${n(s,i)} `},b:function(e){let t=0,r=0;const s=[];for(const i of e){for(let e=0;e{const{svg:l}=a.g();return{c:a.m(l``,"0 0 20 20","caution")}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("CeSBv4aKUm",["CsxDAjmHZE","C42E8rVVpA","DUzIBJc2in"],(async(t,c,n)=>{const{svg:u}=t.g();function a(t,c){const u=n.v(t);return u?u.slice(0,c):[]}return{a:(t,c,u)=>{const e=a(c,u),i=new Map,m=[t,...e];for(;m.length&&i.sizet.uuid===e[c].uuid))||n.u(c,r)},c:t.m(u``,"0 0 20 20","community-fill"),g:a,r:()=>c.b({source:"community_nav",action:"click",noun:"community_recent"})}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./BUnsiaD7oQ.js",import.meta.url,"BUnsiaD7oQ");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./CMwQRCekeQ.js",import.meta.url,"CMwQRCekeQ");SML.di("./UD2pUVjMzE.js",import.meta.url,"UD2pUVjMzE");SML.di("./B-LgD4K8b5.js",import.meta.url,"B-LgD4K8b5");SML.di("./By3M4InPRM.js",import.meta.url,"By3M4InPRM");SML.di("./B7xOUSlR-V.js",import.meta.url,"B7xOUSlR-V");SML.di("./ChVzN5arel.js",import.meta.url,"ChVzN5arel"); SML.dm("Ceb0ABsHlF",["C42E8rVVpA","CsxDAjmHZE","BUnsiaD7oQ","DUzIBJc2in","CMwQRCekeQ","UD2pUVjMzE","B-LgD4K8b5","By3M4InPRM","B7xOUSlR-V","ChVzN5arel"],(async(t,e,i,s,r,n,a,o,l,h)=>{function d(t){void 0!==window.requestIdleCallback?window.requestIdleCallback(t):window.setTimeout(t,1)}class c{constructor(t){this.fromReconnect=!1,(this.host=t).addController(this)}async hostConnected(){await this._enableAutoplayIfApplicable()}fullscreenChange(){this.trackEvent(t.eE)}pause(){this.trackEvent(t.eF)}play(){this.trackEvent(t.eG)}timeUpdate(){this.trackEvent(t.eK)}volumeChange(){this.trackEvent(t.eH)}seeking(){this.trackEvent(t.eI)}seeked(){this.trackEvent(t.eJ)}trackEvent(e){if(!this.host.postPromoted)return;const{currentTime:i,duration:s,muted:r,paused:n,volume:a}=this.host.videoElement,o=this.host.mediaUI?.hasAttribute(t.gt.FULLSCREEN)||!1;let l=!1;e!==t.eJ&&e!==t.eI||(l=this.fromReconnect),e===t.eJ&&(this.fromReconnect=!1);const h=t.c(e,{currentTime:i,duration:s,fullscreen:o,muted:r,paused:n,timeStamp:Date.now(),volume:a,fromReconnect:l});this.host.dispatchEvent(h)}async _enableAutoplayIfApplicable(){if(!this.host.postPromoted)return;const e=(await t.cm()).isAdblockEnabled;("true"===new URL(t.e4.href).searchParams.get(t.ke)||!e&&this.host.autoplayPref)&&(this.host.autoplay=!0,this.host.volumeController.setInitialVolumeSetting(),this.host.mediaVisibilityController.shouldVideoAutoplay()&&(this.host.idleAutoplay?d(this.host.mediaVisibilityController.attemptAutoplay):this.host.mediaVisibilityController.attemptAutoplay()))}}function u({msg:t,error:e,debugOverlay:i}){const s=g(t,e);window.Sentry?window.Sentry.captureMessage?.(s):console.log(s),i?.log("logMessage",s)}function f({msg:t,error:e,debugOverlay:i}){const s=g(t,e);window.Sentry?window.Sentry.captureException?.(s):console.error(s),i?.log("logException",s)}function g(t,e){return["shreddit-player",t,e].filter(Boolean).join(" | ")}let m=class{constructor(e){this._retryCount=0,this._logException=f,this._logMessage=u,this.setMediaErrorCode=e=>{const i=this.host.mediaUI;i&&(i.setAttr(t.gt.ERROR),i.setPausedState(),i.hideLoadingSpinner(),this.mediaErrorCode=e,i.errorOverlay&&(i.errorOverlay.mediaErrorCode=e))},this.handleVideoError=()=>{d((()=>{const t=this.videoElement?.error,{hlsController:e,isHls:i}=this.host;if(t?.code){if(t.code===p.SrcNotSupported&&i&&this._retryCount<5)return this._retryCount+=1,e.initializeHlsJs(),void this._logMessage({msg:`Video error, reinitializing Hls.js: [${t.code}] ${t.message}`,debugOverlay:this.host.debugOverlay});this._logException({msg:`Video error: [${t.code}] ${t.message}`,debugOverlay:this.host.debugOverlay}),this.setMediaErrorCode(t.code),this.host.telemetryController.error(),this.host.updateSubSession()}}))},this.handleHlsError=async(t,e)=>{const{hlsController:i}=this.host,{hls:s}=i;if(s){if(this._retryCount>=5)return this._logException({msg:`HLS error: exceeded max retries: [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),void this._handleHlsIrrecoverableError();switch(this._retryCount+=1,e.type){case"networkError":(e.networkDetails?.status||0)>=500?(this._logException({msg:`HLS error: network error: [${e.networkDetails?.status}] [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),this._handleHlsIrrecoverableError()):403===e.networkDetails?.status?(this._logMessage({msg:`HLS error: network error: [${e.networkDetails?.status}] [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),this._handleHlsIrrecoverableError()):(this._logMessage({msg:`HLS error: network error: [${e.networkDetails?.status}] [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),this.setMediaErrorCode(p.Network),s.startLoad());break;case"mediaError":"audioTrackLoadError"===e.details?(this._logMessage({msg:`HLS error: audioTrackLoadError, switching to audio track 0: [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),s.audioTrack=0):(this._logMessage({msg:`HLS error: mediaError: [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),e.fatal&&s.recoverMediaError());break;default:e.fatal&&(this._logException({msg:`HLS error: unknown fatal error: [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),this._handleHlsIrrecoverableError())}}},this.resetRetryCount=()=>{this._retryCount=0},(this.host=e).addController(this),this.videoElement=e.videoElement,this.host.errorImprovements}hostConnected(){this.host.errorImprovements||this.videoElement.addEventListener("error",this.handleVideoError)}hostDisconnected(){this.host.errorImprovements||this.videoElement.removeEventListener("error",this.handleVideoError)}_handleHlsIrrecoverableError(){this.host.hlsController.destroyHlsEngine(),this.setMediaErrorCode(p.Network),this.host.telemetryController.error(),this.host.updateSubSession()}};var p;!function(t){t[t.Aborted=1]="Aborted",t[t.Network=2]="Network",t[t.Decode=3]="Decode",t[t.SrcNotSupported=4]="SrcNotSupported"}(p||(p={}));const v=new Map([[MediaError.MEDIA_ERR_ABORTED,0],[MediaError.MEDIA_ERR_NETWORK,5],[MediaError.MEDIA_ERR_DECODE,2],[MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,1]]);class y{constructor(e){this._retryAttempts=new Map,this._logException=f,this._logMessage=u,this.setMediaError=e=>{const i=this.host.mediaUI;i&&(i.setAttr(t.gt.ERROR),i.setPausedState(),i.hideLoadingSpinner(),this.mediaErrorCode=e,i.errorOverlay&&(i.errorOverlay.mediaErrorCode=e))},this.handleVideoError=()=>{d((()=>{const t=this.videoElement.error;t?.code&&(t.code!==MediaError.MEDIA_ERR_ABORTED?this._shouldRetry(t.code)?this._attemptRetry(t.code,t.message):this._handleIrrecoverableError(t.code,t.message):this.host.pause("scroll"))}))},this.handleHlsError=async(t,e)=>{const{hlsController:i}=this.host,{hls:s}=i;if(s)if(this._shouldRetry(MediaError.MEDIA_ERR_NETWORK))switch(this._incrementRetryCount(MediaError.MEDIA_ERR_NETWORK),e.type){case"networkError":"manifestLoadError"===e.details||"manifestParsingError"===e.details?s.loadSource(this.host.src):s.startLoad(),this._attemptPlayback("HLS network error recovery");break;case"mediaError":if("audioTrackLoadError"===e.details&&0!==s.audioTrack)s.audioTrack=0;else if(this._logMessage({msg:`HLS error: mediaError: [${e.details}]`,error:e.error,debugOverlay:this.host.debugOverlay}),e.fatal)s.recoverMediaError();else if("bufferStalledError"===e.details)return;this._attemptPlayback("HLS media error recovery");break;default:s.startLoad(),this._attemptPlayback("HLS default error recovery")}else this._handleHlsIrrecoverableError(e)},this.resetRetryCount=()=>{this._retryAttempts=new Map},this._incrementRetryCount=t=>{const e=this._retryAttempts.get(t)||0;this._retryAttempts.set(t,e+1)},this._shouldRetry=t=>{if(!this.host.isConnected)return!1;if(!this.videoElement||this.videoElement.error?.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED)return!1;if(!t)return!1;const e=v.get(t)??3;return(this._retryAttempts.get(t)||0){this._incrementRetryCount(t);const i=this._retryAttempts.get(t)||0,s=v.get(t)??3;if(this._logMessage({msg:`Video error: [${t}] ${e} - retrying (${i}/${s})`,debugOverlay:this.host.debugOverlay}),t===MediaError.MEDIA_ERR_DECODE){const t=this.videoElement.src;this.videoElement.removeAttribute("src"),this.videoElement.load(),this.videoElement.src=t,this._attemptPlayback("decode error retry")}else this._attemptPlayback("network error retry")},this._attemptPlayback=t=>{this.videoElement.play().catch((e=>{this._logMessage({msg:`Play failed during ${t}: ${e.message}`,debugOverlay:this.host.debugOverlay})}))},this._handleIrrecoverableError=(t,e)=>{this._logException({msg:`Irrecoverable video error: [${t}] ${e}`,debugOverlay:this.host.debugOverlay}),this.setMediaError(t),this.host.telemetryController.error(),this.host.updateSubSession()},this._handleHlsIrrecoverableError=t=>{const e={...Object.fromEntries(["manifestLoadError","levelLoadError","fragLoadError","bufferStalledError"].map((t=>[t,MediaError.MEDIA_ERR_NETWORK]))),...Object.fromEntries(["keyLoadError","bufferAppendingError","fragDecryptError","levelSwitchError","keySystemNoKeys"].map((t=>[t,MediaError.MEDIA_ERR_DECODE]))),manifestParsingError:MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED};let i;i=t.details in e?e[t.details]:"networkError"===t.type?MediaError.MEDIA_ERR_NETWORK:MediaError.MEDIA_ERR_DECODE,this._logException({msg:`Irrecoverable HLS error: ${t.type} ${t.details}`,debugOverlay:this.host.debugOverlay}),this.setMediaError(i),this.host.telemetryController.error(),this.host.hlsController.destroyHlsEngine(),this.host.updateSubSession()},(this.host=e).addController(this),this.videoElement=e.videoElement,e.errorImprovements}hostConnected(){this.host.errorImprovements&&this.videoElement.addEventListener("error",this.handleVideoError)}hostDisconnected(){this.host.errorImprovements&&this.videoElement.removeEventListener("error",this.handleVideoError)}}class E{constructor(t){this.handleClick=()=>{this.host.isMobile&&!this.host.videoElement?.paused&&this.host.userIdleController?.isIdle||this.host.mediaActionsController?.togglePlay()},this.handleDblClick=()=>{this.host.mediaActionsController?.toggleFullscreen()},(this.host=t).addController(this)}hostConnected(){this.host.gif||(this.host.videoElement.addEventListener("click",this.handleClick),this.host.videoElement.addEventListener("dblclick",this.handleDblClick))}hostDisconnected(){this.host.gif||(this.host.videoElement.removeEventListener("click",this.handleClick),this.host.videoElement.removeEventListener("dblclick",this.handleDblClick))}}function T(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var S,b,A,L,R,k={exports:{}};S=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,b=/^(?=([^\/?#]*))\1([^]*)$/,A=/(?:\/|^)\.(?=\/)/g,L=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,k.exports=R={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var s=R.parseURL(t);if(!s)throw new Error("Error trying to parse base URL.");return s.path=R.normalizePath(s.path),R.buildURLFromParts(s)}var r=R.parseURL(e);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return i.alwaysNormalize?(r.path=R.normalizePath(r.path),R.buildURLFromParts(r)):e;var n=R.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=b.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=R.normalizePath(h)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=i.alwaysNormalize?R.normalizePath(r.path):r.path),R.buildURLFromParts(o)},parseURL:function(t){var e=S.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(A,"");t.length!==(t=t.replace(L,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var C=k.exports;function _(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,s)}return i}function I(t){for(var e=1;e`):$}(e)}))}const V=G,K=/^(\d+)x(\d+)$/,j=/(.+?)=(".*?"|.*?)(?:,|$)/g;class W{constructor(t){"string"==typeof t&&(t=W.parseAttrList(t)),P(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;tNumber.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=K.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const i={};for(j.lastIndex=0;null!==(e=j.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));i[e[1].trim()]=t}return i}}function Y(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class z{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){V.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=P(new W({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);x(t.getTime())&&(this._endDate=t)}}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 t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(x(t))return t}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&&x(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class q{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 X="audio",Q="video",J="audiovideo";class Z{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[X]:null,[Q]:null,[J]:null},this.baseurl=t}setByteRange(t,e){const i=t.split("@",2);let s;s=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}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=C.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class tt extends Z{constructor(t,e){super(e),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 q,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!x(this.programDateTime))return null;const t=x(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[X]=null,t[Q]=null,t[J]=null}}class et extends Z{constructor(t,e,i,s,r){super(i),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 q,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,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:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class it{constructor(t){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=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&x(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.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 t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function st(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function rt(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),s=t[t.length-1].split(",");if(2===s.length){const e="base64"===s[0],r=s[1];e?(t.splice(-1,1),i=st(r)):i=function(t){const e=nt(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}function nt(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const at="undefined"!=typeof self?self:void 0;var ot={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},lt="org.w3.clearkey",ht="com.apple.streamingkeydelivery",dt="com.microsoft.playready",ct="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ut(t){switch(t){case ht:return ot.FAIRPLAY;case dt:return ot.PLAYREADY;case ct:return ot.WIDEVINE;case lt:return ot.CLEARKEY}}var ft="edef8ba979d64acea3c827dcd51d21ed";function gt(t){switch(t){case ot.FAIRPLAY:return ht;case ot.PLAYREADY:return dt;case ot.WIDEVINE:return ct;case ot.CLEARKEY:return lt}}function mt(t){const{drmSystems:e,widevineLicenseUrl:i}=t,s=e?[ot.FAIRPLAY,ot.WIDEVINE,ot.PLAYREADY,ot.CLEARKEY].filter((t=>!!e[t])):[];return!s[ot.WIDEVINE]&&i&&s.push(ot.WIDEVINE),s}const pt=null!=at&&null!=(vt=at.navigator)&&vt.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var vt;function yt(t,e,i){return Uint8Array.prototype.slice?t.slice(e,i):new Uint8Array(Array.prototype.slice.call(t,e,i))}const Et=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,Tt=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,St=(t,e)=>{const i=e;let s=0;for(;Et(t,e);){s+=10;s+=bt(t,e+6),Tt(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(i,i+s)},bt=(t,e)=>{let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i},At=(t,e)=>Et(t,e)&&bt(t,e+6)+10<=t.length-e,Lt=t=>{const e=Ct(t);for(let t=0;tt&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,kt=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=bt(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}},Ct=t=>{let e=0;const i=[];for(;Et(t,e);){const s=bt(t,e+6);e+=10;const r=e+s;for(;e+8"PRIV"===t.type?It(t):"W"===t.type[0]?wt(t):Dt(t),It=t=>{if(t.size<2)return;const e=xt(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}},Dt=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=xt(t.data.subarray(e),!0);e+=i.length+1;const s=xt(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=xt(t.data.subarray(1));return{key:t.type,data:e}},wt=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=xt(t.data.subarray(e),!0);e+=i.length+1;const s=xt(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=xt(t.data);return{key:t.type,data:e}},Pt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}},xt=(t,e=!1)=>{const i=Ot();if(i){const s=i.decode(t);if(e){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"");}const s=t.length;let r,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&r)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&a)}}return o};let Mt;function Ot(){if(!navigator.userAgent.includes("PlayStation 4"))return Mt||void 0===self.TextDecoder||(Mt=new self.TextDecoder("utf-8")),Mt}const Ft=function(t){let e="";for(let i=0;i>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function Wt(t,e){const i=[];if(!e.length)return i;const s=t.byteLength;for(let r=0;r1?r+n:s;if(Bt(t.subarray(r+4,r+8))===e[0])if(1===e.length)i.push(t.subarray(r+8,a));else{const s=Wt(t.subarray(r+8,a),e.slice(1));s.length&&Ut.apply(i,s)}r=a}return i}function Yt(t){const e=[],i=t[0];let s=8;const r=Ht(t,s);s+=4;let n=0,a=0;0===i?(n=Ht(t,s),a=Ht(t,s+4),s+=8):(n=Vt(t,s),a=Vt(t,s+8),s+=16),s+=2;let o=t.length+a;const l=Gt(t,s);s+=2;for(let i=0;i>>31)return V.warn("SIDX has hierarchical references (not supported)"),null;const l=Ht(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:e}}function zt(t){const e=[],i=Wt(t,["moov","trak"]);for(let t=0;t{const i=Ht(t,4),s=e[i];s&&(s.default={duration:Ht(t,12),flags:Ht(t,20)})})),e}function qt(t){const e=t.subarray(8),i=e.subarray(86),s=Bt(e.subarray(4,8));let r=s;const n="enca"===s||"encv"===s;if(n){const t=Wt(e,[s])[0];Wt(t.subarray("enca"===s?28:78),["sinf"]).forEach((t=>{const e=Wt(t,["schm"])[0];if(e){const i=Bt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Wt(t,["frma"])[0];e&&(r=Bt(e))}}}))}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Wt(i,["avcC"])[0];r+="."+Qt(t[1])+Qt(t[2])+Qt(t[3]);break}case"mp4a":{const t=Wt(e,[s])[0],i=Wt(t.subarray(28),["esds"])[0];if(i&&i.length>12){let t=4;if(3!==i[t++])break;t=Xt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Xt(i,t);const s=i[t++];if(64!==s)break;if(r+="."+Qt(s),t+=12,5!==i[t++])break;t=Xt(i,t);const n=i[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[t])>>5)),r+="."+a}break}case"hvc1":case"hev1":{const t=Wt(i,["hvcC"])[0],e=t[1],s=["","A","B","C"][e>>6],n=31&e,a=Ht(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);r+="."+s+n,r+="."+a.toString(16).toUpperCase(),r+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}r+=d;break}case"dvh1":case"dvhe":{const t=Wt(i,["dvcC"])[0],e=t[2]>>1&127,s=t[2]<<5&32|t[3]>>3&31;r+="."+Jt(e)+"."+Jt(s);break}case"vp09":{const t=Wt(i,["vpcC"])[0],e=t[4],s=t[5],n=t[6]>>4&15;r+="."+Jt(e)+"."+Jt(s)+"."+Jt(n);break}case"av01":{const t=Wt(i,["av1C"])[0],e=t[1]>>>5,s=31&t[1],n=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2],f=1,g=1,m=1,p=0;r+="."+e+"."+Jt(s)+n+"."+Jt(l)+"."+h+"."+d+c+u+"."+Jt(f)+"."+Jt(g)+"."+Jt(m)+"."+p;break}}return{codec:r,encrypted:n}}function Xt(t,e){const i=e+5;for(;128&t[e++]&&e{const l=o.byteOffset-8;Wt(o,["traf"]).map((o=>{const h=Wt(o,["tfdt"]).map((t=>{const e=t[0];let i=Ht(t,4);return 1===e&&(i*=Math.pow(2,32),i+=Ht(t,8)),i/r}))[0];return void 0!==h&&(t=h),Wt(o,["tfhd"]).map((h=>{const d=Ht(h,4),c=16777215&Ht(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=Ht(h,p),p+=4),f&&(g=Ht(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),i=e<0?t:t.substring(0,e);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(e.codec)),Wt(o,["trun"]).map((n=>{const o=n[0],h=16777215&Ht(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const b=Ht(n,4);let A=8;d&&(c=Ht(n,A),A+=4),f&&(A+=4);let L=c+l;for(let l=0;l>1&63;return 39===t||40===t}return 6===(31&e)}function re(t,e,i,s){const r=ne(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(ot){V.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Gt(r,e);if(e+=2,49===t){const t=Ht(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t16){const t=[];for(let i=0;i<16;i++){const s=r[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let s=8,r=i;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r>8*(15-i)&255;return e}(t);return new le(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=rt(this.uri);if(e)switch(this.keyFormat){case ct:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case dt:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ae(t,0,e);const i=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),s=String.fromCharCode.apply(null,Array.from(i)),r=s.substring(s.indexOf("<"),s.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=st(t).subarray(0,16);!function(t){const e=function(t,e,i){const s=t[e];t[e]=t[i],t[i]=s};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=oe[this.uri];if(!t){const e=Object.keys(oe).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),oe[this.uri]=t}this.keyId=t}return this}}const he=/\{\$([a-zA-Z0-9-_]+)\}/g;function de(t){return he.test(t)}function ce(t,e,i){if(null!==t.variableList||t.hasVariableRefs)for(let s=i.length;s--;){const r=i[s],n=e[r];n&&(e[r]=ue(t,n))}}function ue(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(he,(e=>{const s=e.substring(2,e.length-1),r=null==i?void 0:i[s];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):r}))}return e}function fe(t,e,i){let s,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,r=e.VALUE;s in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function ge(t,e,i){const s=e.IMPORT;if(i&&s in i){let e=t.variableList;e||(t.variableList=e={}),e[s]=i[s]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function me(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const pe={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ve(t,e,i=!0){return!t.split(",").some((t=>!ye(t,e,i)))}function ye(t,e,i=!0){var s;const r=me(i);return null!=(s=null==r?void 0:r.isTypeSupported(Ee(t,e)))&&s}function Ee(t,e){return`${e}/mp4;codecs="${t}"`}function Te(t){if(t){const e=t.substring(0,4);return pe.video[e]}return 2}function Se(t){return t.split(",").reduce(((t,e)=>{const i=pe.video[e];return i?(2*i+t)/(t?3:2):(pe.audio[e]+t)/(t?2:1)}),0)}const be={};const Ae=/flac|opus/i;function Le(t,e=!0){return t.replace(Ae,(t=>(function(t, e=!0) {if(be[t])return be[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let s=0;s0&&s.length({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ce.lastIndex=0;null!==(s=Ce.exec(t));){const t=new W(s[1]),n=t.TYPE;if(n){const s=a[n],l=r[n]||[];r[n]=l,ce(i,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?we.resolve(t.URI,e):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=s&&s.length){const t=we.findGroup(s,g.groupId)||s[0];Oe(g,t,"audioCodec"),Oe(g,t,"textCodec")}l.push(g)}}return r}static parseLevelPlaylist(t,e,i,s,r,n){const a=new it(e),o=a.fragments;let l,h,d,c=null,u=0,f=0,g=0,m=0,p=null,v=new tt(s,e),y=-1,E=!1,T=null;for(Ie.lastIndex=0,a.m3u8=t,a.hasVariableRefs=de(t);null!==(l=Ie.exec(t));){E&&(E=!1,v=new tt(s,e),v.start=g,v.sn=u,v.cc=m,v.level=i,c&&(v.initSegment=c,v.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,T&&(v.setByteRange(T),T=null)));const t=l[1];if(t){v.duration=parseFloat(t);const e=(" "+l[2]).slice(1);v.title=e||null,v.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(x(v.duration)){v.start=g,d&&Ue(v,d,a),v.sn=u,v.level=i,v.cc=m,o.push(v);const t=(" "+l[3]).slice(1);v.relurl=ue(a,t),Fe(v,p),p=v,g+=v.duration,u++,f=0,E=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);p?v.setByteRange(t,p):v.setByteRange(t)}else if(l[5])v.rawProgramDateTime=(" "+l[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===y&&(y=o.length);else{if(l=l[0].match(De),!l){V.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new W(r);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const i=f>0?t[t.length-1]:void 0,s=f++,n=new W(r);ce(a,n,["BYTERANGE","URI"]);const o=new et(n,v,e,s,i);t.push(o),v.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new W(r);ce(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new W(r);ce(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:V.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(Fe(v,p),v.cc=m,a.fragmentHint=v,d&&Ue(v,d,a));const S=o.length,b=o[0],A=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&A){a.averagetargetduration=g/S;const t=A.sn;a.endSN="initSegment"!==t?t:0,a.live||(A.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,y>0&&function(t,e){let i=t[e];for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(o,y),a}}function Pe(t,e,i){var s,r;const n=new W(t);ce(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&V.error(`Invalid IV: ${n.IV}`);const c=o?we.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new le(a,c,d,u,l)}function xe(t){const e=new W(t).decimalFloatingPoint("TIME-OFFSET");return x(e)?e:null}function Me(t,e){let i=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const s=i.filter((e=>(function(t, e) {const i=pe[e];return!!i&&!!i[t.slice(0,4)]})(e,t)));s.length&&(e[`${t}Codec`]=s.join(","),i=i.filter((t=>-1===s.indexOf(t))))})),e.unknownCodecs=i}function Oe(t,e,i){const s=e[i];s&&(t[i]=s)}function Fe(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),x(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ne(t,e,i,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function Ue(t,e,i){t.levelkeys=e;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||s.push(t)}var $e="manifest",Be="level",Ge="audioTrack",He="subtitleTrack",Ve="main",Ke="audio",je="subtitle";function We(t){const{type:e}=t;switch(e){case Ge:return Ke;case He:return je;default:return Ve}}function Ye(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class ze{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.LEVEL_LOADING,this.onLevelLoading,this),t.on(F.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(F.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.LEVEL_LOADING,this.onLevelLoading,this),t.off(F.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(F.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=new(i||s)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:$e,url:i,deliveryDirectives:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:Be,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:Ge,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:He,url:r,deliveryDirectives:n})}load(t){var e;const i=this.hls.config;let s,r=this.getInternalLoader(t);if(r){const e=r.context;if(e&&e.url===t.url&&e.level===t.level)return void V.trace("[playlist-loader]: playlist request ongoing");V.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(s=t.type===$e?i.manifestLoadPolicy.default:P({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),x(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===Be&&null!==t.level?e=this.hls.levels[t.level].details:t.type===Ge&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===He&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);s=P({},s,{maxTimeToFirstByteMs:Math.min(e,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),we.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,i,s||null,r):this.handleMasterPlaylist(t,e,i,s)):this.handleManifestParsingError(t,i,new Error("no EXTM3U delimiter"),s||null,e)},onError:(t,e,i,s)=>{this.handleNetworkError(e,i,!1,t,s)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};r.load(t,a,o)}handleMasterPlaylist(t,e,i,s){const r=this.hls,n=t.data,a=Ye(t,i),o=we.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,i,o.playlistParsingError,s,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=we.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(V.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new W({}),bitrate:0,url:""}))}r.trigger(F.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:s,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,h=Ye(t,i),d=x(o)?o:x(a)?a:0,c=We(i),u=we.parseLevelPlaylist(t.data,h,d,c,0,this.variableList);if(l===$e){const t={attrs:new W({}),bitrate:0,details:u,name:"",url:h};n.trigger(F.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,t,e,i,s,r)}handleManifestParsingError(t,e,i,s,r){this.hls.trigger(F.ERROR,{type:N.NETWORK_ERROR,details:U.MANIFEST_PARSING_ERROR,fatal:e.type===$e,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:r})}handleNetworkError(t,e,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===Be?n+=`: ${t.level} id: ${t.id}`:t.type!==Ge&&t.type!==He||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);V.warn(`[playlist-loader]: ${n}`);let o=U.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case $e:o=i?U.MANIFEST_LOAD_TIMEOUT:U.MANIFEST_LOAD_ERROR,l=!0;break;case Be:o=i?U.LEVEL_LOAD_TIMEOUT:U.LEVEL_LOAD_ERROR,l=!1;break;case Ge:o=i?U.AUDIO_TRACK_LOAD_TIMEOUT:U.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case He:o=i?U.SUBTITLE_TRACK_LOAD_TIMEOUT:U.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const d={type:N.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(s){const i=(null==e?void 0:e.url)||t.url;d.response=I({url:i,data:void 0},s)}this.hls.trigger(F.ERROR,d)}handlePlaylistLoaded(t,e,i,s,r,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:c}=s,u=Ye(e,s),f=We(s),g="number"==typeof s.level&&f===Ve?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(F.ERROR,{type:N.NETWORK_ERROR,details:U.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:t,reason:t.message,response:e,context:s,level:g,parent:f,networkDetails:r,stats:i})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m)a.trigger(F.ERROR,{type:N.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:e,context:s,level:g,parent:f,networkDetails:r,stats:i});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case $e:case Be:a.trigger(F.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:c});break;case Ge:a.trigger(F.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:i,networkDetails:r,deliveryDirectives:c});break;case He:a.trigger(F.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:i,networkDetails:r,deliveryDirectives:c})}}}function qe(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function Xe(t,e){const i=t.mode;if("disabled"===i&&(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(i){V.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){V.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Qe(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function Je(t,e,i,s){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const s=[],r=function(t,e){if(et[i].endTime)return-1;let s=0,r=i;for(;s<=r;){const n=Math.floor((r+s)/2);if(et[n].startTime&&s-1)for(let n=r,a=t.length;n=e&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e{const t=si();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ai(t,e){return t.getTime()/1e3-e}class oi{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(F.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(F.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(F.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(F.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(Qe(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;eni&&(s=ni);s-i<=0&&(s=i+.25);for(let t=0;tt.type===ti&&o:"video"===s?t=>t.type===ii&&a:t=>t.type===ti&&o||t.type===ii&&a,Je(r,e,i,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:r}=e,n=Object.keys(r);if(s){const t=Object.keys(i).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const r=t[e];Object.keys(i[r].cues).forEach((t=>{s.removeCue(i[r].cues[t])})),delete i[r]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!x(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=si();for(let t=0;t{if(e!==s.id){const i=r[e];if(i.class===s.class&&i.startDate>s.startDate&&(!t||s.startDatethis.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*s);const h=s;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(null===t||null===e||null===i)return null;const s=i.edge,r=t-e-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(F.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(F.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(F.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(F.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(F.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(F.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(F.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(F.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(F.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(F.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var i;e.details===U.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&V.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,i))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const hi=["NONE","TYPE-0","TYPE-1",null];const di=["SDR","PQ","HLG"];var ci="",ui="YES",fi="v2";function gi(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return vi(this._audioGroups,t)}hasSubtitleGroup(t){return vi(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function vi(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function yi(t,e){const i=e.startPTS;if(x(i)){let s,r=0;e.sn>t.sn?(r=i-t.start,s=t):(r=t.start-i,s=e),s.duration!==r&&(s.duration=r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function Ei(t,e,i,s,r,n){s-i<=0&&(V.warn("Fragment should have a positive duration",e),s=i+e.duration,n=r+e.duration);let a=i,o=s;const l=e.startPTS,h=e.endPTS;if(x(l)){const t=Math.abs(l-i);x(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(i,l),i=Math.min(i,l),r=Math.min(r,e.startDTS),o=Math.min(s,h),s=Math.max(s,h),n=Math.max(n,e.endDTS)}const d=i-e.start;0!==e.start&&(e.start=i),e.duration=s-e.start,e.startPTS=i,e.maxStartPTS=a,e.startDTS=r,e.endPTS=s,e.minEndPTS=o,e.endDTS=n;const c=e.sn;if(!t||ct.endSN)return 0;let u;const f=c-t.startSN,g=t.fragments;for(g[f]=e,u=f;u>0;u--)yi(g[u],g[u-1]);for(u=f;u=0;t--){const e=s[t].initSegment;if(e){i=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let r,n=0;if(function(t,e,i){const s=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(s?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=r;t<=n;t++){const r=l[a+t];let n=o[t];s&&!n&&t{t.relurl&&(n=t.cc-s.cc),x(t.startPTS)&&x(t.endPTS)&&(s.start=s.startPTS=t.startPTS,s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.duration=t.endPTS-t.startPTS,s.duration&&(r=s),e.PTSKnown=e.alignedSliding=!0),s.elementaryStreams=t.elementaryStreams,s.loader=t.loader,s.stats=t.stats,t.initSegment&&(s.initSegment=t.initSegment,i=t.initSegment)})),i){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){V.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const s=P({},t);i&&i.forEach((t=>{delete s[t]}));return Object.keys(e).forEach((t=>{const i=new z(e[t].attr,s[t]);i.isValid?s[t]=i:V.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),s}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){V.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),r?Ei(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):Si(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function Si(t,e){const i=e.startSN+e.skippedSegments-t.startSN,s=t.fragments;i<0||i>=s.length||bi(e,s[i].start)}function bi(t,e){if(e){const i=t.fragments;for(let s=t.skippedSegments;s{const{details:i}=t;null!=i&&i.fragments&&i.fragments.forEach((t=>{t.level=e}))}))}function ki(t){switch(t.details){case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_TIMEOUT:case U.LEVEL_LOAD_TIMEOUT:case U.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ci(t,e){const i=ki(e);return t.default[(i?"timeout":"error")+"Retry"]}function _i(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function Ii(t){return I(I({},t),{errorRetry:null,timeoutRetry:null})}function Di(t,e,i,s){if(!t)return!1;const r=null==s?void 0:s.code,n=e499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}const wi=function(t,e){let i=0,s=t.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=t[r];const a=e(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Pi(t,e,i=0,s=0){let r=null;if(t){r=e[t.sn-e[0].sn+1]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7)}else 0===i&&0===e[0].start&&(r=e[0]);if(r&&(!t||t.level===r.level)&&0===xi(i,s,r))return r;const n=wi(e,xi.bind(null,i,s));return!n||n===t&&r?r:n}function xi(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=t?1:i.start-s>t&&i.start?-1:0}function Mi(t,e,i){const s=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>t}var Oi=0,Fi=2,Ni=3,Ui=5,$i=0,Bi=1,Gi=2;class Hi{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=V.log.bind(V,`${e}:`),this.warn=V.warn.bind(V,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i=0&&t>e.partTarget&&(a+=1)}const o=i&&gi(i);return new mi(n,a>=0?a:void 0,o)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,i){const{details:s,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;if(s.advancedDateTime=Date.now()-a,s.live||null!=i&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&Ti(i,s),!this.canLoad||!s.live)return;let a,o,l;if(s.canBlockReload&&s.endSN&&s.advanced){const t=this.hls.config.lowLatencyMode,r=s.lastPartSn,n=s.endSN,h=s.lastPartIndex,d=r===n;-1!==h?(o=d?n+1:r,l=d?t?0:h:h+1):o=n+1;const c=s.age,u=c+s.ageHeader;let f=Math.min(u-s.partTarget,1.5*s.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${s.age}`),f=0;else{const t=Math.floor(f/s.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}s.tuneInGoal=f}if(a=this.getDeliveryDirectives(s,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(s.canBlockReload||s.canSkipUntil)&&(a=this.getDeliveryDirectives(s,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=function(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,r=4;if(s.length&&i*r>e){const t=1e3*s[s.length-1].duration;tthis.requestScheduled+c&&(this.requestScheduled=r.loading.start),void 0!==o&&s.canBlockReload?this.requestScheduled=r.loading.first+c-(1e3*s.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+cthis.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(t,e,i,s){let r=gi(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=ci),new mi(i,s,r)}checkRetry(t){const e=t.details,i=ki(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Ui||!s.resolved&&r===Fi);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=_i(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,s.resolved=!0}return o}}class Vi{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Ki{constructor(t,e,i,s=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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Vi(t),this.fast_=new Vi(e),this.defaultTTFB_=s,this.ttfb_=new Vi(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new Vi(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Vi(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Vi(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,s=8*e/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,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(){}}const ji={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Wi={};function Yi(t,e,i,s,r,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,i)=>{if(i){const s=e.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach((e=>{t[e]=(t[e]||0)+s.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(s,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(r,8e6))||!!d&&x(h)&&Object.keys(d).some((t=>parseInt(t)>h))}function zi(t,e,i){const s=t.videoCodec,r=t.audioCodec;if(!s||!r||!i)return Promise.resolve(ji);const n={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=s.split(",").map((t=>({type:"media-source",video:I(I({},n),{},{contentType:Ee(t,"video")})})));return r&&t.audioGroups&&t.audioGroups.forEach((t=>{var i;t&&(null==(i=e.groups[t])||i.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",i=parseFloat(t);x(i)&&i>2&&o.push.apply(o,r.split(",").map((t=>({type:"media-source",audio:{contentType:Ee(t,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((t=>{const e=function(t){const{audio:e,video:i}=t,s=i||e;if(s){const t=s.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${t}_${Math.ceil(i.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Wi[e]||(Wi[e]=i.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:o,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:o,decodingInfoResults:[],error:t})))}function qi(t,e){let i=!1,s=[];return t&&(i="SDR"!==t,s=[t]),e&&(s=e.allowedVideoRanges||di.slice(0),i=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s=i?s.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:i,allowedVideoRanges:s}}function Xi(t,e){V.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Qi(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let s=0;s-1===s.indexOf(t)))}(o,e.characteristics))&&(void 0===i||i(t,e))}function Zi(t,e){const{audioCodec:i,channels:s}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function ts(t,e,i){for(let s=e;s;s--)if(i(t[s]))return s;for(let s=e+1;s1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var is="NOT_LOADED",ss="APPENDING",rs="PARTIAL",ns="OK";class as{constructor(t){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=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(F.BUFFER_APPENDED,this.onBufferAppended,this),t.on(F.FRAG_BUFFERED,this.onFragBuffered,this),t.on(F.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(F.BUFFER_APPENDED,this.onBufferAppended,this),t.off(F.FRAG_BUFFERED,this.onFragBuffered,this),t.off(F.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const s=i[e];if(!s)break;const r=s.end;if(s.start<=t&&null!==r&&t<=r)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:i}=this,s=Object.keys(i);for(let r=s.length;r--;){const n=i[s[r]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,s){this.timeRanges&&(this.timeRanges[t]=e);const r=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach((s=>{const n=this.fragments[s];if(!n)return;if(r>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===i&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some((t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(n.body),i}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s}=t;if(!e||"initSegment"===i.sn)return;const r=ls(i),n=this.fragments[r];if(!n||n.buffered&&i.gap)return;const a=!i.relurl;if(Object.keys(e).forEach((t=>{const r=i.elementaryStreams[t];if(!r)return;const o=e[t],l=a||!0===r.partial;n.range[t]=this.getBufferedTimes(i,s,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),os(n)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(n.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const i=ls(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t=e&&o<=i){r.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(ne){const e=Math.max(n,s.start(t)),i=Math.min(a,s.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&os(h)&&(i=h.body.start-a,s=h.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),n<=e&&(r=h.body,n=e)))})),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||os(e))}getState(t){const e=ls(t),i=this.fragments[e];return i?i.buffered?os(i)?rs:ns:ss:is}isTimeBuffered(t,e,i){let s,r;for(let n=0;n=s&&e<=r)return!0;if(e<=s)return!1}return!1}onFragLoaded(t,e){const{frag:i,part:s}=e;if("initSegment"===i.sn||i.bitrateTest)return;const r=s?null:e,n=ls(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r}=e;if("initSegment"===i.sn)return;const n=i.type;if(s){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(s)}this.timeRanges=r,Object.keys(r).forEach((t=>{const e=r[t];this.detectEvictedFragments(t,e,n,s)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ls(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.startt&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(t){const e=ls(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=i.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function os(t){var e,i,s;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(i=t.range.audio)?void 0:i.partial)||(null==(s=t.range.audiovideo)?void 0:s.partial))}function ls(t){return`${t.type}_${t.level}_${t.sn}`}const hs={length:0,start:()=>0,end:()=>0};class ds{static isBuffered(t,e){try{if(t){const i=ds.getBuffered(t);for(let t=0;t=i.start(t)&&e<=i.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,i){try{if(t){const s=ds.getBuffered(t),r=[];let n;for(n=0;nn&&(s[r-1].end=t[e].end):s.push(t[e])}else s.push(t[e])}else s=t;let r,n=0,a=e,o=e;for(let t=0;t=l&&ei.startCC||t&&t.cc{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(Ts(t));t.gap=!1}const l=this.loader=t.loader=r?new r(s):new n(s),h=Es(t),d=Ii(s.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:vs};t.stats=l.stats,l.load(h,c,{onSuccess:(e,i,s,r)=>{this.resetLoader(t,l);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,s,r,n)=>{this.resetLoader(t,l),o(new Ss({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:I({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,i,s)=>{this.resetLoader(t,l),o(new Ss({type:N.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,l),o(new Ss({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:s,stats:e}))},onProgress:(i,s,r,n)=>{e&&e({frag:t,part:null,payload:r,networkDetails:n})}})}))}loadPart(t,e,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Ts(t,e));const l=this.loader=t.loader=r?new r(s):new n(s),h=Es(t,e),d=Ii(s.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:vs};e.stats=l.stats,l.load(h,c,{onSuccess:(s,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:s.data,networkDetails:o};i(h),a(h)},onError:(i,s,r,n)=>{this.resetLoader(t,l),o(new Ss({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:I({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:n}))},onAbort:(i,s,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new Ss({type:N.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(t,l),o(new Ss({type:N.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:i}))}})}))}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Es(t,e=null){const i=e||t,s={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(x(r)&&x(n)){var a;let e=r,i=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-r;t%16&&(i=n+(16-t%16)),0!==r&&(s.resetIV=!0,e=r-16)}s.rangeStart=e,s.rangeEnd=i}return s}function Ts(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:N.MEDIA_ERROR,details:U.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new Ss(s)}class Ss extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class bs{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class As{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Ls{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_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s{if(!s)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new bs(s,new Uint8Array(i)).decrypt(t.buffer,e)})).catch((s=>(V.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,i))))}onWebCryptoError(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=yt(t,0,i),this.remainderData=yt(t,i)),e}logOnce(t){this.logEnabled&&(V.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ks=function(t){let e="";const i=t.length;for(let s=0;sa.end){const t=n>r;(n{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const i=this.state;this.fragContextChanged(t)?(i===Ds||!this.fragCurrent&&i===xs)&&(this.fragmentTracker.removeFragment(t),this.state=_s):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(F.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==Cs&&this.state!==Fs&&(this.warn(e),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===ss){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength);this.reduceMaxBufferLength(r)&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===rs&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(F.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:i}=this,{payload:s}=e,r=t.decryptdata;if(s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer).catch((e=>{throw (i.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}), e)})).then((s=>{const r=self.performance.now();return i.trigger(F.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:n,tdecrypt:r}}),e.payload=s,this.completeInitSegmentLoad(e)}));}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==Cs&&this.state!==Fs&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state=_s,t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var i,s,r,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===Ve?"level":"track"} ${t.level} (frag:[${(null!=(i=t.startPTS)?i:NaN).toFixed(3)}-${(null!=(s=t.endPTS)?s:NaN).toFixed(3)}] > buffer:${a?ks(ds.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==je){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=_s)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=_s,a&&(!this.loadedmetadata&&t.type==Ve&&a.buffered.length&&(null==(r=this.fragCurrent)?void 0:r.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:r}=t,n=!r||0===r.length||r.some((t=>!t)),a=new cs(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var r;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=Is,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(F.KEY_LOADED,t),this.state===Is&&(this.state=_s),t})),this.hls.trigger(F.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const r=n.partList;if(r&&s){i>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,i);if(o>-1){const l=r[o];let h;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${r.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Ds,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,l,e,s))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,s).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(F.FRAG_LOADING,{frag:t,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),x(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Ds;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,s))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?s:void 0),a]).then((([t])=>(!o&&t&&s&&s(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(F.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,i,s){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,s).then((s=>{o[e.index]=s;const n=s.part;this.hls.trigger(F.FRAG_LOADED,s);const a=Ai(i,t.sn,e.index+1)||Li(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===U.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(F.ERROR,e)}else this.hls.trigger(F.ERROR,{type:N.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==xs)return void(this.fragCurrent||this.state===Cs||this.state===Fs||(this.state=_s));const{frag:i,part:s,level:r}=e,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n),this.updateLevelTiming(i,s,r,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${r} of level ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=n>-1?Ai(a,r,n):null,l=o?o.fragment:function(t,e,i){if(null==t||!t.details)return null;const s=t.details;let r=s.fragments[e-s.startSN];return r||(r=s.fragmentHint,r&&r.sn===e?r:en&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const i=this.getLoadPosition();return x(i)?this.getFwdBufferInfoAtPos(t,i,e):null}getFwdBufferInfoAtPos(t,e,i){const{config:{maxBufferHole:s}}=this,r=ds.bufferInfo(t,e,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&r.nextStart=i&&(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0)}getAppendedFrag(t,e=Ve){const i=this.fragmentTracker.getAppendedFrag(t,Ve);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start;let a;if(e.live){const o=r.initialLiveManifestSize;if(se}getNextFragmentLoopLoading(t,e,i,s,r){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&i.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(null!==e&&i.len+e.len>=r)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let a=0,o=t.length;a-1&&ii.start&&i.loaded}getInitialLiveFragment(t,e){const i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!x(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;i=i||0;for(let s=0;s=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=function(t,e){return wi(t,(t=>t.cce?-1:0))}(e,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(s=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,l=s.maxFragLookUpTolerance,h=i.partList,d=!!(s.lowLatencyMode&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),te-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-i.startSN,e=this.fragmentTracker.getState(c);if((e===ns||e===rs&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn)){if(r&&c.level===r.level){const e=n[t+1];c=c.sn=n-e.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r${t.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${s}`),n}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;if(i ${null==(s=this.fragCurrent)?void 0:s.url}`);const r=e.details===U.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===Ui&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const s=_i(l,o);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${s}ms`),n.resolved=!0,this.retryDate=self.performance.now()+s,this.state=ws}else if(l&&n){if(this.resetFragmentErrors(t),!(o.5;s&&this.reduceMaxBufferLength(i.len);const r=!s;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${e} buffer`),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(t){t===Ke&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Cs&&(this.state=_s)}afterBufferFlushed(t,e,i){if(!t)return;const s=ds.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===Os&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=_s}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){var r;const n=i.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,r)=>{const a=t.elementaryStreams[r];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${o})`),e||!1;const l=s?0:Ei(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(F.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:r,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(r=this.transmuxer)?void 0:r.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Ms,this.hls.trigger(F.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class Bs{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let s=0;for(let e=0;e0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ti,duration:Number.POSITIVE_INFINITY});r{if(x(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};function Ks(t,e){return 255===t[e]&&240==(246&t[e+1])}function js(t,e){return 1&t[e+1]?7:9}function Ws(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ys(t,e){return e+1=t.length)return!1;const s=Ws(t,e);if(s<=i)return!1;const r=e+s;return r===t.length||Ys(t,r)}return!1}function qs(t,e,i,s,r){if(!t.samplerate){const n=function(t,e,i,s){let r,n,a,o;const l=navigator.userAgent.toLowerCase(),h=s,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=1+((192&e[i+2])>>>6);const c=(60&e[i+2])>>>2;if(!(c>d.length-1))return a=(1&e[i+2])<<2,a|=(192&e[i+3])>>>6,V.log(`manifest codec:${s}, ADTS type:${r}, samplingIndex:${c}`),/firefox/i.test(l)?c>=6?(r=5,o=new Array(4),n=c-3):(r=2,o=new Array(2),n=c):-1!==l.indexOf("android")?(r=2,o=new Array(2),n=c):(r=5,o=new Array(4),s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&c>=6?n=c-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(c>=6&&1===a||/vivaldi/i.test(l))||!s&&1===a)&&(r=2,o=new Array(2)),n=c)),o[0]=r<<3,o[0]|=(14&c)>>1,o[1]|=(1&c)<<7,o[1]|=a<<3,5===r&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[c],channelCount:a,codec:"mp4a.40."+r,manifestCodec:h};{const e=new Error(`invalid ADTS sampling index:${c}`);t.emit(F.ERROR,F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,i,s,r);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,V.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Xs(t){return 9216e4/t}function Qs(t,e,i,s,r){const n=s+r*Xs(t.samplerate),a=function(t,e){const i=js(t,e);if(e+i<=t.length){const s=Ws(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Js=null;const Zs=[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],tr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],er=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ir=[0,1,1,4];function sr(t,e,i,s,r){if(i+24>e.length)return;const n=rr(e,i);if(n&&i+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function rr(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Zs[14*(3===i?3-s:3===s?3:4)+r-1],h=tr[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,c=er[i][s],u=ir[s],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Js){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Js=t?parseInt(t[1]):0}return!!Js&&Js<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function nr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function ar(t,e){return e+1{let i=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<>l,i=i?i<e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;const h=e[i+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[i+6]<<8|e[i+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=s+r*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}class ur{constructor(){this.VideoSample=null}createVideoSample(t,e,i,s){return{key:t,frame:!1,pts:e,dts:i,units:[],debug:s,length:0}}getLastNalUnit(t){var e;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,s=i.length;if(!s)return void e.dropped++;{const e=i[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&V.log(t.pts+"/"+t.dts+":"+t.debug)}}class fr{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&V.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,i=8,s=8;for(let r=0;r{var n;switch(s.type){case 1:{let e=!1;a=!0;const r=s.data;if(l&&r.length>4){const t=new fr(r).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,re(s.data,1,i.pts,e.samples);break;case 7:{var d,c;a=!0,l=!0;const e=s.data,i=new fr(e).readSPS();if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(d=t.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e],t.duration=r;const s=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[s.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+s.type+" ")}if(o&&a){o.units.push(s)}})),s&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const i=e.byteLength;let s=t.naluState||0;const r=s,n=[];let a,o,l,h=0,d=-1,c=0;for(-1===s&&(d=0,c=31&e[0],s=0,h=1);h=0){const t={data:e.subarray(d,o),type:c};n.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(r&&h<=4-r&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-r)),o>0&&(i.data=ee(i.data,e.subarray(0,o)),i.state=0))}h=0&&s>=0){const t={data:e.subarray(d,i),type:c,state:s};n.push(t)}if(0===n.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=ee(i.data,e))}return t.naluState=s,n}}class mr{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Rs(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}))}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let s=0;for(let e=32;e{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}))}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void s();const r=t[e].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,s,n),this.decrypter.isSync())))return}}}}const pr=188;class vr{constructor(t,e,i){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._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.videoParser=new gr}static probe(t){const e=vr.syncOffset(t);return e>0&&V.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let i=Math.min(940,e-pr)+1,s=0;for(;s1&&(0===n&&a>2||o+pr>i))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:$t[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vr.createTrack("video"),this._audioTrack=vr.createTrack("audio",s),this._id3Track=vr.createTrack("id3"),this._txtTrack=vr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,s=!1){let r;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=ee(this.remainderData,t)).length,this.remainderData=null),y>4>1){if(T=e+5+t[e+4],T===e+pr)continue}else T=e+4;switch(y){case h:s&&(d&&(r=br(d))&&this.videoParser.parseAVCPES(n,l,r,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(T,e+pr)),d.size+=e+pr-T);break;case c:if(s){if(f&&(r=br(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+pr)),f.size+=e+pr-T);break;case u:s&&(g&&(r=br(g))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+pr)),g.size+=e+pr-T);break;case 0:s&&(T+=t[T]+1),v=this._pmtId=Er(t,T);break;case v:{s&&(T+=t[T]+1);const r=Tr(t,T,this.typeSupported,i);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(V.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;if(T>0){const t=new Error(`Found ${T} TS packet/s that do not start with 0x47`);this.observer.emit(F.ERROR,F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:r}=t,n=i.pesData,a=e.pesData,o=s.pesData;let l;if(n&&(l=br(n))?(this.videoParser.parseAVCPES(i,r,l,!0,this._duration),i.pesData=null):i.pesData=n,a&&(l=br(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&V.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=br(o))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new mr(this.observer,this.config,e);return this.decrypt(s,r)}decrypt(t,e){return new Promise((i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,(()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,(()=>{i(t)})):i(t)})):r.samples&&e.decryptAvcSamples(r.samples,0,0,(()=>{i(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let i=0;const s=this.aacOverFlow;let r,n,a,o=e.data;if(s){this.aacOverFlow=null;const e=s.missing,r=s.sample.unit.byteLength;if(-1===e)o=ee(s.sample.unit,o);else{const n=r-e;s.sample.unit.set(o.subarray(0,e),n),t.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void V.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=P({},e,{type:this._videoTrack?ii:ti,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function yr(t,e){return((31&t[e+1])<<8)+t[e+2]}function Er(t,e){return(31&t[e+10])<<8|t[e+11]}function Tr(t,e,i,s){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e0){let s=e+5,o=a;for(;o>2;){if(106===t[s])!0!==i.ac3?V.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=n,r.segmentAudioCodec="ac3");const e=t[s+1]+2;s+=e,o-=e}}break;case 194:case 135:V.warn("Unsupported EC-3 in M2TS found");break;case 36:V.warn("Unsupported HEVC in M2TS found")}e+=a+5}return r}function Sr(t){V.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function br(t){let e,i,s,r,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=ee(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(i=(e[4]<<8)+e[5],i&&i>t.size-6)return null;const l=e[7];192&l&&(r=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,r-n>54e5&&(V.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),s=e[8];let h=s+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,i=o.length;ti){h-=i;continue}e=e.subarray(h),i-=h,h=0}d.set(e,a),a+=i}return i&&(i-=s+3),{data:d,pts:r,dts:n,len:i}}return null}class Ar{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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(6===e)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])}else{if(1===e)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(2===e)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(3===e)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])}}}const Lr=Math.pow(2,32)-1;class Rr{static init(){let t;for(t in (Rr.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]}, Rr.types))Rr.types.hasOwnProperty(t)&&(Rr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]),i=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]);Rr.HDLR_TYPES={video:e,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Rr.STTS=Rr.STSC=Rr.STCO=r,Rr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Rr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Rr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Rr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Rr.FTYP=Rr.box(Rr.types.ftyp,n,o,n,a),Rr.DINF=Rr.box(Rr.types.dinf,Rr.box(Rr.types.dref,s))}static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),s=0,i=8;s>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(t){return Rr.box(Rr.types.mdia,Rr.mdhd(t.timescale,t.duration),Rr.hdlr(t.type),Rr.minf(t))}static mfhd(t){return Rr.box(Rr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Rr.box(Rr.types.minf,Rr.box(Rr.types.smhd,Rr.SMHD),Rr.DINF,Rr.stbl(t)):Rr.box(Rr.types.minf,Rr.box(Rr.types.vmhd,Rr.VMHD),Rr.DINF,Rr.stbl(t))}static moof(t,e,i){return Rr.box(Rr.types.moof,Rr.mfhd(t),Rr.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Rr.trak(t[e]);return Rr.box.apply(null,[Rr.types.moov,Rr.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(Rr.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Rr.trex(t[e]);return Rr.box.apply(null,[Rr.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Lr+1)),s=Math.floor(e%(Lr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,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 Rr.box(Rr.types.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(e=0;e>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Rr.box(Rr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return Rr.box(Rr.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,o>>8&255,255&o,l>>8&255,255&l,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,Rr.box(Rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Rr.box(Rr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Rr.box(Rr.types.mp4a,Rr.audioStsd(t),Rr.box(Rr.types.esds,Rr.esds(t)))}static mp3(t){return Rr.box(Rr.types[".mp3"],Rr.audioStsd(t))}static ac3(t){return Rr.box(Rr.types["ac-3"],Rr.audioStsd(t),Rr.box(Rr.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?Rr.box(Rr.types.stsd,Rr.STSD,Rr.mp3(t)):"ac3"===t.segmentCodec?Rr.box(Rr.types.stsd,Rr.STSD,Rr.ac3(t)):Rr.box(Rr.types.stsd,Rr.STSD,Rr.mp4a(t)):Rr.box(Rr.types.stsd,Rr.STSD,Rr.avc1(t))}static tkhd(t){const e=t.id,i=t.duration*t.timescale,s=t.width,r=t.height,n=Math.floor(i/(Lr+1)),a=Math.floor(i%(Lr+1));return Rr.box(Rr.types.tkhd,new Uint8Array([1,0,0,7,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,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const i=Rr.sdtp(t),s=t.id,r=Math.floor(e/(Lr+1)),n=Math.floor(e%(Lr+1));return Rr.box(Rr.types.traf,Rr.box(Rr.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Rr.box(Rr.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Rr.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Rr.box(Rr.types.trak,Rr.tkhd(t),Rr.mdia(t))}static trex(t){const e=t.id;return Rr.box(Rr.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Rr.box(Rr.types.trun,n)}static initSegment(t){Rr.types||Rr.init();const e=Rr.moov(t);return ee(Rr.FTYP,e)}}Rr.types=void 0,Rr.HDLR_TYPES=void 0,Rr.STTS=void 0,Rr.STSC=void 0,Rr.STCO=void 0,Rr.STSZ=void 0,Rr.VMHD=void 0,Rr.SMHD=void 0,Rr.STSD=void 0,Rr.FTYP=void 0,Rr.DINF=void 0;function kr(t,e,i=1,s=!1){const r=t*e*i;return s?Math.round(r):r}function Cr(t,e=!1){return kr(t,1e3,1/9e4,e)}let _r,Ir=null,Dr=null;class wr{constructor(t,e,i,s=""){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.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Ir){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ir=t?parseInt(t[1]):0}if(null===Dr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Dr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){V.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){V.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){V.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t.reduce(((t,i)=>{const s=i.pts-t;return s<-4294967296?(e=!0,Pr(t,i.pts)):s>0?t:i.pts}),t[0].pts);return e&&V.debug("PTS rollover detected"),i}remux(t,e,i,s,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,b,A,L;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(b=t.pixelRatio)?void 0:b[0])&&(null==(A=e.pixelRatio)?void 0:A[1])===(null==(L=t.pixelRatio)?void 0:L[1])||this.resetInitSegment()}else d=this.generateIS(t,e,r,n);const i=this.isVideoContiguous;let s,a=-1;if(T&&(a=function(t){for(let e=0;e0){V.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,s=m}else-1===a&&(V.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const i=this.getVideoStartPts(e.samples),s=(Pr(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(E){if(t.samplerate||(V.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,r,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===Ke?m:void 0),T){const s=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(V.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,i,s)}}else T&&(l=this.remuxVideo(e,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=xr(i,r,this._initPTS,this._initDTS)),s.samples.length&&(c=Mr(s,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,i,s){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||s,f="audio/mp4";if(u&&(h=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Rr.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=r[0].pts-Math.round(c*i))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Rr.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*i);d=Math.min(d,Pr(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,i,s){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let h,d,c=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||null===c){const t=e*r,s=n[0].pts-Pr(n[0].dts,n[0].pts);Ir&&null!==c&&Math.abs(t-s-c)<15e3?i=!0:c=t-s}const v=l.baseTime*r/l.timescale;for(let t=0;t0?t-1:t].dts&&(p=!0)}p&&n.sort((function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s})),h=n[0].dts,d=n[n.length-1].dts;const y=d-h,E=y?Math.round(y/(o-1)):f||t.inputTimeScale/30;if(i){const t=h-c,i=t>E,s=t<-1;if((i||s)&&(i?V.warn(`AVC: ${Cr(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):V.warn(`AVC: ${Cr(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||c>=n[0].pts||Ir)){h=c;const e=n[0].pts-t;if(i)n[0].dts=h,n[0].pts=e;else for(let i=0;ie);i++)n[i].dts-=t,n[i].pts-=t;V.log(`Video: Initial PTS/DTS adjusted: ${Cr(e,!0)}/${Cr(h,!0)}, delta: ${Cr(t,!0)} ms`)}}h=Math.max(0,h);let T=0,S=0,b=h;for(let t=0;t0?e.dts-n[t-1].dts:E;if(l=t>0?e.pts-n[t-1].pts:E,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(i.maxBufferHole*r),n=(s?g+s*r:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:k=!0,V.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(e.pts-e.dts);C=Math.min(C,f),I=Math.max(I,f),_=Math.min(_,l),D=Math.max(D,l),a.push(new Or(e.key,f,h,d))}if(a.length)if(Ir){if(Ir<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Dr&&D-_0&&(s&&Math.abs(p-m)<9e3||Math.abs(Pr(f[0].pts-v,p)-m)<20*l),f.forEach((function(t){t.pts=Pr(t.pts-v,p)})),!i||m<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;m=0===r?0:s&&!u?Math.max(0,p):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,s=m;i=e*l&&h<1e4&&u){let e=Math.round(o/l);s=a-e*l,s<0&&(e--,s+=l),0===i&&(this.nextAudioPts=m=s),V.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(s/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;S+=g;try{y=new Uint8Array(S)}catch(t){return void this.observer.emit(F.ERROR,F.ERROR,{type:N.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(y.buffer).setUint32(0,S),y.set(Rr.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,c.push(new Or(!0,o,l,0)),T=n}const A=c.length;if(!A)return;const L=c[c.length-1];this.nextAudioPts=m=T+a*L.duration;const R=d?new Uint8Array(0):Rr.moof(t.sequenceNumber++,E/a,P({},t,{samples:c}));t.samples=[];const k=E/n,C=m/n,_={data1:R,data2:y,startPTS:k,endPTS:C,startDTS:k,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,_}remuxEmptyAudio(t,e,i,s){const r=t.inputTimeScale,n=r/(t.samplerate?t.samplerate:r),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:s.startDTS*r)+l,d=s.endDTS*r+l,c=1024*n,u=Math.ceil((d-h)/c),f=Ar.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(V.warn("[mp4-remuxer]: remux empty Audio"),!f)return void V.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t4294967296;)t+=i;return t}function xr(t,e,i,s){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;at.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}class Or{constructor(t,e,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=s,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Fr(t,e){const i=null==t?void 0:t.codec;if(i&&i.length>4)return i;if(e===X){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Le(i,!1)}const t="mp4a.40.5";return V.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${t}"`),t}return V.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{_r=self.performance.now.bind(self.performance)}catch(t){V.debug("Unable to use Performance API on this environment"),_r=null==at?void 0:at.Date.now}const Nr=[{demux:class{constructor(t,e){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=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=Gs("video",1),n=this.audioTrack=Gs("audio",1),a=this.txtTrack=Gs("text",1);if(this.id3Track=Gs("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=zt(t);if(o.video){const{id:t,timescale:e,codec:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=$t.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=s>1?i+s:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ee(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Wt(t,["moof"]);if(i.length<2)return e.remainder=t,e;const s=i[i.length-1];return e.valid=yt(t,0,s.byteOffset-8),e.remainder=yt(t,s.byteOffset-8),e}(i);this.remainderData=e.remainder,s.samples=e.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,e);return r.samples=ie(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=ie(t,e),{videoTrack:e,audioTrack:Gs(),id3Track:s,textTrack:Gs()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=Wt(t.samples,["emsg"]);s&&s.forEach((t=>{const s=function(t){const e=t[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==Bt(t.subarray(h,h+1));)i+=Bt(t.subarray(h,h+1)),h+=1;for(i+=Bt(t.subarray(h,h+1)),h+=1;"\0"!==Bt(t.subarray(h,h+1));)s+=Bt(t.subarray(h,h+1)),h+=1;s+=Bt(t.subarray(h,h+1)),h+=1,r=Ht(t,12),n=Ht(t,16),o=Ht(t,20),l=Ht(t,24),h=28}else if(1===e){h+=4,r=Ht(t,h),h+=4;const e=Ht(t,h);h+=4;const n=Ht(t,h);for(h+=4,a=2**32*e+n,M(a)||(a=Number.MAX_SAFE_INTEGER,V.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ht(t,h),h+=4,l=Ht(t,h),h+=4;"\0"!==Bt(t.subarray(h,h+1));)i+=Bt(t.subarray(h,h+1)),h+=1;for(i+=Bt(t.subarray(h,h+1)),h+=1;"\0"!==Bt(t.subarray(h,h+1));)s+=Bt(t.subarray(h,h+1)),h+=1;s+=Bt(t.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(lr.test(s.schemeIdUri)){const t=x(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale;let r=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:ii,duration:r})}}))}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{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(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(function(t,e){if(!t||!e)return t;const i=e.keyId;i&&e.isCommonEncryption&&Wt(t,["moov","trak"]).forEach((t=>{const e=Wt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let s=Wt(e,["enca"]);const r=s.length>0;r||(s=Wt(e,["encv"])),s.forEach((t=>{Wt(r?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=Zt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(V.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Ft(t)} -> ${Ft(i)}`),e.set(i,8))}}))}))}));return t}(t,s)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const s=this.initData=zt(t);s.audio&&(e=Fr(s.audio,X)),s.video&&(i=Fr(s.video,Q));const r={};s.audio&&s.video?r.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:s.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:s.video?r.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:V.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};x(h)||(h=this.lastEndTime=r||0);const c=e.samples;if(null==c||!c.length)return d;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return V.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){let i=0,s=0,r=0;const n=Wt(t,["moof","traf"]);for(let t=0;tt+e.info.duration||0),0);i=Math.max(i,t+n.earliestPresentationTime/n.timescale),s=i-e}}if(s&&x(s))return s}return s||r}(c,f),m=function(t,e){return Wt(e,["moof","traf"]).reduce(((e,i)=>{const s=Wt(i,["tfdt"])[0],r=s[0],n=Wt(i,["tfhd"]).reduce(((e,i)=>{const n=Ht(i,4),a=t[n];if(a){let t=Ht(s,4);if(1===r){if(t===Nt)return V.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Nt+1,t+=Ht(s,8)}const i=t/(a.timescale||9e4);if(x(i)&&(null===e||ir}(l,p,r,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-r,l&&1===l.timescale&&V.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const v=t?p-l.baseTime/l.timescale:h,y=v+g;!function(t,e,i){Wt(e,["moof","traf"]).forEach((e=>{Wt(e,["tfhd"]).forEach((s=>{const r=Ht(s,4),n=t[r];if(!n)return;const a=n.timescale||9e4;Wt(e,["tfdt"]).forEach((t=>{const e=t[0],s=i*a;if(s){let i=Ht(t,4);if(0===e)i-=s,i=Math.max(i,0),jt(t,4,i);else{i*=Math.pow(2,32),i+=Ht(t,8),i-=s,i=Math.max(i,0);const e=Math.floor(i/(Nt+1)),r=Math.floor(i%(Nt+1));jt(t,4,e),jt(t,8,r)}}}))}))}))}(f,c,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(V.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const E=!!f.audio,T=!!f.video;let S="";E&&(S+="audio"),T&&(S+="video");const b={data1:c,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:E,hasVideo:T,nb:1,dropped:0};return d.audio="audio"===b.type?b:void 0,d.video="audio"!==b.type?b:void 0,d.initSegment=u,d.id3=xr(i,r,l,l),s.samples.length&&(d.text=Mr(s,r,l)),d}}},{demux:vr,remux:wr},{demux:class extends Hs{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=St(t,0);let i=(null==e?void 0:e.length)||0;if(or(t,i))return!1;for(let e=t.length;i0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(n,e);if(E&&"AES-128"===E.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer).then((t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer);if(i.part>-1&&(e=t.flush()),!e)return r.executeEnd=_r(),$r(i);n=new Uint8Array(e)}}const T=this.needsProbing(h,d);if(T){const t=this.configureTransmuxer(n);if(t)return V.warn(`[transmuxer] ${t.message}`),this.observer.emit(F.ERROR,F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=_r(),$r(i)}(h||d||f||T)&&this.resetInitSegment(y,g,m,v,e),(h||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,u,c,i),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=_r(),S}flush(t){const e=t.transmuxing;e.executeStart=_r();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return r.then((()=>this.flush(t)));const n=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=_r(),[$r(t)];const h=o.flush(a);return Br(h)?h.then((e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),n)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;V.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=_r()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,s),a.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,s,r):this.transmuxUnencrypted(t,i,s,r),n}transmuxUnencrypted(t,e,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer.demuxSampleAes(t,e,i).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id),chunkMeta:r})))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s,vendor:r}=this;let n;for(let e=0,i=Nr.length;e({remuxResult:{},chunkMeta:t});function Br(t){return"then"in t&&t.then instanceof Function}class Gr{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class Hr{constructor(t,e,i,s,r,n){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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}var Vr={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r{(e=e||{}).frag=this.frag,e.id=this.id,t===F.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new Kr,this.observer.on(F.FRAG_DECRYPTED,n),this.observer.on(F.ERROR,n);const a=me(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')},l=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(V.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(r.workerPath)):(V.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){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}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const i=new Error(`${t.message} (${t.filename}:${t.lineno})`);r.enableWorker=!1,V.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(F.ERROR,{type:N.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},t.postMessage({cmd:"init",typeSupported:o,vendor:l,id:e,config:JSON.stringify(r)})}catch(t){V.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Ur(this.observer,o,r,l,e)}return}}this.transmuxer=new Ur(this.observer,o,r,l,e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:r.start,g=r.decryptdata,m=this.frag,p=!(m&&r.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===E||T&&E<=0)),b=self.performance.now();(v||y||0===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!E&&S||(n.stats.parsing.start=b);const A=!(m&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),L=new Hr(p,S,o,v,f,A);if(!S||p||A){V.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${A}`);const t=new Gr(i,s,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:L},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,g,l,L);Br(e)?(u.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let i=e.flush(t);Br(i)||e.async?(Br(i)||(i=Promise.resolve(i)),i.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(i,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data,i=this.hls;switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":V[e.data.logType]&&V[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Wr(t,e){if(t.length!==e.length)return!1;for(let i=0;it[i]!==e[i]))}function zr(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class qr{constructor(t){this.buffered=void 0;const e=(e,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}class Xr{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,i){const s=this.queues[e];s.push(t),1!==s.length||i||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const i=new Promise((t=>{e=t})),s={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,t),i}executeNext(t){const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){V.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),i.onError(e);const s=this.buffers[t];null!=s&&s.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Qr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Jr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}const Zr={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},tn=function(t){let e=t;return Zr.hasOwnProperty(t)&&(e=Zr[t]),String.fromCharCode(e)},en=15,sn=100,rn={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},nn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},an={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},on={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ln=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class hn{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;V.log(`${this.time} [${t}] ${i}`)}}}const dn=function(t){const e=[];for(let i=0;isn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=sn)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t=144&&this.backSpace();const e=tn(t);this.pos>=sn?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e"pacData = "+JSON.stringify(t)));let e=t.row-1;if(this.nrRollUpRows&&e"bkgData = "+JSON.stringify(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let i=0;i0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class mn{constructor(t,e,i){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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new gn(i),this.nonDisplayedMemory=new gn(i),this.lastOutputScreen=new gn(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;ee+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(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"),"MODE_TEXT"!==this.mode&&(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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}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"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class pn{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new hn;this.channels=[null,new mn(t,e,s),new mn(t+1,i,s)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){let i,s,r,n=!1;this.logger.time=t;for(let t=0;t ("+dn([s,r])+")"),i=this.parseCmd(s,r),i||(i=this.parseMidrow(s,r)),i||(i=this.parsePAC(s,r)),i||(i=this.parseBackgroundAttributes(s,r)),!i&&(n=this.parseChars(s,r),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||n||this.logger.log(2,"Couldn't parse cleaned data "+dn([s,r])+" orig: "+dn([e[t],e[t+1]]))}}parseCmd(t,e){const{cmdHistory:i}=this;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(yn(t,e,i))return vn(null,null,i),this.logger.log(3,"Repeated command ("+dn([t,e])+") is dropped"),!0;const s=20===t||21===t||23===t?1:2,r=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),vn(t,e,i),this.currentChannel=s,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return!!s&&(s.ccMIDROW(e),this.logger.log(3,"MIDROW ("+dn([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;const s=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(yn(t,e,s))return vn(null,null,s),!0;const r=t<=23?1:2;i=e>=64&&e<=95?1===r?rn[t]:an[t]:1===r?nn[t]:on[t];const n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(i,e)),vn(t,e,s),this.currentChannel=r,!0)}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,s.underline=!(1&~i),i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=4*Math.floor((i-16)/2),s}parseChars(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,"Special char '"+tn(t)+"' in channel "+i),s=[t]}else t>=32&&t<=127&&(s=0===e?[t]:[t,e]);if(s){const i=dn(s);this.logger.log(3,"Char codes = "+i.join(",")),vn(t,e,this.cmdHistory)}return s}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const s={};16===t||24===t?(i=Math.floor((e-32)/2),s.background=ln[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(s),vn(t,e,this.cmdHistory),!0}reset(){for(let t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Tn=function(){if(null!=at&&at.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function s(t){return i(e,t)}function r(t,...e){let i=1;for(;i100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return b},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Sn{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function bn(t){function e(t,e,i,s){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(s||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class An{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s=0&&i<=100)return this.set(t,i),!0}return!1}}function Ln(t,e,i,s){const r=s?t.split(s):[t];for(const t in r){if("string"!=typeof r[t])continue;const s=r[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const Rn=new Tn(0,0,""),kn="middle"===Rn.align?"middle":"center";function Cn(t,e,i){const s=t;function r(){const e=bn(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e;}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const s=new An;Ln(t,(function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){s.set(t,i[r].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),s.integer(t,r[0]),s.percent(t,r[0])&&s.set("snapToLines",!1),s.alt(t,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",kn,"end"]);break;case"position":r=e.split(","),s.percent(t,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",kn,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",kn,"end","left","right"])}}),/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===Rn.line&&(r=-1),e.line=r,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",kn);let n=s.get("position","auto");"auto"===n&&50===Rn.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function _n(t){return t.replace(//gi,"\n");}class In{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Sn,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=_n(t);i>>0).toString()};function xn(t,e,i){return Pn(t.toString())+Pn(e.toString())+Pn(i)}function Mn(t,e,i,s,r,n,a){const o=new In,l=xt(new Uint8Array(t)).trim().replace(Dn,"\n").split("\n"),h=[],d=e?function(t,e=1){return kr(t,9e4,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=i[s];let a=i.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(t,e,i){let s=t[e],r=t[s.prevCC];if(!r||!r.new&&s.new)return t.ccOffset=t.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=s.start-r.start,s.new=!1,s=r,r=t[s.prevCC]}t.presentationOffset=i}(i,s,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=t.endTime-t.startTime,u=Pr(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=xn(t.startTime,t.endTime,m)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(h)},l.forEach((t=>{if(m){if(wn(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach((t=>{wn(t,"LOCAL:")?u=t.slice(6):wn(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(x(e)&&x(i)&&x(s)&&x(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*s,e+=36e5*r,e}(u)/1e3}catch(t){c=t}return}""===t&&(m=!1)}o.parse(t+"\n")})),o.flush()}const On="stpp.ttml.im1t",Fn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Nn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Un={left:"start",center:"center",right:"end",start:"start",end:"end"};function $n(t,e,i,s){const r=Wt(new Uint8Array(t),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map((t=>xt(t))),a=function(t,e,i=1,s=!1){return kr(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{n.forEach((t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||r[e],t)),{}),a="preserve"!==s.getAttribute("xml:space"),o=Gn(Bn(s,"styling","style")),l=Gn(Bn(s,"layout","region")),h=Bn(s,"body","[begin]");return[].map.call(h,(t=>{const i=Hn(t,a);if(!i||!t.hasAttribute("begin"))return null;const s=jn(t.getAttribute("begin"),n),r=jn(t.getAttribute("dur"),n);let h=jn(t.getAttribute("end"),n);if(null===s)throw Kn(t);if(null===h){if(null===r)throw Kn(t);h=s+r}const d=new Tn(s-e,h-e,i);d.id=xn(d.startTime,d.endTime,d.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce(((i,n)=>{const a=Vn(e,s,n)||Vn(t,s,n)||Vn(r,s,n);return a&&(i[n]=a),i}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=Un[u];t&&(d.lineAlign=t),d.align=u}return P(d,c),d})).filter((t=>null!==t))}(t,a))))}catch(t){s(t)}}function Bn(t,e,i){const s=t.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function Gn(t){return t.reduce(((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function Hn(t,e){return [].slice.call(t.childNodes).reduce(((t,i,s)=>{var r;return "br"===i.nodeName&&s?t+"\n":null!=(r=i.childNodes)&&r.length?Hn(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent;}),"");}function Vn(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Kn(t){return new Error(`Could not parse ttml timestamp ${t}`)}function jn(t,e){if(!t)return null;let i=bn(t);return null===i&&(Fn.test(t)?i=function(t,e){const i=Fn.exec(t),s=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/e.frameRate}(t,e):Nn.test(t)&&(i=function(t,e){const i=Nn.exec(t),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}(t,e))),i}function Wn(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles";}function Yn(t,e){return!!t&&t.kind===Wn(e)&&zr(e,t)}class zn{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(F.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(F.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(F.MANIFEST_PARSED,this.onManifestParsed,this),t.on(F.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(F.BUFFER_CODECS,this.onBufferCodecs,this),t.on(F.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(F.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(F.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(F.MANIFEST_PARSED,this.onManifestParsed,this),t.off(F.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(F.BUFFER_CODECS,this.onBufferCodecs,this),t.off(F.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&x(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&V.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter(((e,i)=>this.isLevelAllowed(e)&&i<=t));return this.clientRect=null,zn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,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 t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;let s=t.length-1;const r=Math.max(e,i);for(let e=0;e=r||i.height>=r)&&(n=i,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){s=e;break}}var n,a;return s}}const qn="[eme]";class Xn{constructor(t){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=Xn.CDMCleanupPromise?[Xn.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=V.debug.bind(V,qn),this.log=V.log.bind(V,qn),this.warn=V.warn.bind(V,qn),this.error=V.error.bind(V,qn),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(F.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(F.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(F.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(F.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(F.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(F.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(F.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(F.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=e[t];if(s)return s.licenseUrl;if(t===ot.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,s=e.map((t=>t.audioCodec)).filter(i),r=e.map((t=>t.videoCodec)).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((e,i)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,s,r).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):i(e instanceof Qn?e:new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===pt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){const s=function(t,e,i,s){let r;switch(t){case ot.FAIRPLAY:r=["cenc","sinf"];break;case ot.WIDEVINE:case ot.PLAYREADY:r=["cenc"];break;case ot.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,s){return[{initDataTypes:t,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null}))),videoCapabilities:i.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null})))}]}(r,e,i,s)}(t,e,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(s)}`),n=this.requestMediaKeySystemAccess(t,s);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=i.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),s.then((i=>i?this.setMediaKeysServerCertificate(e,t,i):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Ft(t.keyId||[])}`);const s=i.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return Ft(t.keyId)}updateKeySession(t,e){var i;const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Ft((null==(i=t.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),s.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,i)=>{const s=mt(this.config),r=t.map(ut).filter((t=>!!t&&-1!==s.indexOf(t)));return this.getKeySystemSelectionPromise(r).then((({keySystem:t})=>{const s=gt(t);s?e(s):i(new Error(`Unable to find format for key-system "${t}"`))})).catch(i)}))}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),s=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${s}`);let r=this.keyIdToKeySessionPromise[i];return r||(r=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(e).then((({keySystem:i,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(i,r).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:i,mediaKeys:r,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))))),r.catch((t=>this.handleError(t)))),r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof Qn?this.hls.trigger(F.ERROR,t.data):this.hls.trigger(F.ERROR,{type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=ut(t.keyFormat),i=e?[e]:mt(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=mt(this.config)),0===t.length)throw new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:i}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===i)return;let s,r;if("sinf"===e&&this.config.drmSystems[ot.FAIRPLAY]){const t=Bt(new Uint8Array(i));try{const e=st(JSON.parse(t).sinf),i=Zt(new Uint8Array(e));if(!i)return;s=i.subarray(8,24),r=ot.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},i=new DataView(t),s=i.getUint32(0);if(t.byteLength!==s&&s>44)return null;if(1886614376!==i.getUint32(4))return null;if(e.version=i.getUint32(8)>>>24,e.version>1)return null;e.systemId=Ft(new Uint8Array(t,12,16));const r=i.getUint32(28);if(0===e.version){if(s-32this.generateRequestWithPreferredKeySession(r,e,i,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([r]).then((({keySystem:t,mediaKeys:r})=>{var a;this.throwIfDestroyed();const o=new le("ISO-23001-7",n,null!=(a=gt(t))?a:"");return o.pssh=new Uint8Array(i),o.keyId=s,this.attemptSetMediaKeys(t,r).then((()=>{this.throwIfDestroyed();const s=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:r});return this.generateRequestWithPreferredKeySession(s,e,i,"encrypted-event-no-match")}))}))),l.catch((t=>this.handleError(t)))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(s),s.then((()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===i.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,i,s){var r,n;const a=null==(r=this.config.drmSystems)||null==(n=r[t.keySystem])?void 0:n.generateRequest;if(a)try{const s=a.call(this.hls,e,i,t);if(!s)throw new Error("Invalid response from configured generateRequest filter");e=s.initDataType,i=t.decryptdata.pssh=s.initData?new Uint8Array(s.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${s}": ${l} (init data type: ${e} length: ${i?i.byteLength:null})`);const h=new Kr,d=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:s,message:r}=e;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(t,r).catch((t=>{this.handleError(t),h.emit("error",t)})):"license-release"===s?t.keySystem===ot.FAIRPLAY&&(this.updateKeySession(t,nt("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${s}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const i=t.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const u=new Promise(((t,e)=>{h.on("error",e),h.on("keyStatus",(i=>{i.startsWith("usable")?t():"output-restricted"===i?e(new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?e(new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return t.mediaKeysSession.generateRequest(e,i).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>u)).catch((e=>{throw (h.removeAllListeners(), this.removeSession(t), e)})).then((()=>(h.removeAllListeners(),t)));}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,i)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${Ft("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Ft(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),s=this.getServerCertificateUrl(t);return s?(this.log(`Fetching server certificate for "${t}"`),new Promise(((r,n)=>{const a={responseType:"arraybuffer",url:s},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,s)=>{r(t.data)},onError:(e,i,r,o)=>{n(new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:I({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${s}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,r)=>{n(new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${s})`))},onAbort:(t,e,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise(((s,r)=>{t.setServerCertificate(i).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${e}"`),s(t)})).catch((t=>{r(new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,s=r.length;i in key message");return nt(atob(l))}setupLicenseXHR(t,e,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,i,s)})).catch((n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,i,s)})).then((i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||s}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise(((s,r)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,a,n,t)}catch(t){this.error(t)}s(e)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Qn({type:N.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(s,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:i})=>{t.keySystem==ot.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},le.clearKeyUriToKeyIdMap();const i=e.length;Xn.CDMCleanupPromise=Promise.all(e.map((t=>this.removeSession(t))).concat(null==t?void 0:t.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}`)})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(t);return s>-1&&this.mediaKeySessions.splice(s,1),e.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}Xn.CDMCleanupPromise=void 0;class Qn extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var Jn,Zn,ta;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(Jn||(Jn={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Zn||(Zn={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(ta||(ta={}));const ea={[ta.OBJECT]:["br","d","ot","tb"],[ta.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[ta.SESSION]:["cid","pr","sf","sid","st","v"],[ta.STATUS]:["bs","rtp"]};class ia{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof ia?t:new ia(t)))),this.value=t,this.params=e}}class sa{constructor(t){this.description=void 0,this.description=t}}function ra(t,e,i,s){return new Error(`failed to ${t} "${(r=e, Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r))}" as ${i}`,{cause:s});var r}const na="Bare Item";const aa=/[\x00-\x1f\x7f]+/;function oa(t,e,i){return ra("serialize",t,e,i)}function la(t){if(!1===ArrayBuffer.isView(t))throw oa(t,"Byte Sequence");return `:${(e=t, btoa(String.fromCharCode(...e)))}:`;var e}function ha(t){if(function(t){return t<-999999999999999||99999999999999912)throw oa(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}function ua(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw oa(e,"Token");return e}function fa(t){switch(typeof t){case"number":if(!x(t))throw oa(t,na);return Number.isInteger(t)?ha(t):ca(t);case"string":return function(t){if(aa.test(t))throw oa(t,"String");return `"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;}(t);case"symbol":return ua(t);case"boolean":return function(t){if("boolean"!=typeof t)throw oa(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ha(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return la(t);if(t instanceof sa)return ua(t);default:throw oa(t,na)}}function ga(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw oa(t,"Key");return t}function ma(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${ga(t)}`:`;${ga(t)}=${fa(e)}`)).join("")}function pa(t){return t instanceof ia?`${fa(t.value)}${ma(t.params)}`:fa(t)}function va(t,e={whitespace:!0}){if("object"!=typeof t)throw oa(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),s=null!=e&&e.whitespace?" ":"";return Array.from(i).map((([t,e])=>{e instanceof ia==!1&&(e=new ia(e));let i=ga(t);var s;return!0===e.value?i+=ma(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(s=e).value.map(pa).join(" ")})${ma(s.params)}`:i+=pa(e)),i})).join(`,${s}`)}const ya=t=>Math.round(t),Ea=t=>100*ya(t/100),Ta={br:ya,d:ya,bl:Ea,dl:Ea,mtp:Ea,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const i=new URL(t),s=new URL(e);if(i.origin!==s.origin)return t;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:Ea,tb:ya};function Sa(t,e){const i={};if(null==t||"object"!=typeof t)return i;const s=Object.keys(t).sort(),r=P({},Ta,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return s.forEach((s=>{if(null!=n&&n(s))return;let a=t[s];const o=r[s];o&&(a=o(a,e)),"v"===s&&1===a||"pr"==s&&1===a||(t=>"number"==typeof t?x(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(s)&&"string"==typeof a&&(a=new sa(a)),i[s]=a)})),i}function ba(t,e={}){return t?function(t,e){return va(t,e)}(Sa(t,e),P({whitespace:!1},e)):""}function Aa(t,e,i){return P(t,function(t,e={}){if(!t)return{};const i=Object.entries(t),s=Object.entries(ea).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),r=i.reduce(((t,e)=>{var i;const[r,n]=e,a=(null==(i=s.find((t=>t[1].includes(r))))?void 0:i[0])||ta.REQUEST;return null!=t[a]||(t[a]={}),t[a][r]=n,t}),{});return Object.entries(r).reduce(((t,[i,s])=>(t[i]=ba(s,e),t)),{})}(e,i))}const La=/CMCD=[^&#]+/;function Ra(t,e,i){const s=function(t,e={}){if(!t)return"";const i=ba(t,e);return`CMCD=${encodeURIComponent(i)}`}(e,i);if(!s)return t;if(La.test(t))return t.replace(La,s);const r=t.includes("?")?"&":"?";return`${t}${r}${s}`}function ka(t,e,i,s){t&&Object.keys(e).forEach((r=>{const n=t.filter((t=>t.groupId===r)).map((t=>{const n=P({},t);return n.details=void 0,n.attrs=new W(n.attrs),n.url=n.attrs.URI=Ca(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=s,n}));t.push(...n)}))}function Ca(t,e,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}const _a=/^age:\s*[\d.]+\s*$/im;class Ia{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new q,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(!this.stats.aborted)return r(i,e.url)})).catch((t=>(i.open("GET",e.url,!0),r(i,e.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(i,e,t)})).catch((t=>{this.callbacks.onError({code:i.status,text:t.message},e,i,s)})):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const e in s)t.setRequestHeader(e,s[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&x(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const s=e.status,n="text"!==e.responseType;if(s>=200&&s<300&&(n&&e.response||null!==e.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const r=n?e.response:e.responseText,a="arraybuffer"===e.responseType?r.byteLength:r.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(i,t,r,e),!this.callbacks)return;const l={url:e.responseURL,data:r,code:s};this.callbacks.onSuccess(l,i,t,e)}else{const n=r.loadPolicy.errorRetry;Di(n,i.retry,!1,{url:t.url,data:void 0,code:s})?this.retry(n):(V.error(`${s} while loading ${t.url}`),this.callbacks.onError({code:s,text:e.statusText},t,e,i))}}}loadtimeout(){var t;const e=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if(Di(e,this.stats.retry,!0))this.retry(e);else{var i;V.warn(`timeout while loading ${null==(i=this.context)?void 0:i.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=_i(t,i.retry),i.retry++,V.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&_a.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Da=/(\d+)-(\d+)\/(\d+)/;class wa{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Pa,this.controller=new self.AbortController,this.stats=new q}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(P({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),n=i.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=l&&x(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(s,t,this.response)}),e.timeout),self.fetch(this.request).then((r=>{this.response=this.loader=r;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(s,t,this.response)}),h-(o-s.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new xa(e||"fetch, bad network response",t,r)}return s.loading.first=o,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Da.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(x(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(r.headers)||s.total,n&&x(e.highWaterMark)?this.loadProgressively(r,s,t,e.highWaterMark,n):a?r.arrayBuffer():"json"===t.responseType?r.json():r.text()})).then((r=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=r[o];l&&(s.loaded=s.total=l);const h={url:a.url,data:r,code:a.status};n&&!x(e.highWaterMark)&&n(s,t,r,a),i.onSuccess(h,s,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=e&&e.code||0,n=e?e.message:null;i.onError({code:r,text:n},t,e?e.details:null,s)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const n=new Bs,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(e,i,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h=s&&r(e,i,n.flush(),t)):r(e,i,l,t),o()})).catch((()=>Promise.reject()));return o()}}function Pa(t,e){return new self.Request(t.url,e)}class xa extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Ma=/\s/,Oa={newCue(t,e,i,s){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const s=_n(h.trim()),f=xn(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,i,s),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),r.forEach((e=>Xe(t,e)))),r}},Fa=I(I({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,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:Ia,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:i}=this,{autoLevelEnabled:s,media:r}=i;if(!t||!r)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start,h=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!s||r.paused||!r.playbackRate||!r.readyState)return;const d=i.mainForwardBufferInfo;if(null===d)return;const c=this.bwEstimator.getEstimateTTFB(),u=Math.abs(r.playbackRate);if(l<=Math.max(c,o/(2*u)*1e3))return;const f=d.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),v=i.levels,y=v[t.level],E=a.total||Math.max(a.loaded,Math.round(o*y.averageBitrate/8));let T=m?l-g:l;T<1&&m&&(T=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/T:0,b=S?(E-a.loaded)/S:8*E/p+c/1e3;if(b<=f)return;const A=S?8*S:p;let L,R=Number.POSITIVE_INFINITY;for(L=t.level-1;L>h;L--){const t=v[L].maxBitrate;if(R=this.getTimeToLoadFrag(c/1e3,A,o*t,!v[L].details),R=b)return;if(R>10*o)return;i.nextLoadLevel=i.nextAutoLevel=L,m?this.bwEstimator.sample(l-Math.min(c,g),a.loaded):this.bwEstimator.sampleTTFB(l);const k=v[L].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>k&&this.resetEstimator(k),this.clearTimer(),V.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${R.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${x(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${L} @ ${0|k} bps`),i.trigger(F.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(V.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new Ki(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.FRAG_LOADING,this.onFragLoading,this),t.on(F.FRAG_LOADED,this.onFragLoaded,this),t.on(F.FRAG_BUFFERED,this.onFragBuffered,this),t.on(F.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(F.LEVEL_LOADED,this.onLevelLoaded,this),t.on(F.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(F.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(F.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.FRAG_LOADING,this.onFragLoading,this),t.off(F.FRAG_LOADED,this.onFragLoaded,this),t.off(F.FRAG_BUFFERED,this.onFragBuffered,this),t.off(F.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(F.LEVEL_LOADED,this.onLevelLoaded,this),t.off(F.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(F.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(F.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case U.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:s}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=s?s.stats:t.stats,r=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:s}=e.stats,r=s.end-s.start;x(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===Ve&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(F.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Ve||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return V.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,h,d);if(t>=0)return t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,V.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,s,l,c,h,d);if(V.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=i.levels[n],g=i.levels[i.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,s,r,n,a){var o;const l=s+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==v||null==(o=v.details)||!o.live),E=-1===m||-1===h;let T,S="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:A,videoPreference:L}=p,R=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(E){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(t,e,i,s){return t.slice(i,s+1).reduce(((t,i)=>{if(!i.codecSet)return t;const s=i.audioGroups;let r=t[i.codecSet];r||(t[i.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,i.bitrate);const n=Math.min(i.height,i.width);return r.minHeight=Math.min(r.minHeight,n),r.minFramerate=Math.min(r.minFramerate,i.frameRate),r.maxScore=Math.max(r.maxScore,i.score),r.fragmentError+=i.fragmentError,r.videoRanges[i.videoRange]=(r.videoRanges[i.videoRange]||0)+1,s&&s.forEach((t=>{if(!t)return;const i=e.groups[t];i&&(r.hasDefaultAudio=r.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((t=>{r.channels[t]=(r.channels[t]||0)+i.channels[t]})))})),t}),{})}(f,R,e,i)),r=function(t,e,i,s,r){const n=Object.keys(t),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=a&&2===parseInt(a);let h=!0,d=!1,c=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=qi(e,r);for(let e=n.length;e--;){const i=t[n[e]];h=i.channels[2]>0,c=Math.min(c,i.minHeight),u=Math.min(u,i.minFramerate),f=Math.min(f,i.minBitrate);const s=v.filter((t=>i.videoRanges[t]>0));s.length>0&&(d=!0,m=s)}c=x(c)?c:0,u=x(u)?u:0;const y=Math.max(1080,c),E=Math.max(30,u);return f=x(f)?f:i,i=Math.max(f,i),d||(e=void 0,m=[]),{codecSet:n.reduce(((e,s)=>{const r=t[s];if(s===e)return e;if(r.minBitrate>i)return Xi(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),e;if(!r.hasDefaultAudio)return Xi(s,"no renditions with default or auto-select sound found"),e;if(o&&s.indexOf(o.substring(0,4))%5!=0)return Xi(s,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!r.channels[a])return Xi(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||l)&&h&&0===r.channels[2])return Xi(s,"no renditions with stereo sound found"),e;return r.minHeight>y?(Xi(s,`min resolution of ${r.minHeight} > maximum of ${y}`),e):r.minFramerate>E?(Xi(s,`min framerate of ${r.minFramerate} > maximum of ${E}`),e):m.some((t=>r.videoRanges[t]>0))?r.maxScore=Se(e)||r.fragmentError>t[e].fragmentError)?e:(g=r.maxScore,s):(Xi(s,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),e)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}(s,S,t,A,L),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=r;T=n,S=h?a[a.length-1]:a[0],b=o,t=Math.max(t,l),V.log(`[abr] picked start tier ${JSON.stringify(r)}`)}else T=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const k=u?u.duration:c?c.duration:0,C=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let o=i;o>=e;o--){var I;const e=f[o],c=o>d;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Yi(e,R,S,b,t,A)?(e.supportedPromise=zi(e,R,i),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,s=i.indexOf(e);t.error?V.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${s} ${JSON.stringify(t)}`):t.supported||(V.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${s} ${JSON.stringify(t)}`),s>-1&&i.length>1&&(V.log(`[abr] Removing unsupported level ${s}`),this.hls.removeLevel(s)))}))):e.supportedResult=ji}if(T&&e.codecSet!==T||S&&e.videoRange!==S||c&&b>e.frameRate||!c&&b>0&&b=2*k&&0===r?f[o].averageBitrate:f[o].maxBitrate,P=this.getTimeToLoadFrag(C,D,w*L,void 0===g);if(D>=w&&(o===h||0===e.loadError&&0===e.fragmentError)&&(P<=C||!x(P)||y&&!this.bitrateTestDelay||P${o} adjustedbw(${Math.round(D)})-bitrate=${Math.round(D-w)} ttfb:${C.toFixed(1)} avgDuration:${L.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${P.toFixed(1)} firstSelection:${E} codecSet:${T} videoRange:${S} hls.loadLevel:${m}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls,s=Math.min(Math.max(t,i),e);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}},bufferController:class{constructor(t){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.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(F.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&V.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var i;this.appendSource=(i=me(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.log=V.log.bind(V,e),this.warn=V.warn.bind(V,e),this.error=V.error.bind(V,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,this.hls=null}registerListeners(){const{hls:t}=this;t.on(F.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.MANIFEST_PARSED,this.onManifestParsed,this),t.on(F.BUFFER_RESET,this.onBufferReset,this),t.on(F.BUFFER_APPENDING,this.onBufferAppending,this),t.on(F.BUFFER_CODECS,this.onBufferCodecs,this),t.on(F.BUFFER_EOS,this.onBufferEos,this),t.on(F.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(F.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(F.FRAG_PARSED,this.onFragParsed,this),t.on(F.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(F.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.MANIFEST_PARSED,this.onManifestParsed,this),t.off(F.BUFFER_RESET,this.onBufferReset,this),t.off(F.BUFFER_APPENDING,this.onBufferAppending,this),t.off(F.BUFFER_CODECS,this.onBufferCodecs,this),t.off(F.BUFFER_EOS,this.onBufferEos,this),t.off(F.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(F.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(F.FRAG_PARSED,this.onFragParsed,this),t.off(F.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Xr(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const i=this.media=e.media,s=me(this.appendSource);if(i&&s){var r;const t=this.mediaSource=new s;this.log(`created media source: ${null==(r=t.constructor)?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{i.removeAttribute("src");const s=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||s&&t instanceof s,Jr(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:i}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(t.removeAttribute("src"),this.appendSource&&Jr(t),t.load()):this.warn("media|source.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(F.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var i;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const i=this.getSourceBufferTypes().length,s=Object.keys(e);if(s.forEach((t=>{if(i){const i=this.tracks[t];if(i&&"function"==typeof i.buffer.changeType){var s;const{id:r,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=Re(i.codec,i.levelCodec),d=null==h?void 0:h.replace(Qr,"$1");let c=Re(n,a);const u=null==(s=c)?void 0:s.replace(Qr,"$1");if(c&&d!==u){"audio"===t.slice(0,5)&&(c=Le(c,this.appendSource));const e=`${o};codecs=${c}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${c}`),this.tracks[t]={buffer:i.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:r}}}}else this.pendingTracks[t]=e[t]})),i)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${s.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:i}=this,s={execute:()=>{const s=this.sourceBuffer[t];s&&(this.log(`changing ${t} sourceBuffer type to ${e}`),s.changeType(e)),i.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};i.append(s,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:i,operationQueue:s,tracks:r}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],c=self.performance.now();d.start=c;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=c),f&&0===f.start&&(f.start=c);const g=r.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,v={execute:()=>{if(d.executeStart=self.performance.now(),m){const t=this.sourceBuffer[a];if(t){const e=p-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===u.first&&(u.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,i={};for(const t in e)i[t]=ds.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(F.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:i})},onError:t=>{const e={type:N.MEDIA_ERROR,parent:o.type,details:U.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=U.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=U.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=i.config.appendErrorMaxRetry&&(e.fatal=!0)}i.trigger(F.ERROR,e)}};s.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:i}=this,s=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(F.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?i.append(s(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{i.append(s(t),t)}))}onFragParsed(t,e){const{frag:i,part:s}=e,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[J]?r.push("audiovideo"):(n[X]&&r.push("audio"),n[Q]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const t=self.performance.now();i.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:i.stats;this.hls.trigger(F.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type})}),r)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,i)=>{const s=this.sourceBuffer[i];return!s||e.type&&e.type!==i||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${i} sourceBuffer now EOS`))),t&&!(s&&!s.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.getSourceBufferTypes().length)return;const s=t.config,r=i.currentTime,n=e.levelTargetDuration,a=e.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(x(a)&&a>0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}if(x(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const t=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),e=Math.max(t,n),i=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,i)}}flushBackBuffer(t,e,i){const{details:s,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((n=>{const a=r[n];if(a){const r=ds.getBuffered(a);if(r.length>0&&i>r.start(0)){if(this.hls.trigger(F.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=s&&s.live)this.hls.trigger(F.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&r.end(r.length-1)-t<2*e)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(F.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}}))}flushFrontBuffer(t,e,i){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((r=>{const n=s[r];if(n){const s=ds.getBuffered(n),a=s.length;if(a<2)return;const o=s.start(a-1),l=s.end(a-1);if(i>o||t>=o&&t<=l)return;if(n.ended&&t-l<2*e)return void this.log(`Cannot flush ${r} front buffer while SourceBuffer is in ended state`);this.hls.trigger(F.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:r})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:i,mediaSource:s}=this,r=t.fragments[0].start+t.totalduration,n=i.duration,a=x(s.duration)?s.duration:0;t.live&&e.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(t)):(r>a&&r>n||!x(n))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),s.duration=r)}updateSeekableRange(t){const e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&null!=e&&e.setLiveSeekableRange){const s=Math.max(0,i[0].start),r=Math.max(s,s+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${s}-${r}.`),e.setLiveSeekableRange(s,r)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&(!t||2===s||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(F.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in t)if(!e[r]){var s;const n=t[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let a=-1===(null==(s=n.levelCodec)?void 0:s.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===r.slice(0,5)&&(a=Le(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[r]=i.addSourceBuffer(o),s=r;this.addBufferListener(s,"updatestart",this._onSBUpdateStart),this.addBufferListener(s,"updateend",this._onSBUpdateEnd),this.addBufferListener(s,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(s,"bufferedchange",((t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(F.BUFFER_FLUSHED,{type:r})})),this.tracks[r]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:r,mimeType:o})}}}get mediaSrc(){var t;const e=(null==(t=this.media)?void 0:t.firstChild)||this.media;return null==e?void 0:e.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:i}=this;i.current(t).onComplete(),i.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var i;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,e),this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(s)}removeExecutor(t,e,i){const{media:s,mediaSource:r,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!s||!r||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=x(s.duration)?s.duration:1/0,h=x(r.duration)?r.duration:1/0,d=Math.max(0,e),c=Math.min(i,l,h);c>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),o.remove(d,c)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.sourceBuffer[e];if(i)i.ended=!1,i.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:i}=this,s=e.map((t=>i.appendBlocker(t)));Promise.all(s).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||i.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,i){const s=this.sourceBuffer[t];if(!s)return;const r=i.bind(this,t);this.listeners[t].push({event:e,listener:r}),s.addEventListener(e,r)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}},capLevelController:zn,errorController:class{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=V.log.bind(V,"[info]:"),this.warn=V.warn.bind(V,"[warning]:"),this.error=V.error.bind(V,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(F.ERROR,this.onError,this),t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(F.ERROR,this.onError,this),t.off(F.ERROR,this.onErrorOut,this),t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===Ve?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,s;if(e.fatal)return;const r=this.hls,n=e.context;switch(e.details){case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case U.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction={action:Oi,flags:$i});case U.FRAG_GAP:case U.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Fi);case U.LEVEL_EMPTY_ERROR:case U.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===Ve?e.level:r.loadLevel;e.details===U.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_LOAD_ERROR:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=r.levels[r.loadLevel];if(t&&(n.type===Ge&&t.hasAudioGroup(n.groupId)||n.type===He&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Fi,void(e.errorAction.flags=Bi)}return;case U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],i=null==t?void 0:t.attrs["HDCP-LEVEL"];i?e.errorAction={action:Fi,flags:Gi,hdcpLevel:i}:this.keySystemError(e)}return;case U.BUFFER_ADD_CODEC_ERROR:case U.REMUX_ALLOC_ERROR:case U.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(s=e.level)?s:r.loadLevel));case U.INTERNAL_EXCEPTION:case U.BUFFER_APPENDING_ERROR:case U.BUFFER_FULL_ERROR:case U.LEVEL_SWITCH_ERROR:case U.BUFFER_STALLED_ERROR:case U.BUFFER_SEEK_OVER_HOLE:case U.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Oi,flags:$i})}e.type===N.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const i=Ci(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(Di(i,s,ki(t),t.response))return{action:Ui,flags:$i,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Ci(t.details.startsWith("key")?n:r,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(s){t.details!==U.FRAG_GAP&&s.fragmentError++;if(Di(a,o,ki(t),t.response))return{action:Ui,flags:$i,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,n;const e=t.details;s.loadError++,e===U.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===Ke&&e===U.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===U.BUFFER_ADD_CODEC_ERROR||e===U.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>s.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===U.BUFFER_ADD_CODEC_ERROR||e===U.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e)),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let i=h.length;i--;){const r=(i+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const i=h[r];if(e===U.FRAG_GAP&&t.frag){const e=h[r].details;if(e){const i=Pi(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(p===Ge&&i.hasAudioGroup(v)||p===He&&i.hasSubtitleGroup(v))continue;if(f===Ke&&null!=(a=s.audioGroups)&&a.some((t=>i.hasAudioGroup(t)))||f===je&&null!=(o=s.subtitleGroups)&&o.some((t=>i.hasSubtitleGroup(t)))||g&&s.audioCodec===i.audioCodec||!g&&s.audioCodec!==i.audioCodec||m&&s.codecSet===i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Fi,flags:$i,nextAutoLevel:l}}return{action:Fi,flags:Bi}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case Oi:break;case Fi:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===U.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s,hdcpLevel:r,nextAutoLevel:n}=i;switch(s){case $i:this.switchLevel(t,n);break;case Gi:r&&(e.maxHdcpLevel=hi[hi.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(t){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=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(F.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(F.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,r=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(F.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;V.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(F.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:pt,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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},{cueHandler:Oa,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends $s{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",je),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.LEVEL_LOADED,this.onLevelLoaded,this),t.on(F.ERROR,this.onError,this),t.on(F.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(F.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(F.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(F.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(F.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(F.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.LEVEL_LOADED,this.onLevelLoaded,this),t.off(F.ERROR,this.onError,this),t.off(F.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(F.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(F.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(F.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(F.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(F.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=_s,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragPrevious=i,this.state=_s,!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let t=0;t=r[t].start&&a<=r[t].end){n=r[t];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(0===i&&s!==Number.POSITIVE_INFINITY){const t=s-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let i=0;inew pi(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new pi(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,je),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[s];if(a>=r.length||a!==s||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,bi(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(ps(n,t),l=n.fragments[0].start):e&&(l=e.start,bi(n,l))}if(o.details=n,this.levelLastLoaded=o,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===_s){Pi(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch((t=>{throw (r.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}), t)})).then((i=>{const s=performance.now();r.trigger(F.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:s}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=_s}))}}doTick(){if(this.media){if(this.state===_s){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;const{config:s}=this,r=this.getLoadPosition(),n=ds.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,Ve),h=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,c=d.length,u=h.edge;let f=null;const g=this.fragPrevious;if(au-t?0:t;f=Pi(g,d,Math.max(d[0].start,a),e),!f&&g&&g.startthis.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Ze(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.MANIFEST_PARSED,this.onManifestParsed,this),t.on(F.LEVEL_LOADING,this.onLevelLoading,this),t.on(F.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(F.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(F.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.MANIFEST_PARSED,this.onManifestParsed,this),t.off(F.LEVEL_LOADING,this.onLevelLoading,this),t.off(F.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(F.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(F.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}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);Ze(this.media.textTracks).forEach((t=>{Qe(t)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==s?void 0:s.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=Qi(e,t);if(i>-1)r=t[i];else{const t=Qi(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(F.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s),t}if(i)return null;{const i=Qi(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const i=e.id,s=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(F.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Ze(t.textTracks),i=this.currentTrack;let s;if(i&&(s=e.filter((t=>zr(i,t)))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==s&&(t.mode="disabled")})),s){const t=this.subtitleDisplay?"showing":"hidden";s.mode!==t&&(s.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!x(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t]||null;if(this.trackId=t,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(F.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${t}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=s;this.hls.trigger(F.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(d)}},timelineController:class{constructor(t){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.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.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}},t.on(F.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(F.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(F.FRAG_LOADING,this.onFragLoading,this),t.on(F.FRAG_LOADED,this.onFragLoaded,this),t.on(F.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(F.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(F.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(F.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(F.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(F.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(F.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(F.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(F.FRAG_LOADING,this.onFragLoading,this),t.off(F.FRAG_LOADED,this.onFragLoaded,this),t.off(F.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(F.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(F.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(F.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(F.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new En(this,"textTrack1"),e=new En(this,"textTrack2"),i=new En(this,"textTrack3"),s=new En(this,"textTrack4");this.cea608Parser1=new pn(1,t,e),this.cea608Parser2=new pn(3,i,s)}}addCues(t,e,i,s,r){let n=!1;for(let t=r.length;t--;){const s=r[t],d=(a=s[0],o=s[1],l=e,h=i,Math.min(o,h)-Math.max(a,l));if(d>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),n=!0,d/(i-e)>.5))return}var a,o,l,h;if(n||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,i,s)}else{const r=this.Cues.newCue(null,e,i,s);this.hls.trigger(F.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:r}){const{unparsedVttFrags:n}=this;"main"===i&&(this.initPTS[e.cc]={baseTime:s,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(F.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let s=0;s{Qe(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;tt.textCodec===On));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Wr(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Ze(t.textTracks):null;if(this.tracks.forEach(((t,i)=>{let s;if(e){let i=null;for(let s=0;snull!==t)).map((t=>t.label));t.length&&V.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(F.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,s=this.captionsProperties[i];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:s,lastCc:r,lastSn:n,lastPartIndex:a}=this;if(this.enabled&&i&&s&&e.frag.type===Ve){var o,l;const{cc:t,sn:h}=e.frag,d=null!=(o=null==e||null==(l=e.part)?void 0:l.index)?o:-1;h===n+1||h===n&&d===a+1||t===r||(i.reset(),s.reset()),this.lastCc=t,this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===je)if(s.byteLength){const t=i.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===On?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(F.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;$n(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),i.trigger(F.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{V.log(`Failed to parse IMSC1: ${e}`),i.trigger(F.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void n.push(t);const o=this.hls;Mn(null!=(e=i.initSegment)&&e.data?ee(i.initSegment.data,new Uint8Array(s)):s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(t=>{this._appendCues(t,i.level),o.trigger(F.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(i,s),V.log(`Failed to parse VTT cue: ${e}`),r&&a>i.cc||o.trigger(F.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||$n(e,this.initPTS[t.cc],(()=>{i.textCodec=On,this._parseIMSC1(t,e)}),(()=>{i.textCodec="wvtt"}))}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((t=>Xe(i,t)))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(F.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===je&&this.onFragLoaded(F.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!i||!s)return;const{frag:r,samples:n}=e;if(r.type!==Ve||"NONE"!==this.closedCaptionsForLevel(r))for(let t=0;tJe(t[s],e,i)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==s){const{textTracks:t}=this;Object.keys(t).forEach((i=>Je(t[i],e,s)))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let r=0;r0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=_s):(this.loadedmetadata=!1,this.state=Ps),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case _s:this.doTickIdle();break;case Ps:{var t;const{levels:e,trackId:i}=this,s=null==e||null==(t=e[i])?void 0:t.details;if(s){if(this.waitForCdnTuneIn(s))break;this.state=Ns}break}case ws:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=_s}break}case Ns:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:r}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Ds;const t={frag:e,part:i,payload:s.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),i=ds.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);xi(i.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=_s}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=_s)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:i,trackId:s}=this,r=t.config;if(!i&&(this.startFragRequested||!r.startFragPrefetch)||null==e||!e[s])return;const n=e[s],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Ps);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,X,Ke));const l=this.getFwdBufferInfo(o,Ke);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(F.BUFFER_EOS,{type:"audio"}),void(this.state=Os);const c=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Ve),u=l.len,f=this.getMaxBufferLength(null==c?void 0:c.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(d&&i){const t=this.getLoadPosition();h&&!Yr(d.attrs,h.attrs)&&(p=t),a.PTSKnown&&tm||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(u>=f&&!d&&pc.end+a.targetduration;if(E||(null==c||!c.len)&&l.len){const t=this.getAppendedFrag(v.start,Ve);if(null===t)return;if(y||(y=!!t.gap||!!E&&0===c.len),E&&!y||y&&l.nextStart&&l.nextStartnew pi(t)))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=_s,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=Cs),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!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(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(F.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:s}=this,{details:r,id:n}=e;if(!s)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const a=s[n];let o=0;if(r.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(r);const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;var l;if(!a.details&&r.hasProgramDateTime&&t.hasProgramDateTime)ps(r,t),o=r.fragments[0].start;else o=this.alignPlaylists(r,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=r,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(this.mainDetails||r,o),this.state!==Ps||this.waitForCdnTuneIn(r)||(this.state=_s),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new jr(this.hls,Ke,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=s?s.index:-1,n=-1!==e,a=new cs(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,n);c.push(r,f,d,"",i,s,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Bs,complete:!1};t.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=Ns}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type===Ke)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(F.AUDIO_TRACK_SWITCHED,I({},t)))}this.fragBufferedComplete(i,s)}else if(!this.loadedmetadata&&i.type===Ve){const t=this.videoBuffer||this.media;if(t){ds.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var i;if(e.fatal)this.state=Fs;else switch(e.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ke,e);break;case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ps||(null==(i=e.context)?void 0:i.type)!==Ge||(this.state=_s);break;case U.BUFFER_APPEND_ERROR:case U.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===U.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Q&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Q){this.flushing=!1,this.bufferFlushed=!0,this.state===Os&&(this.state=_s);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,Ke),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=xs,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,g.tracks,t,n),s.trigger(F.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:g.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=c;l&&(l.elementaryStreams[X]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(X,t,e,i,s),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=P({id:i,frag:o,details:d},f);s.trigger(F.FRAG_PARSING_METADATA,t)}if(u){const t=P({id:i,frag:o,details:d},u);s.trigger(F.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,s){if(this.state!==xs)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(F.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(F.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);var r;if(this.fragCurrent=t,this.switchingTrack||s===is||s===rs)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Ns;const i=this.mainDetails;i&&i.fragments[0].start!==e.details.fragments[0].start&&ps(e.details,i)}else this.startFragRequested=!0,super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:i}=this,s=null==i?void 0:i.attrs,r=t.attrs;e&&s&&(s.CHANNELS!==r.CHANNELS||i.name!==t.name||i.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(F.AUDIO_TRACK_SWITCHED,I({},t))}},audioTrackController:class extends Hi{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.MANIFEST_PARSED,this.onManifestParsed,this),t.on(F.LEVEL_LOADING,this.onLevelLoading,this),t.on(F.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(F.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(F.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.MANIFEST_PARSED,this.onManifestParsed,this),t.off(F.LEVEL_LOADING,this.onLevelLoading,this),t.off(F.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(F.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(F.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==s?void 0:s.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const i=Qi(e,t,Zi);if(i>-1)r=t[i];else{const t=Qi(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(F.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==s&&-1===o)this.setAudioTrack(s);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==Ge||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Ji(t,s,Zi))return s;const r=Qi(t,this.tracksInGroup,Zi);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const r=function(t,e,i,s,r){const n=e[s],a=e.reduce(((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t}),{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=ts(e,s,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const s=e.audioGroups,n=i.filter((t=>!s||-1!==s.indexOf(t.groupId)));return Qi(t,n,r)>-1}));return d>-1?d:ts(e,s,(e=>{const s=e.audioGroups,n=i.filter((t=>!s||-1!==s.indexOf(t.groupId)));return Qi(t,n,r)>-1}))}(t,e.levels,i,s,Zi);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=Qi(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t],r=s.details&&!s.details.live;if(t===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${t} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=t,this.currentTrack=s,this.hls.trigger(F.AUDIO_TRACK_SWITCHING,I({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:Jn.MANIFEST,su:!this.initialized})}catch(t){V.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,i=this.hls.levels[e.level],s=this.getObjectType(e),r={d:1e3*e.duration,ot:s};s!==Jn.VIDEO&&s!==Jn.AUDIO&&s!=Jn.MUXED||(r.br=i.bitrate/1e3,r.tb=this.getTopBandwidth(s)/1e3,r.bl=this.getBufferLength(s)),this.apply(t,r)}catch(t){V.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}));}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(F.MEDIA_DETACHED,this.onMediaDetached,this),t.on(F.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(F.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(F.MEDIA_DETACHED,this.onMediaDetached,this),t.off(F.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.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(t,e){var i,s;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=e.tracks.video)?void 0:s.buffer}createData(){var t;return{v:1,sf:Zn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){P(e,this.createData());const i=e.ot===Jn.INIT||e.ot===Jn.VIDEO||e.ot===Jn.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce(((t,i)=>(s.includes(i)&&(t[i]=e[i]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),Aa(t.headers,e)):t.url=Ra(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?Jn.TIMED_TEXT:"initSegment"===t.sn?Jn.INIT:"audio"===e?Jn.AUDIO:"main"===e?this.hls.audioTracks.length?Jn.VIDEO:Jn.MUXED:void 0}getTopBandwidth(t){let e,i=0;const s=this.hls;if(t===Jn.AUDIO)e=s.audioTracks;else{const t=s.maxAutoLevel,i=t>-1?t+1:s.levels.length;e=s.levels.slice(0,i)}for(const t of e)t.bitrate>i&&(i=t.bitrate);return i>0?i:NaN}getBufferLength(t){const e=this.hls.media,i=t===Jn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*ds.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}},contentSteeringController:class{constructor(t){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=t,this.log=V.log.bind(V,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(F.MANIFEST_PARSED,this.onManifestParsed,this),t.on(F.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(F.MANIFEST_PARSED,this.onManifestParsed,this),t.off(F.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}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(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Fi&&i.flags===Bi){const t=this.levels;let s=this.pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:n}=e.context;i&&t?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&t&&(s=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),i.resolved||V.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${JSON.stringify(s)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach((t=>{s-i[t]>3e5&&delete i[t]}));for(let s=0;s0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Ri(e),this.hls.trigger(F.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new W(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Ca(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new pi({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e{this.log(`Loaded steering manifest: "${s}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:s.toString()};this.hls.trigger(F.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,i,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,r);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}});function Na(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Na):Object.keys(t).reduce(((e,i)=>(e[i]=Na(t[i]),e)),{}):t}function Ua(t){const e=t.loader;if(e!==wa&&e!==Ia)V.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=wa,t.progressive=!0,t.enableSoftwareAES=!0,V.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let $a;class Ba extends Hi{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(F.MANIFEST_LOADING,this.onManifestLoading,this),t.on(F.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(F.LEVEL_LOADED,this.onLevelLoaded,this),t.on(F.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(F.FRAG_BUFFERED,this.onFragBuffered,this),t.on(F.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(F.MANIFEST_LOADING,this.onManifestLoading,this),t.off(F.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(F.LEVEL_LOADED,this.onLevelLoaded,this),t.off(F.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(F.FRAG_BUFFERED,this.onFragBuffered,this),t.off(F.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,h;const d=t.attrs;let{audioCodec:c,videoCodec:u}=t;-1!==(null==(e=c)?void 0:e.indexOf("mp4a.40.34"))&&($a||($a=/chrome|firefox/i.test(navigator.userAgent)),$a&&(t.audioCodec=c=void 0)),c&&(t.audioCodec=c=Le(c,i)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=t.videoCodec=function(t){const e=t.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return t}(u));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!c),null!=m&&m.length||c&&!ve(c,"audio",i)||u&&!ve(u,"video",i))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=d,b=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[b])if(r[b].uri===t.url||t.attrs["PATHWAY-ID"])r[b].addGroupId("audio",d.AUDIO),r[b].addGroupId("text",d.SUBTITLES);else{const e=n[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=new pi(t);r[b]=i,s.push(i)}else{const e=new pi(t);r[b]=e,n[b]=1,s.push(e)}})),this.filterAndSortMediaOptions(s,e,a,o,l)}filterAndSortMediaOptions(t,e,i,s,r){let n=[],a=[],o=t;if((i||s)&&r&&(o=o.filter((({videoCodec:t,videoRange:e,width:i,height:s})=>{return(!!t||!(!i||!s))&&(!!(r=e)&&di.indexOf(r)>-1);var r}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;n=e.audioTracks.filter((e=>!e.audioCodec||ve(e.audioCodec,"audio",t))),Ga(n)}e.subtitles&&(a=e.subtitles,Ga(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return di.indexOf(t.videoRange)-di.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=Te(t.videoCodec),s=Te(e.videoCodec);if(i!==s)return s-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=Se(t.codecSet),s=Se(e.codecSet);if(i!==s)return s-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;ti&&i===Fa.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=r&&!s,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:s,altAudio:!c&&n.some((t=>!!t.url))};this.hls.trigger(F.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(F.ERROR,{type:N.OTHER_ERROR,details:U.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:i,reason:i.message}),s)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,i===t&&n.details&&s&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(F.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==s?void 0:s.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Be&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===Ve){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,n=this._levels[s];var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));s===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(s,e,n.details)):null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(t)try{s=t.addDirectives(s)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const r=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${r?" Pathway "+r:""} ${s}`),this.clearTimer(),this.hls.trigger(F.LEVEL_LOADING,{url:s,level:e,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const i=this._levels.filter(((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));Ri(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(F.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(F.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Ga(t){const e={};t.forEach((t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}class Ha{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=U.KEY_LOAD_ERROR,i,s,r){return new Ss({type:N.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:s})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=t;for(let t=0;t{r.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,U.KEY_LOAD_ERROR,i))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,U.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(s=a)&&s.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(r.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={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"identity"===r.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,U.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(i);if(e)return (t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,i)))).catch((e=>{throw (t.keyLoadPromise=null, e)}));}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=new(0,i.loader)(i);return e.keyLoader=t.loader=s,t.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,s)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,U.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,i,s,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,U.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),s,I({url:a.url,data:void 0},t)))},onTimeout:(t,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(e,U.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(t,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(e,U.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,h)}))}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],r&&r.destroy()}}function Va(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ka(){if(!me())return!1;const t=Va();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class ja{constructor(t,e,i,s){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=t,this.media=e,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:i,media:s,stalled:r}=this;if(null===s)return;const{currentTime:n,seeking:a}=s,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==r){if(this.stallReported){const t=self.performance.now()-r;V.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(s.paused&&!a||s.ended||0===s.playbackRate||!ds.getBuffered(s).length)return void(this.nudgeRetry=0);const h=ds.bufferInfo(s,n,0),d=h.nextStart||0;if(a){const t=h.len>2,i=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==e||null==(c=e.details)?void 0:c.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=i||r))return void(s.paused||this._trySkipBufferHole(r))}const u=self.performance.now();if(null===r)return void(this.stalled=u);const f=u-r;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=ds.bufferInfo(s,n,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:s,media:r}=this;if(null===r)return;const n=r.currentTime,a=s.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-n1e3*i.highBufferWatchdogPeriod&&(V.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(t)})`);V.warn(s.message),e.trigger(F.ERROR,{type:N.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:i,media:s}=this;if(null===s)return 0;const r=s.currentTime,n=ds.bufferInfo(s,r,0),a=r0&&n.len<1&&s.readyState<3,h=a-r;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let i=!1;if(0===r){const t=e.getAppendedFrag(0,Ve);t&&a1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=_s,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Cs}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Us:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(s))break;this.state=_s;break}if(this.hls.nextLoadLevel!==this.level){this.state=_s;break}break}case ws:{var t;const e=self.performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,i=null==t?void 0:t[e];this.resetStartWhenNotLoaded(i||null),this.state=_s}}}this.state===_s&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(null===e||!s&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=t.nextLoadLevel;if(null==i||!i[r])return;const n=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(F.BUFFER_EOS,t),void(this.state=Os)}t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===Us||l.live&&this.levelLastLoaded!==n)return this.level=r,void(this.state=Us);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==ns){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?X:Q,e=(t===Q?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,Ve)}u=this.getNextFragmentLoopLoading(u,l,a,Ve,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);this.fragCurrent=t,s===is||s===rs?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,i)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Ve)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Is:case Ds:case ws:case xs:case Ms:this.state=_s}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new ja(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.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 t=this.media,e=t?t.currentTime:null;x(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(F.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let i=!1,s=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(i=i||-1!==e.indexOf("mp4a.40.2"),s=s||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&s&&!function(){var t;const e=Va();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==_s)return;const s=i[e.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=Us)}onLevelLoaded(t,e){var i;const{levels:s}=this,r=e.level,n=e.details,a=n.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=s[r],l=this.fragCurrent;!l||this.state!==Ds&&this.state!==ws||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(i=o.details)&&i.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(F.LEVEL_UPDATED,{details:n,level:r}),this.state===Us){if(this.waitForCdnTuneIn(n))return;this.state=_s}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new jr(this.hls,Ve,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,m=new cs(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[i.cc];u.push(r,d,c,l,i,s,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const i=this.altAudio;if(!!!e.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 t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;i&&(t.trigger(F.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(F.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=e.id,s=!!this.hls.audioTracks[i].url;if(s){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=s,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i&&i.type!==Ve)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ms&&(this.state=_s));const r=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal)this.state=Fs;else switch(e.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ve,e);break;case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Us||(null==(i=e.context)?void 0:i.type)!==Be||(this.state=_s);break;case U.BUFFER_APPEND_ERROR:case U.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===U.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!ds.getBuffered(t).length){const t=this.state!==_s?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=_s,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==X||this.audioOnly&&!this.altAudio){const t=(e===Q?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,Ve),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e0&&(r{const{hls:s}=this;if(!i||this.fragContextChanged(t))return;e.fragmentError=0,this.state=_s,this.startFragRequested=!1,this.bitrateTest=!1;const r=t.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(F.FRAG_LOADED,i),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const i="main",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:d,text:c,id3:u,initSegment:f}=r,{details:g}=h,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=xs,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,f.tracks,t,n),s.trigger(F.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;x(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},s.trigger(F.INIT_PTS_FOUND,{frag:o,id:i,initPTS:t,timescale:e}))}if(d&&g&&"initSegment"!==o.sn){const t=g.fragments[o.sn-1-g.startSN],e=o.sn===g.startSN,i=!t||o.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:s,startDTS:r,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:t,endPTS:s,startDTS:r,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,s,r,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,e||i)}else{if(!e&&!i)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=m;l&&(l.elementaryStreams[X]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(X,t,e,i,s),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(e=u.samples)&&e.length){const t={id:i,frag:o,details:g,samples:u.samples};s.trigger(F.FRAG_PARSING_METADATA,t)}if(g&&c){const t={id:i,frag:o,details:g,samples:c.samples};s.trigger(F.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,i,s){if(this.state!==xs)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:r,video:n,audiovideo:a}=e;if(r){let e=t.audioCodec;const i=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==r.metadata.channelCount&&-1===i.indexOf("firefox")&&(e="mp4a.40.5")),e&&-1!==e.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==r.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),r.levelCodec=e,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${r.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(F.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(F.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Ve)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=_s}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(ds.isBuffered(t,i)?e=this.getAppendedFrag(i):ds.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(F.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(F.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,i=this.currentFrag;if(i&&x(e)&&x(i.programDateTime)){const t=i.programDateTime+1e3*(e-i.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Ya{static get version(){return"1.5.8"}static isMSESupported(){return Ka()}static isSupported(){return function(){if(!Ka())return!1;const t=me();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(Ee(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(Ee(e,"audio")))))}()}static getMediaSource(){return me()}static get Events(){return F}static get ErrorTypes(){return N}static get ErrorDetails(){return U}static get DefaultConfig(){return Ya.defaultConfig?Ya.defaultConfig:Fa}static set DefaultConfig(t){Ya.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Kr,this._autoLevelCapping=-1,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,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){H(t,"debug","log","info","warn","error");try{G.log(`Debug logs enabled for "${e}" in hls.js version 1.5.8`)}catch(t){G=B}}else G=B}(t.debug||!1,"Hls instance");const e=this.config=function(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(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Na(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[r],a=[];s.forEach((s=>{const o=`${t}Loading${s}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=i[r].default;switch(e[r]={default:t},s){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&V.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${r}": ${JSON.stringify(e[r])}`)})),I(I({},i),e)}(Ya.DefaultConfig,t);this.userConfig=t,e.progressive&&Ua(e);const{abrController:i,bufferController:s,capLevelController:r,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new i(this),h=this.bufferController=new s(this),d=this.capLevelController=new r(this),c=new a(this),u=new ze(this),f=new oi(this),g=e.contentSteeringController,m=g?new g(this):null,p=this.levelController=new Ba(this,m),v=new as(this),y=new Ha(this.config),E=this.streamController=new Wa(this,v,y);d.setStreamController(E),c.setStreamController(E);const T=[u,p,E];m&&T.splice(1,0,m),this.networkControllers=T;const S=[l,h,d,c,f,v];this.audioTrackController=this.createController(e.audioTrackController,T);const b=e.audioStreamController;b&&T.push(new b(this,v,y)),this.subtitleTrackController=this.createController(e.subtitleTrackController,T);const A=e.subtitleStreamController;A&&T.push(new A(this,v,y)),this.createController(e.timelineController,S),y.emeController=this.emeController=this.createController(e.emeController,S),this.cmcdController=this.createController(e.cmcdController,S),this.latencyController=this.createController(li,S),this.coreComponents=S,T.push(o);const L=o.onErrorOut;"function"==typeof L&&this.on(F.ERROR,L,o)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(V.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===F.ERROR;this.trigger(F.ERROR,{type:N.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){V.log("destroy"),this.trigger(F.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){V.log("attachMedia"),this._media=t,this.trigger(F.MEDIA_ATTACHING,{media:t})}detachMedia(){V.log("detachMedia"),this.trigger(F.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,i=this.url,s=this.url=C.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,V.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(F.MANIFEST_LOADING,{url:t})}startLoad(t=-1){V.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){V.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){V.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){V.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){V.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){V.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){V.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){V.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){V.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(V.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return hi.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=i)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}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}}Ya.defaultConfig=void 0;const za=new RegExp("(^https://v.redd.it/)([a-zA-Z0-9]+)/");function qa(t){const e=t?.match(za);return 3===e?.length?e[2]:""}const Xa="@reddit/shreddit-player-media-quality";function Qa(t){return t>=1080?1080:t>=720?720:t>=540?540:t>=480?480:t>=360?360:t>=240?240:144}function Ja({hlsEngine:t,mp4Sources:e}){return e?e.some((t=>t.source.dimensions.height>t.source.dimensions.width&&t.source.dimensions.height>768)):!!t&&t.levels.some((t=>t.height>t.width&&t.height>768))}function Za(t=[]){return t.sort(((t,e)=>t.quality>e.quality?-1:1))}function to(t,e=[]){for(let i=0;i=e[i].quality)return i;return e.length-1}function eo(){const e=t.a0.getItem(Xa);return e?parseInt(e):void 0}class io{constructor(t){(this.host=t).addController(this),this.videoElement=t.videoElement}hostDisconnected(){this.destroyHlsEngine()}get isHlsStream(){return this.host.src.includes(".m3u8")}async initializeHlsJs(){Ya.isSupported()?(this.hls=new Ya((({cmcdSessionId:t,src:e})=>({capLevelToPlayerSize:!0,cmcd:{sessionId:t,contentId:qa(e),useHeaders:!0},maxBufferLength:20,maxMaxBufferLength:20,backBufferLength:3}))({authToken:this.host.streamingAuthToken,cmcdSessionId:this.host.subSessionId,src:this.host.src})),this.hls.once(Ya.Events.MANIFEST_PARSED,(()=>{this.host.qualityLevels=this.createQualityLevels(),this.host.currentQualityLevelIndex=this.getInitialQualityLevel()})),this.hls.on(Ya.Events.MANIFEST_LOADING,(()=>{this.host.telemetryController.startDownload()})),this.hls.on(Ya.Events.MANIFEST_LOADED,(()=>{this.host.telemetryController.endDownload()})),this.hls.on(Ya.Events.FRAG_LOADED,(()=>{this.host.errorController.resetRetryCount()})),this.hls.on(Ya.Events.LEVEL_SWITCHED,(()=>{this.host.telemetryController.switchBitrate()})),this.hls.on(Ya.Events.BUFFER_APPENDED,(()=>{this.host.errorController.resetRetryCount()})),this.hls.on(Ya.Events.LEVEL_LOADED,(()=>{this.host.errorController.resetRetryCount()})),this.hls.on(Ya.Events.ERROR,this.host.errorController.handleHlsError),this.hls.loadSource(this.host.src),this.hls.attachMedia(this.videoElement)):this.videoElement.src||(this.videoElement.src=this.host.src)}setQualityLevel(t){this.host.currentQualityLevelIndex=t,this.hls&&(this.hls.nextLevel=t)}createQualityLevels(){if(!this.hls)return[];const t=[],e=Ja({hlsEngine:this.hls});return(this.hls.levels||[]).map(((t,e)=>({...t,hlsLevelIndex:e}))).sort(((t,e)=>t.bitrate>e.bitrate?-1:1)).forEach((i=>{const s=Qa(e?i?.width:i?.height);s&&-1===t.map((t=>t.quality)).indexOf(s)&&t.push({hlsLevelIndex:i.hlsLevelIndex,quality:s})})),Za(t)}getInitialQualityLevel(){const t=eo();if(t&&this.hls){const e=this.host.qualityLevels.filter((e=>e.quality===t))[0]?.hlsLevelIndex;if(void 0!==e)return this.hls.startLevel=e,this.hls.loadLevel=e,e}return-1}updateCmcdSessionId(t){this.hls&&this.hls.cmcdController&&(this.hls.cmcdController.sid=t)}destroyHlsEngine(){this.hls?.destroy(),this.hls=void 0}getCurLevel(){return this.hls?.levels&&void 0!==this.hls?.currentLevel?this.hls.levels[this.hls.currentLevel]:void 0}getCurAudioTrack(){return this.hls?.audioTracks&&void 0!==this.hls?.audioTrack?this.hls.audioTracks[this.hls.audioTrack]:void 0}}var so={fullscreenEnabled:0,fullscreenElement:1,requestFullscreen:2,exitFullscreen:3,fullscreenchange:4,fullscreenerror:5,fullscreen:6},ro=["webkitFullscreenEnabled","webkitFullscreenElement","webkitRequestFullscreen","webkitExitFullscreen","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"],no=["mozFullScreenEnabled","mozFullScreenElement","mozRequestFullScreen","mozCancelFullScreen","mozfullscreenchange","mozfullscreenerror","-moz-full-screen"],ao=["msFullscreenEnabled","msFullscreenElement","msRequestFullscreen","msExitFullscreen","MSFullscreenChange","MSFullscreenError","-ms-fullscreen"],oo="undefined"!=typeof window&&void 0!==window.document?window.document:{},lo="fullscreenEnabled"in oo&&Object.keys(so)||ro[0]in oo&&ro||no[0]in oo&&no||ao[0]in oo&&ao||[],ho={requestFullscreen:function(t){return t[lo[so.requestFullscreen]]()},requestFullscreenFunction:function(t){return t[lo[so.requestFullscreen]]},get exitFullscreen(){return oo[lo[so.exitFullscreen]].bind(oo)},get fullscreenPseudoClass(){return":"+lo[so.fullscreen]},addEventListener:function(t,e,i){return oo.addEventListener(lo[so[t]],e,i)},removeEventListener:function(t,e,i){return oo.removeEventListener(lo[so[t]],e,i)},get fullscreenEnabled(){return Boolean(oo[lo[so.fullscreenEnabled]])},set fullscreenEnabled(t){},get fullscreenElement(){return oo[lo[so.fullscreenElement]]},set fullscreenElement(t){},get onfullscreenchange(){return oo[("on"+lo[so.fullscreenchange]).toLowerCase()]},set onfullscreenchange(t){return oo[("on"+lo[so.fullscreenchange]).toLowerCase()]=t},get onfullscreenerror(){return oo[("on"+lo[so.fullscreenerror]).toLowerCase()]},set onfullscreenerror(t){return oo[("on"+lo[so.fullscreenerror]).toLowerCase()]=t}};class co{constructor(e){this._logMessage=u,this._playRequested=!1,this._loadRequested=!1,this.play=async(t=!1)=>{if(this.host.hasHadPlayAttempt=!0,this._playRequested=!0,this.videoElement.paused)if(t?this.host.telemetryController.autoplay():this.host.telemetryController.clickPlay(),this.host.mediaUI?.showLoadingSpinner(),this.host.initializeVideoElement(),this.host.isHls&&!this.host.hlsController.hls&&(await (this.host.hlsController?.initializeHlsJs())),this.host.mediaVisibilityController?.isVideoInView()||this.host.playOutOfViewport){this.host.subSessionPlayStartTime=this.host.subSessionPlayStartTime||Date.now();try{await this.videoElement.play(),this.host.debugOverlay?.log("Load time",(Date.now()-(this.host.subSessionInstructionTime??0))/1e3+"s")}catch(t){this._logMessage({msg:"Play failed",error:t,debugOverlay:this.host.debugOverlay}),this.host.pause("scroll")}}else this.pause("scroll")},this.pause=t=>{if(this._playRequested){if("click"===t)this.host.telemetryController.clickPause();else if("scroll"===t)this.host.telemetryController.scrollPause();else if("background"===t)this.host.telemetryController.backgroundVideo();else if("ended"===t&&(this.host.playCount++,this.host.telemetryController.servedVideo(),this._shouldLoop()))return this.loop();this.host.updateSubSession()}this._playRequested=!1,"click"===t&&this.host.autoplay&&(this.host.autoplay=!1),this.videoElement.pause(),this.host.mediaUI?.setPausedState()},this.loop=()=>{this.host.telemetryController.looped=!0,this.host.updateSubSession(),this.play(!0)},this._shouldLoop=()=>!(!this.host.gif&&!this.host.loop)&&(!this.host.loopLimit||this.host.playCount<=this.host.loopLimit),this.togglePlay=()=>{this.videoElement.paused?this.play(!1):this.pause("click")},this.load=async(e=t.kf.AUTO)=>{this._loadRequested||this._playRequested||this.host.hasHadPlayAttempt||(this._loadRequested=!0,this.host.initializeVideoElement(),this.host.isHls&&!this.host.hlsController.hls&&(await (this.host.hlsController?.initializeHlsJs())),this.videoElement.preload=e,this.videoElement.load())},this.stop=()=>{this.host.initialized&&(this.host.stoppedState={currentTime:this.videoElement.currentTime},this.videoElement.pause(),this.host.isHls&&this.host.hlsController.destroyHlsEngine(),this.videoElement.removeAttribute("src"),this.videoElement.load(),this.host.initialized=!1)},this.toggleFullscreen=()=>{if(ho.fullscreenElement===this.host)ho.exitFullscreen();else{this.host.mediaSyncController.syncPlayback();try{ho.fullscreenEnabled?(ho.requestFullscreen(this.host),this.host.telemetryController.enterFullscreen()):"function"==typeof this.host.videoElement.webkitSetPresentationMode?(this.host.videoElement.webkitSetPresentationMode?.("fullscreen"),this.host.telemetryController.enterFullscreen()):this._logMessage({msg:"Could not enter fullscreen for device",debugOverlay:this.host.debugOverlay})}catch(t){this._logMessage({msg:"Error entering fullscreen",error:t,debugOverlay:this.host.debugOverlay})}}},this.setQualityLevel=t=>{this.host.isHls?this.host.hlsController.setQualityLevel(t):this.host.isMp4&&this.host.packagedMediaController.setQualityLevel(t)},this.toggleCaptions=()=>this.host.mediaUI?.captionController?.toggleCaptions(),this.setVolume=t=>this.host.volumeController.setVolume(t),this.increaseVolume=()=>this.host.volumeController.increaseVolume(),this.decreaseVolume=()=>this.host.volumeController.decreaseVolume(),this.toggleMute=()=>this.host.volumeController.toggleMute(),(this.host=e).addController(this),this.videoElement=e.videoElement}hostDisconnected(){this._playRequested=!1,this._loadRequested=!1}}class uo{constructor(e){this.initializeSubscribers=()=>{this.hotkeyController?.contextualSubscribe(t.kg.TOGGLE_PLAY,this.mediaActionsController?.togglePlay),this.hotkeyController?.contextualSubscribe(t.kg.TOGGLE_FULLSCREEN,this.mediaActionsController?.toggleFullscreen),this.hotkeyController?.contextualSubscribe(t.kg.REWIND_5,this._rewind5),this.hotkeyController?.contextualSubscribe(t.kg.FAST_FORWARD_5,this._fastForward5),this.hotkeyController?.contextualSubscribe(t.kg.INCREASE_VOLUME,this.mediaActionsController?.increaseVolume),this.hotkeyController?.contextualSubscribe(t.kg.DECREASE_VOLUME,this.mediaActionsController?.decreaseVolume),this.hotkeyController?.contextualSubscribe(t.kg.REWIND_10,this._rewind10),this.hotkeyController?.contextualSubscribe(t.kg.FAST_FORWARD_10,this._fastForward10),this.hotkeyController?.contextualSubscribe(t.kg.RESTART,this._restart),this.hotkeyController?.contextualSubscribe(t.kg.TOGGLE_MUTE,this.mediaActionsController?.toggleMute),this.hotkeyController?.contextualSubscribe(t.kg.TOGGLE_CAPTIONS,this.mediaActionsController?.toggleCaptions)},this._rewind5=()=>{this.timeController?.skipTime(-5)},this._fastForward5=()=>{this.timeController?.skipTime(5)},this._rewind10=()=>{this.timeController?.skipTime(-10)},this._fastForward10=()=>{this.timeController?.skipTime(10)},this._restart=()=>{this.timeController?.setTime(0)},(this.host=e).addController(this)}get mediaActionsController(){return this.host.mediaActionsController}get timeController(){return this.host.mediaUI?.timeController}hostConnected(){this.hotkeyController=new t.cn(this.host),this.initializeSubscribers()}hostDisconnected(){this.hotkeyController?.contextualUnsubscribe(t.kg.TOGGLE_PLAY,this.mediaActionsController?.togglePlay),this.hotkeyController?.contextualUnsubscribe(t.kg.TOGGLE_FULLSCREEN,this.mediaActionsController?.toggleFullscreen),this.hotkeyController?.contextualUnsubscribe(t.kg.REWIND_5,this._rewind5),this.hotkeyController?.contextualUnsubscribe(t.kg.FAST_FORWARD_5,this._fastForward5),this.hotkeyController?.contextualUnsubscribe(t.kg.INCREASE_VOLUME,this.mediaActionsController?.increaseVolume),this.hotkeyController?.contextualUnsubscribe(t.kg.DECREASE_VOLUME,this.mediaActionsController?.decreaseVolume),this.hotkeyController?.contextualUnsubscribe(t.kg.REWIND_10,this._rewind10),this.hotkeyController?.contextualUnsubscribe(t.kg.FAST_FORWARD_10,this._fastForward10),this.hotkeyController?.contextualUnsubscribe(t.kg.RESTART,this._restart),this.hotkeyController?.contextualUnsubscribe(t.kg.TOGGLE_MUTE,this.mediaActionsController?.toggleMute),this.hotkeyController?.contextualUnsubscribe(t.kg.TOGGLE_CAPTIONS,this.mediaActionsController?.toggleCaptions),this.hotkeyController=void 0}}const fo="@reddit/shreddit-player-media-volume";let go=!1;class mo{constructor(t){this.setVolume=t=>{let e=parseFloat(Math.pow(t,2).toFixed(2));e=Math.min(Math.max(e,0),1),this.videoElement.volume=e,this.videoElement.muted=!e,e>0&&(go=!0),po({volume:e,muted:this.videoElement.muted})},this.increaseVolume=()=>{const t=Math.min(this.sliderPosition+.1,1);this.setVolume(t)},this.decreaseVolume=()=>{const t=Math.max(this.sliderPosition-.1,0);this.setVolume(t)},this.toggleMute=()=>{const t=!this.videoElement.muted;this.videoElement.muted=t,this.host.telemetryController.clickMute(t),t||(go=!0,0===this.videoElement.volume&&(this.videoElement.volume=this.defaultVolumeSetting.volume)),po({volume:this.videoElement.volume,muted:this.videoElement.muted})},(this.host=t).addController(this),this.videoElement=t.videoElement}hostConnected(){}hostDisconnected(){}get defaultVolumeSetting(){return{volume:.25,muted:!1}}setInitialVolumeSetting(){const{autoplay:e,gif:i}=this.host;if(i)return this.videoElement.volume=0,void(this.videoElement.muted=!0);const s=function(){try{return JSON.parse(t.a0.getItem(fo))}catch(t){return}}(),r={...this.defaultVolumeSetting,...s};e?(go?(this.videoElement.volume=r.volume,this.videoElement.muted=r.muted,this.host.mediaUI?.setAttr(t.gt.MUTED,this.videoElement.muted)):(this.videoElement.volume=r.volume,this.videoElement.muted=!0,this.host.mediaUI?.setAttr(t.gt.MUTED)),this.updateVolumeFillRate()):(this.videoElement.volume=r.volume,this.videoElement.muted=r.muted)}get sliderPosition(){return this.videoElement.muted?0:Math.sqrt(this.videoElement.volume)}updateVolumeFillRate(){this.host.mediaUI?.style.setProperty(t.kh.VOLUME_FILL_RATE,this.sliderPosition.toString())}}function po({volume:e,muted:i}){t.a0.setItem(fo,JSON.stringify({volume:e,muted:i}))}class vo{constructor(e){this.syncPlayback=()=>{this.pubSubController.publish(t.T.MediaSyncPlayback,{subSessionId:this.host.subSessionId})},this.handlePlaybackSync=({subSessionId:t})=>{t!==this.host.subSessionId&&this.host.pause("scroll")},this.syncVolume=()=>{this.pubSubController.publish(t.T.MediaSyncVolume,{volume:this.videoElement.volume,muted:this.videoElement.muted})},this.handleVolumeSync=({volume:t,muted:e})=>{e||function(t=!0){go=t}(!0),this.videoElement.volume===t&&this.videoElement.muted===e||(this.videoElement.volume=t,this.videoElement.muted=e)},(this.host=e).addController(this),this.videoElement=e.videoElement,this.pubSubController=new t.m(this.host)}hostConnected(){this.host.singlePlayback&&(this.videoElement?.addEventListener("playing",this.syncPlayback),this.pubSubController.subscribe(t.T.MediaSyncPlayback,this.handlePlaybackSync)),this.host.gif||d((()=>{this.videoElement?.addEventListener("volumechange",this.syncVolume),this.pubSubController.subscribe(t.T.MediaSyncVolume,this.handleVolumeSync)}))}hostDisconnected(){this.host.singlePlayback&&(this.videoElement?.removeEventListener("playing",this.syncPlayback),this.pubSubController.unsubscribe(t.T.MediaSyncPlayback,this.handlePlaybackSync)),this.host.gif||(this.videoElement?.removeEventListener("volumechange",this.syncVolume),this.pubSubController.unsubscribe(t.T.MediaSyncVolume,this.handleVolumeSync))}}class yo{constructor(e){this._isWithinAutoplayThreshold=!1,this._canAutoplay=!0,this._autoplayAttemptFailures=0,this.handleAutoplayAttempt=({isAttempting:t})=>{this._canAutoplay=!t},this.preloadIntersectionCallback=t=>{const e=t[t.length-1].isIntersecting;e&&this.host.autoplay?this.host.load():e||this.host.playOutOfViewport||this.host.stop()},this.autoplayIntersectionCallback=e=>{const i=e[e.length-1].intersectionRatio;this._isWithinAutoplayThreshold=i>=.5,this._isWithinAutoplayThreshold?this.host.idleAutoplay?d(this.attemptAutoplay):this.attemptAutoplay():this.host.playOutOfViewport||(this.host.pause("scroll"),this.pubSubController.publish(t.T.MediaAutoplayAttempt,{isAttempting:!1}))},this.attemptAutoplay=async()=>{if(this.shouldVideoAutoplay())if(this.host.initializeVideoElement(),this.host.singlePlayback){if(ho.fullscreenElement)return;if(this._canAutoplay){this.pubSubController.publish(t.T.MediaAutoplayAttempt,{isAttempting:!0});try{await this.host.play(!0),this.pubSubController.publish(t.T.MediaAutoplayAttempt,{isAttempting:!1})}catch(e){if(this.pubSubController.publish(t.T.MediaAutoplayAttempt,{isAttempting:!1}),this._autoplayAttemptFailures++,this._autoplayAttemptFailures<3)return void this.attemptAutoplay();this.host.pause("scroll"),this.host.mediaUI?.showPoster()}}else this.host.mediaUI?.showPoster()}else this.host.play(!0)},(this.host=e).addController(this),this.pubSubController=new t.m(this.host)}hostConnected(){this.pubSubController.subscribe(t.T.MediaAutoplayAttempt,this.handleAutoplayAttempt),this.preloadObserver=new IntersectionObserver(this.preloadIntersectionCallback,{threshold:0,rootMargin:"500px 0px"}),this.preloadObserver.observe(this.host),this.autoplayObserver=new IntersectionObserver(this.autoplayIntersectionCallback,{threshold:.5}),this.autoplayObserver.observe(this.host)}hostDisconnected(){this.preloadObserver?.unobserve(this.host),this.preloadObserver?.disconnect(),this.autoplayObserver?.unobserve(this.host),this.autoplayObserver?.disconnect(),this._isWithinAutoplayThreshold=!1,this._autoplayAttemptFailures=0}isVideoInView(){return"visible"===document.visibilityState&&this._isWithinAutoplayThreshold}shouldVideoAutoplay(){return Boolean(this.host.autoplay&&this.isVideoInView()&&!this.host.mediaUI?.hasAttribute(t.gt.ENDED))}}let Eo=t.C;class To{constructor(t){this._logException=f,(this.host=t).addController(this),this.videoElement=t.videoElement}async hostDisconnected(){this.packagedMedia=void 0}get hasPackagedMedia(){return!!this.host.packagedMediaJSON}initialize(){if(!this.videoElement)throw new Error("Video element not found");this.hasPackagedMedia&&(this.parsePackagedMedia(),this.host.qualityLevels=this.createQualityLevels(),this.setQualityLevel(this.getInitialQualityLevel()))}parsePackagedMedia(){try{this.packagedMedia=JSON.parse(this.host.packagedMediaJSON),this.packagedMedia?.playbackMp4s?.permutations?.length||this.errorParsingPackagedMedia()}catch(t){this.errorParsingPackagedMedia(t)}}errorParsingPackagedMedia(t){this._logException({msg:"Could not parse packaged-media-json",error:t,debugOverlay:this.host.debugOverlay}),this.host.packagedMediaJSON=void 0,this.packagedMedia=void 0}setQualityLevel(t){this.host.currentQualityLevelIndex=t;const e=this.packagedMedia?.playbackMp4s.permutations[-1===t?function(t){let e=0;const i=navigator?.connection||navigator?.mozConnection||navigator?.webkitConnection,s=i?.effectiveType;return e="4g"===s||(i?.downlink??0)>3?0:to("3g"===s?360:"2g"===s||"slow-2g"===s?144:480,t),t[e].mp4SourceIndex??0}(this.host.qualityLevels):t]?.source.url,i=this.videoElement.currentTime;if(e){const t=new URL(e);i&&(t.hash=`t=${i}`);const s=!this.videoElement.paused;this.videoElement.src=t.toString(),s&&this.host.play()}}updateAuthTokenParam(){this.videoElement.src=function(e,i){if(!i)return e;const s=new URL(e);return s.searchParams.set(t.ki,i),s.toString()}(this.videoElement.src,this.host.packagedAuthToken)}createQualityLevels(){const t=this.packagedMedia?.playbackMp4s.permutations;if(!t)return[];const e=[],i=Ja({mp4Sources:t});return(t||[]).forEach(((t,s)=>{const r=Qa(i?t.source.dimensions.width:t.source.dimensions.height);r&&-1===e.map((t=>t.quality)).indexOf(r)&&e.push({mp4SourceIndex:s,quality:r})})),Za(e)}getInitialQualityLevel(){const t=eo();if(t){const e=this.host.qualityLevels.filter((e=>e.quality===t))[0]?.mp4SourceIndex;if(void 0!==e)return e}return-1}}class So{constructor(t){this.handleVisibilityChange=t=>{t||this.host.playOutOfViewport||this.host.pause("background"),t&&this.host.mediaVisibilityController.attemptAutoplay()},this.onBeforeUnload=()=>{this.host.pause("background")},(this.host=t).addController(this)}hostConnected(){t.ch(this.handleVisibilityChange),t.ax.subscribe(this.onBeforeUnload)}hostDisconnected(){t.ci(this.handleVisibilityChange),t.ax.unsubscribe(this.onBeforeUnload)}}class bo{constructor(){this.firstStartedAt=0,this.startedAt=null,this._laps=[],this._time=0}get paused(){return null===this.startedAt}get time(){if(this.paused)return this._time;const t=Date.now()-this.startedAt;return this._time+t}start(){this.firstStartedAt=this.firstStartedAt||Date.now(),this.paused&&(this.startedAt=Date.now())}pause(){this.paused||(this._time=this.time,this.startedAt=null)}reset(){this._laps=[],this.startedAt=null,this._time=0}lap(){const{_laps:t,time:e}=this,i=t[t.length-1],s={time:i?e-i.cumulativeTime:e,cumulativeTime:e};return t.push(s),s}}const Ao=[25,50,75,95,100],Lo=[2,3,5,10];function Ro(t){const{host:e}=t,{videoElement:s}=e,r=e.isHls?e.src:s.src,{hostname:n,pathname:a,id:o}=function(t){let e,i,s="";try{const r=new URL(t);if(e=r.hostname,i=r.pathname,"v.redd.it"===e){const t=i.split("/");s=t[1]||"";const e=t.findIndex((t=>"asset"===t)),r=-1!==e?e+1:-1;r>=0&&r=l?i.M.Landscape:i.M.Portrait;let c,u,f,g;e.isHls?(u=i.F.Hls,f=!!e.hlsController?.getCurAudioTrack(),c=e.hlsController.hls?.streamController?.fragCurrent?.byteRange):(u=i.F.Mp4,f=s?.mozHasAudio||Boolean(s?.webkitAudioDecodedByteCount)||Boolean(s?.audioTracks?.length)),Array.isArray(c)&&2===c.length&&(g=c[1]-c[0]);let m=i.a.VOD;e.gif&&(m=i.a.Gif),e.commentId&&!e.gif&&(m=i.a.Video);const p=ho.fullscreenElement===e||"fullscreen"===e.videoElement.webkitPresentationMode;return{duration:Math.round(1e3*s.duration),height:l,width:h,id:o,domain:n,orientation:d,origin:e.mediaOrigin,size:g,type:m,packaging_format:e.isHls?i.P.Hls:i.P.SingleFile,byte_range:Array.isArray(c)?c.toString():void 0,time:Math.round(1e3*s.currentTime),zoomed:p,format:u,has_audio:f,file_name:a,url:r,captions_present:e.mediaUI?.captionController?.captionsPresent}}function ko(t){const{host:e}=t;return{id:e.commentId}}function Co(){return{device_name:navigator.userAgent,os_name:navigator.platform,browser_name:navigator.userAgent,browser_version:navigator.appVersion}}function _o(e,{source:s,action:r,noun:n}){const{host:a}=e,{videoElement:o}=a,l=wo(e),h=l?`[${l.error_code}] ${l.error_message||l.reason||l.custom_response}`:void 0,d=a.hlsController?.getCurLevel()?.bitrate,c=a.hlsController?.getCurAudioTrack()?.bitrate,{height:u,width:f}=function(t){return{height:t?.clientHeight||0,width:t?.clientWidth||0}}(o),g=s===i.Q.Videoplayer&&r===i.b.Switch&&n===i.c.Bitrate;return{id:a.playbackId,sub_session_id:a.subSessionId,is_live:!1,is_looped:e.looped,state:Po(e),error:h,watch_duration_ms:Math.round(e.stopwatch.time),heartbeat_duration_ms:e.stopwatch.lap().time,playhead_offset_ms:Math.round(1e3*(o.duration-o.currentTime)),timestamp_ms:Math.round(1e3*o.currentTime),start_time_ms:e.stopwatch.firstStartedAt,volume:o.muted?0:Math.round(100*o.volume),total_bitrate:(d??0)+(c??0),video_bitrate:d,audio_bitrate:c,player_type:a.playerType??null,player_width:f,player_height:u,autoplay_setting:a.autoplay?i.A.Autoplay:i.A.Click,sequence_number:e.sequenceNumber+=1,user_bitrate_switch:g&&e.manualQualityChange,captions_enabled:a.mediaUI?.hasAttribute(t.gt.CAPTIONS_ENABLED)}}function Io(e){const{host:i}=e;return{created_timestamp:i.postCreatedAt?t.cv(i.postCreatedAt):void 0,domain:i.postDomain,id:i.postId||"",nsfw:!!i.postNsfw,promoted:!!i.postPromoted,score:i.postScore,spoiler:!!i.postSpoiler,subreddit_name:i.subredditName,subreddit_id:i.subredditId,type:i.postType}}function Do({instructionTimestamp:t}={}){return{event_timestamp:Date.now(),instruction_timestamp:t}}function wo(t){const{error:e}=t.host.videoElement,{errorController:i}=t.host;if(!e&&!i?.mediaErrorCode)return;return{reason:undefined,custom_response:undefined,error_code:i?.mediaErrorCode||e?.code,error_message:e?.message}}function Po(e){return e.host.mediaUI?.hasAttribute(t.gt.LOADING)?i.d.Buffering:e.host.mediaUI?.hasAttribute(t.gt.PLAYING)?i.d.Playing:e.host.mediaUI?.hasAttribute(t.gt.PAUSED)?i.d.Paused:i.d.Buffering}class xo{get complete(){return 0===this._thresholds.length}constructor(t){const e=Array.isArray(t)?Array.from(t):[t];this._thresholds=e.sort(((t,e)=>t-e))}test(t){const e=[];for(;!this.complete;){const i=this._thresholds[0];if(t=e?e/i:0);return t.watchPercentThresholdObserver?.test(s)}(this);for(const e of t||[])this.trackEvent({action:`watch_${e}_percent`,noun:i.e.Video});const e=function(t){if(t.watchSecondsThresholdObserver?.complete)return[];const e=t.stopwatch.time/1e3;return t.watchSecondsThresholdObserver?.test(e)}(this);for(const t of e||[])this.trackEvent({action:`watch_${t}_seconds`,noun:i.e.Video})}checkPlayedWithSound(){this.started&&!this._playedWithSound&&this._isAudible()&&(this._playedWithSound=!0,this.trackEvent({action:i.T.PlayWithSound,noun:i.e.Video}))}viewRecommendationOverlay(){this.trackEvent({action:i.b.View,noun:i.c.RecommendationOverlay})}tracePerformance(){if(this.host.isBot)return;const e=t.b({source:i.Q.Videoplayer,action:i.b.Trace,noun:i.c.Performance},{platform:Co(),video_performance_report:{loading_report:{file_load_started_timestamp:this.host.subSessionPlayStartTime,file_load_completed_timestamp:this.host.subSessionPlayingStartTime},playback_report:{session_id_v2:this.host.subSessionId}}});t.f(this.host,e)}trackEvent({source:e=i.Q.Videoplayer,action:s,noun:r}){if(this.host.isBot)return;const n=t.b({source:e,action:s,noun:r},{comment:ko(this),media:Ro(this),media_system_info:Do({instructionTimestamp:this.host.subSessionInstructionTime}),platform:Co(),playback:_o(this,{source:e,action:s,noun:r}),post:Io(this),subreddit:{name:this.host.subredditName,id:this.host.subredditId},video_error_report:wo(this)});t.f(this.host,n)}_isAudible(){const{videoElement:t}=this.host;return!t.muted&&t.volume>0}}const Oo=["click","pointerup","pointermove","focus","keydown","mouseleave"];class Fo{constructor(t){this.isIdle=!1,this._handleIdleChange=()=>{requestAnimationFrame((()=>{const t=this.host.mediaUI?.progressBar?.hasAttribute("dragging");return this.host.isMobile||this.host.matches(":hover")||t?!this.host.isMobile&&this.host.mediaUI?.controlBar?.matches(":hover")||t?(this._stopIdleTimer(),void this._setIdleState(!1)):void this._startIdleTimer():(this._stopIdleTimer(),void this._setIdleState(!0))}))},(this.host=t).addController(this)}async hostConnected(){this.host.gif||(Oo.forEach((t=>{this.host.addEventListener(t,this._handleIdleChange)})),this._startIdleTimer())}hostDisconnected(){this.host.gif||(Oo.forEach((t=>{this.host.removeEventListener(t,this._handleIdleChange)})),this._stopIdleTimer())}restartIdleTimer(){this._startIdleTimer()}_startIdleTimer(){this._stopIdleTimer(),this._idleTimeout=window.setTimeout((()=>{this._setIdleState(!0)}),1500)}_stopIdleTimer(){window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._setIdleState(!1)}_setIdleState(e){this.isIdle=e,this.host.mediaUI?.setAttr(t.gt.USER_IDLE,e)}}var No;!function(t){t.AVC="video/avc",t.VP9="video/vp9"}(No||(No={}));let Uo=s.cS({videoPlayerLabel:()=>"video player"});const{svg:$o}=e.g(),Bo=e.m($o``,"0 0 20 20","closed-caption-fill"),{svg:Go}=e.g(),Ho=e.m(Go``,"0 0 20 20","closed-caption"),{svg:Vo}=e.g(),Ko=e.m(Vo``,"0 0 20 20","pause-fill"),{svg:jo}=e.g(),Wo=e.m(jo``,"0 0 20 20","volume-on-fill",!0),Yo="@reddit/shreddit-player-media-captions";class zo{constructor(e){this.captionsPresent=!1,this.initializeCaptions=async()=>{if(!this.captionsEnabled())return;const{captionUrl:t,captionOverlay:e}=this.host;if(!t||!e?.captionsTarget)return void this._disableCaptionButton();const i=await this._requestCaptions();if(i?.ok){await async function(){"undefined"==typeof ResizeObserver&&(window.ResizeObserver=(await SML.di("./gXddY58AT3.js",import.meta.url,"gXddY58AT3"))?.default)}();const{CaptionsRenderer:t,parseResponse:s}=await SML.di("./By3M4InPRM.js",import.meta.url,"By3M4InPRM").then((function(t){return t.p})),r=await s(i);r?.cues?.length>0?(this.destroyCaptionsRenderer(),this.captionsRenderer=new t(e.captionsTarget),this.captionsRenderer.changeTrack(r),this.captionsPresent=!0,this._handleTimeUpdate(),this.videoElement?.addEventListener("timeupdate",this._handleTimeUpdate)):this._disableCaptionButton()}else this._disableCaptionButton()},this.captionsEnabled=()=>this.host.hasAttribute(t.gt.CAPTIONS_ENABLED),this.toggleCaptions=async()=>{const e=!this.captionsEnabled();var i;this.host.playerRoot?.telemetryController.clickCaptions(e),this.host.setAttr(t.gt.CAPTIONS_ENABLED,e),i=e,t.a0.setItem(Yo,i.toString()),e&&this.initializeCaptions()},this._disableCaptionButton=()=>{this.host.captionButton&&(this.host.captionButton.disabled=!0)},this._handleTimeUpdate=()=>{this.captionsRenderer&&(this.captionsRenderer.currentTime=this.videoElement?.currentTime||0)},this._requestCaptions=async()=>{const{captionUrl:e}=this.host;if(!e)return;const i=new Headers,s=this.host.playerRoot?.streamingAuthToken;return s&&i.set(t.kk,s),fetch(e,{headers:i})},(this.host=e).addController(this)}async hostConnected(){this.videoElement=this.host.videoElement,"true"===(t.a0.getItem(Yo)||"").toLowerCase()&&this.host.setAttr(t.gt.CAPTIONS_ENABLED)}hostDisconnected(){this.videoElement=void 0,this.captionsPresent=!1,this.destroyCaptionsRenderer()}destroyCaptionsRenderer(){this.captionsRenderer?.destroy(),this.captionsRenderer=void 0,this.videoElement?.removeEventListener("timeupdate",this._handleTimeUpdate)}}function qo(t,e){return t.toString().padStart(e,"0")}var Xo;function Qo(t){const e=Math.round(1e3*t)/1e3,i=Math.trunc(e/3600),s=Math.trunc(e%3600/60),r=Math.trunc(e%60),n=Number((e-Math.trunc(e)).toPrecision(3));return{[Xo.Hours]:i,[Xo.Minutes]:s,[Xo.Seconds]:r,[Xo.Fraction]:n}}function Jo(t,e=!1,i=!1){if(Number.isNaN(t))return"0:00";const{hours:s,minutes:r,seconds:n}=Qo(t),a=e?qo(s,2):s,o=qo(r,2),l=qo(n,2);return s>0||i?`${a}:${o}:${l}`:`${r}:${l}`}function Zo(t){const e=[],{hours:i,minutes:s,seconds:r}=Qo(t),n=(t,e)=>1===t?e:`${e}s`;return i>0&&e.push(`${i} ${n(i,"hour")}`),s>0&&e.push(`${s} ${n(s,"minute")}`),(r>0||0===e.length)&&e.push(`${r} ${n(r,"second")}`),e.join(", ")}function tl(t){return"number"==typeof t&&!Number.isNaN(t)}function el(t){return Math.round(10*t)/10}!function(t){t.Hours="hours",t.Minutes="minutes",t.Seconds="seconds",t.Fraction="fraction"}(Xo||(Xo={}));const{ENDED:il,ERROR:sl,FULLSCREEN:rl,MUTED:nl,PLAYING:al,PAUSED:ol,SHOW_POSTER:ll}=t.gt;class hl{constructor(t){this._logException=f,this._started=!1,this.handleWaiting=()=>{this.videoElement&&this.videoElement.readyState<3&&(this.host.showLoadingSpinner(),this._started&&this.host.playerRoot?.telemetryController.startRebuffer())},this.handlePlay=()=>{this.host.setAttr(ll,!1),this.host.setAttr(ol,!1),this.host.setAttr(il,!1)},this.handlePlaying=()=>{this._started=!0,this.host.hideLoadingSpinner(),this.host.setAttr(ll,!1),this.host.setAttr(al),this.host.setAttr(ol,!1),this.host.setAttr(il,!1),this.host.setAttr(sl,!1),this.host.playerRoot?.errorController?.resetRetryCount(),this.host.recommendationOverlayController.handlePlaying(),this.host.playerRoot&&(this.host.playerRoot.subSessionPlayingStartTime=this.host.playerRoot.subSessionPlayingStartTime||Date.now(),this.host.playerRoot.telemetryController.startVideo(),this.host.playerRoot.adController.play())},this.handlePause=()=>{this.host.setPausedState(),this.host.playerRoot?.adController.pause()},this.handleEnded=()=>{this.host.hideLoadingSpinner(),this.host.setAttr(il),this.host.setPausedState(),this.host.recommendationOverlayController.handleEnded(),this.host.playerRoot&&this.host.playerRoot.pause("ended")},this.handleLoadStart=()=>{this.host.setAttr(sl,!1)},this.handleLoadedData=()=>{this.host.setAttr(sl,!1),this.host.playerRoot?.errorController?.resetRetryCount()},this.handleCanPlay=()=>{this.host.hideLoadingSpinner(),this.host.setAttr(sl,!1),this.host.playerRoot?.errorController?.resetRetryCount()},this.handleError=()=>{this.host.hideLoadingSpinner()},this.handleVolumeChange=()=>{const{muted:t,volume:e}=this.videoElement||{};this.host.setAttr(nl,t||0===e),this.host.playerRoot?.volumeController.updateVolumeFillRate(),this.host.playerRoot?.adController.volumeChange()},this.handleFullscreenChange=t=>{t?.target===this.host.playerRoot&&(ho.fullscreenElement?this.host.setAttr(rl):this.host.setAttr(rl,!1),this.host.playerRoot?.adController.fullscreenChange())},this.handleTimeUpdate=()=>{tl(this.videoElement?.currentTime)&&tl(this.videoElement?.duration)&&(this.videoElement?.currentTime&&this.videoElement?.duration&&el(this.videoElement.currentTime)>=el(this.videoElement.duration)?this.host.setAttr(il):this.host.setAttr(il,!1),this.host.playerRoot?.telemetryController.timeUpdate(),this.host.playerRoot?.adController.timeUpdate(),this.host.recommendationOverlayController.handleTimeUpdate())},this.handleSeeking=()=>{this.host.playerRoot?.adController.seeking()},this.handleSeeked=()=>{this.host.playerRoot?.adController.seeked()},this.handlePresentationModeChange=()=>{const t="fullscreen"===this.videoElement?.webkitPresentationMode;this.host.setAttr(rl,t),this.host.playerRoot?.adController.fullscreenChange()},(this.host=t).addController(this)}hostConnected(){if(this.videoElement=this.host.videoElement,!this.videoElement){const t="MediaEventsController: videoElement is not defined";throw (this._logException({msg:t,debugOverlay:this.host.playerRoot?.debugOverlay}), new Error(t))}this.eventListeners.forEach((({eventName:t,callback:e})=>{this.videoElement?.addEventListener(t,e)})),ho.addEventListener("fullscreenchange",this.handleFullscreenChange)}hostDisconnected(){this.eventListeners.forEach((({eventName:t,callback:e})=>{this.videoElement?.removeEventListener(t,e)})),ho.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.videoElement=void 0,this._started=!1}get eventListeners(){return[{eventName:"play",callback:this.handlePlay},{eventName:"playing",callback:this.handlePlaying},{eventName:"pause",callback:this.handlePause},{eventName:"ended",callback:this.handleEnded},{eventName:"loadstart",callback:this.handleLoadStart},{eventName:"loadeddata",callback:this.handleLoadedData},{eventName:"canplay",callback:this.handleCanPlay},{eventName:"error",callback:this.handleError},{eventName:"volumechange",callback:this.handleVolumeChange},{eventName:"timeupdate",callback:this.handleTimeUpdate},{eventName:"seeking",callback:this.handleSeeking},{eventName:"seeked",callback:this.handleSeeked},{eventName:"webkitpresentationmodechanged",callback:this.handlePresentationModeChange},{eventName:"waiting",callback:this.handleWaiting},{eventName:"stalled",callback:this.handleWaiting}]}}class dl{constructor(e){this._isActivated=!1,this._activateFeature=t.j,this.handlePlaying=()=>{this.hideRecommendationOverlay()},this.handleEnded=()=>{this.showRecommendationOverlay()},this.handleTimeUpdate=()=>{const{currentTime:t,duration:e}=this.videoElement||{};tl(t)&&tl(e)&&this.isPostSupported()&&(e-t<=3&&this._activateRecommendedMediaOverlay(),el(t)>=el(e)?this.showRecommendationOverlay():this.hideRecommendationOverlay())},this._activateRecommendedMediaOverlay=async()=>{if(this._isActivated||!this.isPostSupported())return;this._isActivated=!0;const{postId:e,subredditId:i,isMobile:s,playerRoot:r}=this.host,n=this.host.playerRoot?.closest("shreddit-app")?.pageType;try{await this._activateFeature({name:t.kl,routeParams:{postId:e,subredditId:i,limit:s?"1":"4",navigationSessionId:r?.navigationSessionId,pageType:n},renderMode:t.P.Contents,root:r??void 0})}catch(t){this._isActivated=!1}},(this.host=e).addController(this)}hostConnected(){this.videoElement=this.host.videoElement}hostDisconnected(){this.videoElement=void 0}showRecommendationOverlay(){this.host.hasAttribute(t.gt.SHOW_RECOMMENDATION_OVERLAY)||(this.host.setAttr(t.gt.SHOW_RECOMMENDATION_OVERLAY),this.host.playerRoot?.telemetryController?.viewRecommendationOverlay())}hideRecommendationOverlay(){this.host.setAttr(t.gt.SHOW_RECOMMENDATION_OVERLAY,!1)}isPostSupported(){return Boolean(!this.host.playerRoot?.postPromoted&&!this.host.playerRoot?.gif&&!this.host.playerRoot?.loop&&!this.host.playerRoot?.hideControls&&this.host.playerRoot?.postId&&this.host.playerRoot?.subredditId)}}class cl{constructor(e){this._timeRAF=void 0,this.skipTime=t=>{this.currentTime+=t},this.setTime=t=>{this.currentTime=t},this._updateTimeProperties=()=>{tl(this.videoElement?.duration)&&(this._updateStyleProperties(),this._updateFormattedTime(),this.host.playerRoot?.adController.timeUpdate())},this._updateStyleProperties=()=>{if(!this.videoElement)return;const e=this.currentTime/this.videoElement.duration||0;this.host.style.setProperty(t.kh.PROGRESS_FILL_RATE,e.toFixed(4))},this._updateFormattedTime=()=>{if(!this.videoElement)return;const t=this.currentTime;if((this.formattedCurrentTime!==Jo(t)||this.formattedDuration!==Jo(this.videoElement.duration))&&(this.formattedCurrentTime=Jo(t),this.formattedDuration=Jo(this.videoElement.duration),this.host.currentTimeElement?.requestUpdate(),this.host.progressBar)){this.host.progressBar.ariaValueMax=this.formattedDuration,this.host.progressBar.ariaValueNow=this.formattedCurrentTime;const e=`${Zo(t)} out of ${Zo(this.videoElement.duration)}`;this.host.progressBar.ariaValueText=e}},this._cancelTimeUpdates=()=>{tl(this._timeRAF)&&window.cancelAnimationFrame(this._timeRAF),this._timeRAF=void 0},this._requestTimeUpdates=()=>{this._timeRAF||this._requestTimeUpdate()},this._requestTimeUpdate=()=>{this.videoElement&&(this._updateTimeProperties(),this._timeRAF=window.requestAnimationFrame((()=>{void 0!==this._timeRAF&&this._requestTimeUpdate()})))},(this.host=e).addController(this),this.host.style.setProperty(t.kh.PROGRESS_FILL_RATE,"0")}hostConnected(){this.videoElement=this.host.videoElement,this.host.gif||(this.videoElement?.addEventListener("loadedmetadata",this._updateTimeProperties),this.videoElement?.addEventListener("timeupdate",this._updateTimeProperties),this.videoElement?.addEventListener("playing",this._requestTimeUpdates),this.videoElement?.addEventListener("pause",this._cancelTimeUpdates))}hostDisconnected(){this.host.gif||(this.videoElement?.removeEventListener("loadedmetadata",this._updateTimeProperties),this.videoElement?.removeEventListener("timeupdate",this._updateTimeProperties),this.videoElement?.removeEventListener("playing",this._requestTimeUpdates),this.videoElement?.removeEventListener("pause",this._cancelTimeUpdates)),this._cancelTimeUpdates(),this.videoElement=void 0}get currentTime(){return Math.min(this.videoElement?.currentTime||0,this.videoElement?.duration||0)}set currentTime(t){this.videoElement&&(this.host.playerRoot?.telemetryController?.clickSeek(),this.videoElement.currentTime=t,this._updateTimeProperties())}get duration(){return this.videoElement?.duration||0}}const ul=({icon:i,onClick:s,disabled:r,ariaLabel:n,ariaKeyshortcuts:a,ariaHidden:o,additionalClasses:l=""})=>e.x` `,fl=({icon:t,additionalClasses:i="",size:s=e.I.Medium})=>t({attributes:{className:`text-white ease duration-150 ${i}`.trim()},size:s});var gl=e.i`:host{--slider-bg:#434343;--slider-fill:#fff;position:absolute;inset:0}.poster-play-button svg{filter:drop-shadow(3px 3px 2px rgba(0, 0, 0, .5));-webkit-filter:drop-shadow(3px 3px 2px rgba(0, 0, 0, .5))}:host(:not([show-poster]):not([gif])) .poster-play-button,:host([gif][playing]) .poster-play-button{display:none}:host(:not([show-poster])) .poster-play-button,:host([loading]) .poster-play-button{display:none}:host(:not([loading])) ::slotted([slot=loading-spinner]){display:none!important}:host([show-poster]) .controls{display:none}.scrim{background:linear-gradient(to top,rgba(0,0,0,.4) 40px,transparent 80px)}:host(:not([captions-enabled])) .caption-disabled-icon,:host(:not([fullscreen])) .expand-icon,:host(:not([muted])) .volume-icon,:host(:not([paused])) .pause-icon,:host([captions-enabled]) .caption-enabled-icon,:host([ended]) .refresh-icon,:host([fullscreen]) .collapse-icon,:host([muted]) .mute-icon,:host([paused]:not([ended])) .play-icon{display:inline-block}:host([user-idle]:not([paused])) .disappearing-controls,:host([user-idle]:not([paused])) .scrim{opacity:0;pointer-events:none}:host ::slotted([slot=recommendation-overlay]){transition:opacity .2s}:host([show-rec-overlay]) ::slotted([slot=recommendation-overlay]){opacity:1;visibility:visible;pointer-events:auto}:host(:not([show-rec-overlay])) ::slotted([slot=recommendation-overlay]){opacity:0;visibility:hidden;pointer-events:none}:host([captions-enabled]) shreddit-caption-overlay{display:block}:host(:not([captions-enabled])) shreddit-caption-overlay{display:none}:host([loading]) shreddit-caption-overlay,:host([show-poster]) shreddit-caption-overlay{display:none}:host(:not([error])) shreddit-error-overlay{display:none}`,ml=e.i`:where([data-part=captions]),:where([part=captions]){--overlay-padding:1%;--cue-color:white;--cue-bg-color:rgba(0, 0, 0, 0.75);--cue-font-size:16px;--cue-line-height:calc(var(--cue-font-size) * 1.2);--cue-padding-x:0.5rem;--cue-padding-y:0.5rem;position:absolute;inset:0;contain:content;margin:var(--overlay-padding);font-size:var(--cue-font-size);font-family:sans-serif;box-sizing:border-box;pointer-events:none;user-select:none;word-spacing:normal;word-break:break-word}:where([data-part=captions]>[data-part=cue-display]),:where([part=captions]>[part=cue-display]){position:absolute;bottom:0;direction:ltr;overflow:visible;contain:content;width:var(--cue-width,auto);height:var(--cue-height,auto);box-sizing:border-box;transform:var(--cue-transform);text-align:var(--cue-text-align);writing-mode:var(--cue-writing-mode,unset);white-space:pre-line;unicode-bidi:plaintext;min-width:min-content;min-height:min-content}:where([data-dir=rtl][data-part=cue-display]),:where([data-dir=rtl][part=cue-display]){direction:rtl}:where([data-part=captions]>[data-part=cue-display]>[data-part=cue]),:where([part=captions]>[part=cue-display]>[part=cue]){display:inline-block;padding:var(--cue-padding-y) var(--cue-padding-x);line-height:var(--cue-line-height);background-color:var(--cue-bg-color);box-sizing:border-box;color:var(--cue-color);box-shadow:var(--cue-box-shadow);white-space:var(--cue-white-space,pre-wrap);outline:var(--cue-outline);text-shadow:var(--cue-text-shadow)}:where([data-part=captions][data-part=cue-display][data-vertical][data-part=cue]),:where([part=captions][part=cue-display][data-vertical][part=cue]){padding:var(--cue-padding-x) var(--cue-padding-y)}`;let pl=class extends e.s{constructor(){super(...arguments),this.captionsTarget=document.createElement("div")}connectedCallback(){super.connectedCallback(),this.captionController?.initializeCaptions()}disconnectedCallback(){super.disconnectedCallback(),this.captionController?.destroyCaptionsRenderer(),this.captionsTarget.innerHTML=""}render(){return e.x`${this.captionsTarget}`}};pl.styles=[t.t,ml],t._([t.n()],pl.prototype,"captionController",void 0),pl=t._([t.e("shreddit-caption-overlay")],pl);let vl=class extends e.s{render(){return e.x` ${this.timeController?.formattedCurrentTime??"0:00"} / ${this.timeController?.formattedDuration??"0:00"} `}};vl.styles=[t.t],t._([t.n()],vl.prototype,"timeController",void 0),vl=t._([t.e("shreddit-current-time")],vl);let yl=class extends e.s{render(){if(void 0===this.mediaErrorCode)return;let t;return t=this.mediaErrorCode===MediaError.MEDIA_ERR_NETWORK?"This video is no longer available.":"This video cannot be played.",e.x`

    ${t}

    `;}};yl.styles=[t.t],t._([t.n({type:Number})],yl.prototype,"mediaErrorCode",void 0),yl=t._([t.e("shreddit-error-overlay")],yl);let El=class extends e.s{constructor(){super(...arguments),this.isMobile=!1,this.loadedPreviewVideo=!1,this._onCanPlay=()=>{this.videoElement.style.display="block"}}disconnectedCallback(){super.disconnectedCallback(),this.videoElement?.removeEventListener("canplay",this._onCanPlay)}loadPreviewVideo(){!this.loadedPreviewVideo&&this.videoElement&&(this.loadedPreviewVideo=!0,this.videoElement.load(),this.videoElement.addEventListener("canplay",this._onCanPlay))}render(){return e.x` ${this.isMobile||!this.preview?e.A:e.x` `} 0:00 `}};El.styles=[e.i`:host{display:inline-block;contain:content}:host(:not([preview])) video,:host([hidden]) video{display:none}`,t.t],t._([t.n({type:String})],El.prototype,"preview",void 0),t._([t.n({type:Boolean})],El.prototype,"isMobile",void 0),t._([t.v()],El.prototype,"loadedPreviewVideo",void 0),t._([t.Q("video")],El.prototype,"videoElement",void 0),t._([t.Q("span.formatted-current-time")],El.prototype,"formattedCurrentTime",void 0),El=t._([t.e("shreddit-preview-video-lazy")],El);let Tl=class extends e.s{constructor(){super(...arguments),this._isPointerDown=!1,this.idleUpdate=!1,this._handlePointerDown=e=>{t.km(e),this._isPointerDown=!0,this.onPointerDownMove?.(e),this.idleUpdate||this.onChange?.(e),this.dispatchEvent(new Event("slider-dragstart"))},this._handlePointerUp=e=>{this._isPointerDown&&(t.km(e),this._isPointerDown=!1,this.onChange?.(e),this.dispatchEvent(new Event("slider-dragend")))},this._handlePointerMove=e=>{this._isPointerDown&&(t.km(e),this.onPointerDownMove?.(e),this.idleUpdate||this.onChange?.(e))}}connectedCallback(){super.connectedCallback(),document.addEventListener("pointerup",this._handlePointerUp),document.addEventListener("pointercancel",this._handlePointerUp),document.addEventListener("pointermove",this._handlePointerMove)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("pointerup",this._handlePointerUp),document.removeEventListener("pointercancel",this._handlePointerUp),document.removeEventListener("pointermove",this._handlePointerMove)}render(){return e.x` `}};Tl.styles=[t.t],t._([t.n({type:Boolean})],Tl.prototype,"idleUpdate",void 0),t._([t.n()],Tl.prototype,"onChange",void 0),t._([t.n()],Tl.prototype,"onPointerDownMove",void 0),t._([t.n()],Tl.prototype,"additionalClasses",void 0),Tl=t._([t.e("shreddit-slider-element")],Tl);let Sl=class extends e.s{constructor(){super(...arguments),this.isMobile=!1,this._updateTime=t=>{const{left:e,width:i}=this.getBoundingClientRect(),s=Math.min((t.x-e)/i,1),r=(this.timeController?.duration??0)*s;Number.isNaN(r)||(this.timeController.currentTime=r)},this._handleSliderChange=t=>{this._updateTime(t),this._updatePreviewVideoPosition(t)},this._handleDragStart=()=>{this.setAttribute("dragging","")},this._handleDragEnd=()=>{this.removeAttribute("dragging")},this._handlePointerDownMove=t=>{this._updateSliderBallPosition(t),this._updatePreviewVideoPosition(t)},this._handleMouseEnter=()=>{this.isMobile||this.setAttribute("hovered","")},this._handleMouseLeave=()=>{this.isMobile||this.removeAttribute("hovered")},this._updateSliderBallPosition=e=>{const{left:i,width:s}=this.getBoundingClientRect(),r=Math.max(0,Math.min(e.x-i,s));this.style.setProperty(t.kh.SLIDER_BALL_LEFT_PX,`${r}px`)},this._updatePreviewVideoPosition=e=>{const{left:i,width:s}=this.getBoundingClientRect(),r=Math.max(0,Math.min((e.x-i)/s,1)),n=(this.timeController?.duration||0)*r;this.previewVideoLazy?.loadPreviewVideo(),this.previewVideoLazy?.videoElement&&(this.previewVideoLazy.videoElement.currentTime=n),this.previewVideoLazy?.formattedCurrentTime&&(this.previewVideoLazy.formattedCurrentTime.innerText=Jo(n));const a=Math.max(0,Math.min(e.x-i,s));this.previewVideoLazy?.style.setProperty(t.kh.PREVIEW_VIDEO_LEFT_PX,`${a}px`)}}renderPreviewVideo(){return e.x` `}render(){return e.x`
    ${this.renderPreviewVideo()} `}};Sl.styles=[e.i`:host shreddit-preview-video-lazy{display:none}:host([dragging]) shreddit-preview-video-lazy,:host([hovered]) shreddit-preview-video-lazy{display:flex}:host(:not([dragging])) shreddit-slider-element .slider-ball{left:calc(var(--progress-fill-rate) * 100%)}:host([dragging]) shreddit-slider-element .slider-ball{left:var(--slider-ball-left-px)}`,t.t],t._([t.n()],Sl.prototype,"timeController",void 0),t._([t.n({type:String})],Sl.prototype,"preview",void 0),t._([t.n({type:Boolean})],Sl.prototype,"isMobile",void 0),t._([t.Q("shreddit-preview-video-lazy")],Sl.prototype,"previewVideoLazy",void 0),Sl=t._([t.e("shreddit-progress-bar")],Sl);let bl=class extends e.s{constructor(){super(...arguments),this.autoplayPref=!1,this.isLoggedInUser=!1,this.hideAutoplayToggle=!1,this.qualityLevels=[],this.currentQualityLevelIndex=-1,this.rootSelector="shreddit-player",this.isMenuOpen=!1}showSettings(){this.isMenuOpen=!0}hideSettings(){this.isMenuOpen=!1}handleQualityChange(e,i){e.stopPropagation();const s=i?"hlsLevelIndex"in i?i.hlsLevelIndex:i.mp4SourceIndex:-1;var r;this.mediaActionsController?.setQualityLevel(s),r=i?.quality,r?t.a0.setItem(Xa,r.toString()):t.a0.removeItem(Xa);const n=t.bx(this,this.rootSelector);n&&(n.telemetryController.manualQualityChange=!0)}renderSettings(){const i=t=>this.currentQualityLevelIndex===("hlsLevelIndex"in t?t.hlsLevelIndex:t.mp4SourceIndex),s="px-sm py-xs flex justify-center border-none bg-transparent cursor-pointer text-white",r=this.isLoggedInUser&&!this.hideAutoplayToggle,n=e.x` ${r?e.x`
    `:e.A} `;return e.x`
    ${n} ${this.qualityLevels?.map((t=>e.x` `))}
    `;}renderCheckmark(t){return t?e.x` ${e.C({size:e.I.ExtraSmall})} `:e.A}render(){return e.x`
    ${ul({icon:fl({icon:h.s}),onClick:()=>this.isMenuOpen?this.hideSettings():this.showSettings(),ariaLabel:"Settings"})} ${this.renderSettings()}
    `;}};bl.styles=[e.i`:host{position:relative}`,t.t],t._([t.n()],bl.prototype,"mediaActionsController",void 0),t._([t.n({type:Boolean})],bl.prototype,"autoplayPref",void 0),t._([t.n({type:Boolean})],bl.prototype,"isLoggedInUser",void 0),t._([t.n({type:Boolean,attribute:"hide-autoplay-toggle"})],bl.prototype,"hideAutoplayToggle",void 0),t._([t.n()],bl.prototype,"qualityLevels",void 0),t._([t.n()],bl.prototype,"currentQualityLevelIndex",void 0),t._([t.n({type:String})],bl.prototype,"rootSelector",void 0),t._([t.v()],bl.prototype,"isMenuOpen",void 0),bl=t._([t.e("shreddit-video-settings")],bl);let Al=class extends e.s{constructor(){super(...arguments),this.isMobile=!1,this._updateVolume=e=>{t.km(e);const{height:i=0,y:s=0}=this.sliderTrack?.getBoundingClientRect()??{};if(!i)return;const r=Math.min(1,Math.max(0,(s+i-e.y)/i));this.mediaActionsController?.setVolume(r)}}render(){const i=this.isMobile?e.A:e.x`
    `;return e.x`
    ${i}
    `}};Al.styles=[e.i`:host .slider-element-wrapper{display:none}:host(:hover) .slider-element-wrapper{display:block}`,t.t],t._([t.n()],Al.prototype,"mediaActionsController",void 0),t._([t.n({type:Boolean})],Al.prototype,"isMobile",void 0),t._([t.Q(".slider-track")],Al.prototype,"sliderTrack",void 0),Al=t._([t.e("shreddit-volume-slider")],Al);let Ll=class extends e.s{constructor(){super(...arguments),this.mediaEventsController=new hl(this),this.timeController=new cl(this),this.captionController=new zo(this),this.recommendationOverlayController=new dl(this),this.autoplay=!1,this.autoplayPref=!1,this.gif=!1,this.hideControls=!1,this.hideFullscreenButton=!1,this.hideAutoplayToggle=!1,this.isMobile=!1,this.isLoggedInUser=!1,this.qualityLevels=[],this.currentQualityLevelIndex=-1,this.hideGifIcon=!1,this.rootSelector="shreddit-player",this.gifToggle=t=>{this.mediaActionsController?.togglePlay(),t.stopImmediatePropagation(),t.preventDefault()},this.renderGifControls=()=>e.x`${this.autoplay?e.A:e.x`${this.renderPosterPlayButton()}
    ${ul({icon:e.x` ${fl({icon:a.p,additionalClasses:"hidden play-icon"})} ${fl({icon:Ko,additionalClasses:"hidden pause-icon"})} `,additionalClasses:"absolute left-0 bottom-0",onClick:t=>this.gifToggle(t)})}
    `} ${this.hideGifIcon?e.A:ul({icon:fl({icon:a.g}),disabled:!0,ariaHidden:!0,additionalClasses:"absolute right-0 bottom-0"})} ${this.renderErrorOverlay()}`}connectedCallback(){super.connectedCallback(),this.autoplay||this.playerRoot?.hasHadPlayAttempt||(this.showPoster(),this.setPausedState())}disconnectedCallback(){super.disconnectedCallback(),this.hideLoadingSpinner()}get playerRoot(){return t.bx(this,this.rootSelector)}renderPosterPlayButton(){return ul({icon:e.x` ${fl({icon:a.p,size:e.I.ExtraLarge})} `,onClick:t=>{t?.preventDefault(),t?.stopImmediatePropagation(),this.mediaActionsController?.play()},ariaLabel:"Play",additionalClasses:"poster-play-button absolute inset-0 flex items-center justify-center cursor-pointer pointer-events-auto"});}showPoster(){this.setAttr(t.gt.SHOW_POSTER)}showLoadingSpinner(){this.hasAttribute(t.gt.LOADING)||(this._loadingSpinnerRAF=requestAnimationFrame((()=>{this.videoElement&&this.videoElement.readyState<3&&this.setAttr(t.gt.LOADING)})))}hideLoadingSpinner(){this._loadingSpinnerRAF&&(cancelAnimationFrame(this._loadingSpinnerRAF),this._loadingSpinnerRAF=void 0),this.hasAttribute(t.gt.LOADING)&&requestAnimationFrame((()=>{this.setAttr(t.gt.LOADING,!1)}))}renderCaptionOverlay(){return e.x``}renderControls(){if(this.hideControls)return;const t=ul({icon:e.x` ${fl({icon:a.p,additionalClasses:"hidden play-icon"})} ${fl({icon:Ko,additionalClasses:"hidden pause-icon"})} ${fl({icon:l.r,additionalClasses:"hidden refresh-icon"})} `,onClick:this.mediaActionsController?.togglePlay,ariaLabel:"Toggle playback",ariaKeyshortcuts:"k",additionalClasses:"play-pause-button"}),i=e.x` `,s=e.x` `,h=this.isMobile?e.x``:e.x` `,d=ul({icon:e.x` ${fl({icon:n.e,additionalClasses:"hidden expand-icon"})} ${fl({icon:r.c,additionalClasses:"hidden collapse-icon"})} `,onClick:this.mediaActionsController?.toggleFullscreen,ariaLabel:"Toggle fullscreen",ariaKeyshortcuts:"f",additionalClasses:"fullscreen-button "+(this.hideFullscreenButton?"invisible":"")}),c=ul({additionalClasses:"embed-s:hidden caption-button",icon:e.x` ${fl({icon:Bo,additionalClasses:"hidden caption-enabled-icon"})} ${fl({icon:Ho,additionalClasses:"hidden caption-disabled-icon"})} `,onClick:this.mediaActionsController?.toggleCaptions,ariaLabel:"Toggle captions",ariaKeyshortcuts:"c"}),u=e.x` ${ul({icon:e.x` ${fl({icon:Wo,additionalClasses:"hidden volume-icon"})} ${fl({icon:o.v,additionalClasses:"hidden mute-icon"})} `,onClick:this.mediaActionsController?.toggleMute,ariaLabel:"Toggle volume",ariaKeyshortcuts:"m",additionalClasses:"mute-button"})} `;return e.x`
    ${""}
    ${t} ${i} ${s} ${c} ${h} ${d}
    ${""}
    ${u}
    `}renderRecommendationOverlay(){return e.x``}renderErrorOverlay(){return e.x` `}setPausedState(){this.setAttr(t.gt.PAUSED),this.setAttr(t.gt.PLAYING,!1),this.hideLoadingSpinner()}setAttr(t,e=!0){!1===e?this.removeAttribute(t):this.setAttribute(t,!0===e?"":e)}render(){return e.x` ${this.gif?this.renderGifControls():e.x` ${this.renderPosterPlayButton()} ${this.renderCaptionOverlay()} ${this.renderErrorOverlay()} ${this.renderRecommendationOverlay()} ${this.renderControls()} `} `}};Ll.styles=[gl,t.t],t._([t.n()],Ll.prototype,"videoElement",void 0),t._([t.n()],Ll.prototype,"mediaActionsController",void 0),t._([t.n({type:Boolean})],Ll.prototype,"autoplay",void 0),t._([t.n({type:Boolean})],Ll.prototype,"autoplayPref",void 0),t._([t.n({type:Boolean})],Ll.prototype,"gif",void 0),t._([t.n({type:Boolean})],Ll.prototype,"hideControls",void 0),t._([t.n({type:Boolean})],Ll.prototype,"hideFullscreenButton",void 0),t._([t.n({type:Boolean,attribute:"hide-autoplay-toggle"})],Ll.prototype,"hideAutoplayToggle",void 0),t._([t.n({type:Boolean})],Ll.prototype,"isMobile",void 0),t._([t.n({type:Boolean})],Ll.prototype,"isLoggedInUser",void 0),t._([t.n({type:String,attribute:"caption-url"})],Ll.prototype,"captionUrl",void 0),t._([t.n({type:String})],Ll.prototype,"preview",void 0),t._([t.n()],Ll.prototype,"qualityLevels",void 0),t._([t.n()],Ll.prototype,"currentQualityLevelIndex",void 0),t._([t.n()],Ll.prototype,"postId",void 0),t._([t.n()],Ll.prototype,"subredditId",void 0),t._([t.n({type:Boolean})],Ll.prototype,"hideGifIcon",void 0),t._([t.n({type:String})],Ll.prototype,"rootSelector",void 0),t._([t.Q(".control-bar")],Ll.prototype,"controlBar",void 0),t._([t.Q("shreddit-current-time")],Ll.prototype,"currentTimeElement",void 0),t._([t.Q("shreddit-progress-bar")],Ll.prototype,"progressBar",void 0),t._([t.Q("shreddit-video-settings")],Ll.prototype,"videoSettings",void 0),t._([t.Q("shreddit-caption-overlay")],Ll.prototype,"captionOverlay",void 0),t._([t.Q(".caption-button")],Ll.prototype,"captionButton",void 0),t._([t.Q("shreddit-error-overlay")],Ll.prototype,"errorOverlay",void 0),Ll=t._([t.e("shreddit-media-ui")],Ll);let Rl=class extends e.s{constructor(){super(...arguments),this.debugLogs=[]}log(t,e){this.debugLogs.push({key:t,value:e}),this.requestUpdate()}render(){return e.x`

    Debug info

    ${this.debugLogs.map((t=>e.x`
    ${t.key}
    ${t.value}
    `))}
    `}};Rl.styles=[t.t,e.i`:host{position:absolute;top:0;left:0;right:0;bottom:50px;max-height:100%;overflow-y:auto}`],t._([t.n({type:Array})],Rl.prototype,"debugLogs",void 0),Rl=t._([t.e("shreddit-player-debug-overlay")],Rl),(({country:e,_setCookie:i=t.B})=>{const s=t.kj;if(!e||!t.aI({country:e,name:s}))return;i({name:s,value:function(){const t=document.createElement("video"),e=[];""!==t.canPlayType('video/mp4; codecs="avc1.42E01E"')&&e.push(No.AVC);""!==t.canPlayType('video/webm; codecs="vp9"')&&e.push(No.VP9);return e}().join(","),options:t.D,country:e})})({country:document.querySelector("shreddit-app")?.getAttribute("country")??void 0});const kl="shreddit-player";let Cl=class extends e.s{constructor(){super(...arguments),this.playbackId=t.a3(),this.subSessionId=t.a3(),this.navigationSessionId=t.a3(),this.videoElement=document.createElement("video"),this.initialized=!1,this.rootSelector=kl,this.hasHadPlayAttempt=!1,this.playCount=0,this._disconnected=!1,this.errorControllerLegacy=new m(this),this.errorControllerNew=new y(this),this.hlsController=new io(this),this.mediaActionsController=new co(this),this.mediaSyncController=new vo(this),this.mediaVisibilityController=new yo(this),this.packagedMediaController=new To(this),this.telemetryController=new Mo(this),this.adController=new c(this),this.userIdleController=new Fo(this),this.volumeController=new mo(this),this.gestureController=new E(this),this.mediaHotkeyController=new uo(this),this.pageController=new So(this),this.src="",this.autoplay=!1,this.autoplayPref=!1,this.hideAutoplayToggle=!1,this.gif=!1,this.loop=!1,this.hideControls=!1,this.hideFullscreenButton=!1,this.isMobile=!1,this.isBot=!1,this.poster="",this.isLoggedInUser=!1,this.singlePlayback=!1,this.playOutOfViewport=!1,this.objectFit="contain",this.shouldRoundBackground=!1,this.errorImprovements=!1,this.idleAutoplay=!1,this.hideGifIcon=!1,this.debug=!1,this.qualityLevels=[],this.currentQualityLevelIndex=-1}connectedCallback(){super.connectedCallback(),this.videoElement.poster=this.poster,this._disconnected&&this.reconnect()}disconnectedCallback(){this.stop(),this._disconnected=!0,this.initialized=!1,super.disconnectedCallback()}firstUpdated(){this.volumeController.setInitialVolumeSetting()}reconnect(){this.adController.fromReconnect=!0,this.autoplay||this.mediaUI?.setPausedState(),this._disconnected=!1}get isMp4(){return this.packagedMediaController.hasPackagedMedia}get isHls(){return this.hlsController.isHlsStream&&!this.isMp4}get errorController(){return this.errorImprovements?this.errorControllerNew:this.errorControllerLegacy}shouldUseFakePosterImage(){return this.gif&&!this.autoplay&&!this.poster}initializeVideoElement(){if(this.initialized)return;this.initialized=!0,this.isMp4&&this.packagedMediaController.initialize(),this.isMp4||this.isHls||(this.videoElement.src=this.src),this._restoreVideoTime(),this.videoElement.playsInline=!0;this.shouldUseFakePosterImage()?(this.videoElement.preload=t.kf.AUTO,this.videoElement.src=this.videoElement.src.concat("#t=.01")):this.videoElement.preload=t.kf.NONE,this.videoElement.tabIndex=-1,this.videoElement.setAttribute("aria-label",String(Uo.videoPlayerLabel())),this.videoElement.style.objectFit=this.objectFit,this.shouldRoundBackground&&this.videoElement.classList.add("rounded-4"),this.stoppedState=void 0}async play(t=!1){return this.mediaActionsController.play(t)}async load(e=t.kf.AUTO){return this.mediaActionsController.load(e)}pause(t){return this.mediaActionsController.pause(t)}stop(){this.mediaActionsController.stop()}updateSubSession(){this.subSessionId=t.a3(),this.hlsController.updateCmcdSessionId(this.subSessionId),this.subSessionInstructionTime=void 0,this.subSessionPlayStartTime=void 0,this.subSessionPlayingStartTime=void 0}hideRecommendationOverlay(){this.mediaUI?.recommendationOverlayController?.hideRecommendationOverlay()}_restoreVideoTime(){!this.videoElement.currentTime&&this.stoppedState?.currentTime&&(this.videoElement.currentTime=this.stoppedState?.currentTime)}render(){return e.x` ${this.videoElement} ${this.debug?e.x``:e.A} `}};return Cl.styles=[e.i`:host{display:block;position:relative;height:100%;width:100%;max-height:100%;max-width:100%}video{height:100%;width:100%;background:#000;outline:0}`,t.t],t._([t.n()],Cl.prototype,"src",void 0),t._([t.n({type:Boolean,reflect:!0})],Cl.prototype,"autoplay",void 0),t._([t.n({type:Boolean,attribute:"autoplay-pref"})],Cl.prototype,"autoplayPref",void 0),t._([t.n({type:Boolean,attribute:"hide-autoplay-toggle"})],Cl.prototype,"hideAutoplayToggle",void 0),t._([t.n({type:Boolean})],Cl.prototype,"gif",void 0),t._([t.n({type:Boolean,attribute:"loop"})],Cl.prototype,"loop",void 0),t._([t.n({type:Number,attribute:"loop-limit"})],Cl.prototype,"loopLimit",void 0),t._([t.n({type:Boolean,attribute:"hide-controls"})],Cl.prototype,"hideControls",void 0),t._([t.n({type:Boolean,attribute:"hide-fullscreen-button"})],Cl.prototype,"hideFullscreenButton",void 0),t._([t.n({type:Boolean,attribute:"is-mobile"})],Cl.prototype,"isMobile",void 0),t._([t.n({type:Boolean,attribute:"is-bot"})],Cl.prototype,"isBot",void 0),t._([t.n({type:String})],Cl.prototype,"poster",void 0),t._([t.n({type:String,attribute:"post-id"})],Cl.prototype,"postId",void 0),t._([t.n({type:String,attribute:"comment-id"})],Cl.prototype,"commentId",void 0),t._([t.n({type:String})],Cl.prototype,"preview",void 0),t._([t.n({type:Boolean,attribute:"is-logged-in-user"})],Cl.prototype,"isLoggedInUser",void 0),t._([t.n({type:Boolean,attribute:"single-playback"})],Cl.prototype,"singlePlayback",void 0),t._([t.n({type:Boolean,attribute:"play-out-of-viewport"})],Cl.prototype,"playOutOfViewport",void 0),t._([t.n({type:String,attribute:"object-fit"})],Cl.prototype,"objectFit",void 0),t._([t.n({type:Boolean,attribute:"should-round-background"})],Cl.prototype,"shouldRoundBackground",void 0),t._([t.n({type:String,attribute:"packaged-media-json"})],Cl.prototype,"packagedMediaJSON",void 0),t._([t.n({type:String,attribute:"packaged-auth-token",reflect:!0})],Cl.prototype,"packagedAuthToken",void 0),t._([t.n({type:String,attribute:"packaged-auth-expires-at",reflect:!0})],Cl.prototype,"packagedAuthExpiresAt",void 0),t._([t.n({type:String,attribute:"streaming-auth-token",reflect:!0})],Cl.prototype,"streamingAuthToken",void 0),t._([t.n({type:String,attribute:"streaming-auth-expires-at",reflect:!0})],Cl.prototype,"streamingAuthExpiresAt",void 0),t._([t.n({type:String,attribute:"caption-url"})],Cl.prototype,"captionUrl",void 0),t._([t.n({attribute:"media-origin"})],Cl.prototype,"mediaOrigin",void 0),t._([t.n({attribute:"player-type"})],Cl.prototype,"playerType",void 0),t._([t.n({attribute:"post-created-at"})],Cl.prototype,"postCreatedAt",void 0),t._([t.n({attribute:"post-domain"})],Cl.prototype,"postDomain",void 0),t._([t.n({type:Boolean,attribute:"post-nsfw"})],Cl.prototype,"postNsfw",void 0),t._([t.n({type:Boolean,attribute:"post-promoted"})],Cl.prototype,"postPromoted",void 0),t._([t.n({type:Boolean,attribute:"post-spoiler"})],Cl.prototype,"postSpoiler",void 0),t._([t.n({type:Number,attribute:"post-score"})],Cl.prototype,"postScore",void 0),t._([t.n({attribute:"post-type"})],Cl.prototype,"postType",void 0),t._([t.n({attribute:"subreddit-name"})],Cl.prototype,"subredditName",void 0),t._([t.n({attribute:"subreddit-id"})],Cl.prototype,"subredditId",void 0),t._([t.n({type:Boolean,attribute:"error-improvements"})],Cl.prototype,"errorImprovements",void 0),t._([t.n({type:Boolean,attribute:"idle-autoplay"})],Cl.prototype,"idleAutoplay",void 0),t._([t.n({type:Boolean,attribute:"hide-gif-icon"})],Cl.prototype,"hideGifIcon",void 0),t._([t.n({type:Boolean,attribute:"debug"})],Cl.prototype,"debug",void 0),t._([t.v()],Cl.prototype,"qualityLevels",void 0),t._([t.v()],Cl.prototype,"currentQualityLevelIndex",void 0),t._([t.Q("shreddit-media-ui")],Cl.prototype,"mediaUI",void 0),t._([t.Q("shreddit-player-debug-overlay")],Cl.prototype,"debugOverlay",void 0),Cl=t._([t.e(kl)],Cl),{SELECTOR:t.ez,TAG_NAMES:t.bj,get ShredditPlayer(){return Cl},setUiStrings:t=>{Uo=t}}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./By3M4InPRM.js",import.meta.url,"By3M4InPRM"); SML.dm("ChVzN5arel",["CsxDAjmHZE","By3M4InPRM"],(async(e,n)=>{const{svg:a}=e.g(),t=e.m(a``,"0 0 20 20","settings-fill"),i=/,/g;class l extends n.V{parse(e,a){if(""===e)this.a&&(this.j.push(this.a),this.f.onCue?.(this.a),this.a=null),this.c=n.a.None;else if(this.c===n.a.Cue)this.a.text+=(this.a.text?"\n":"")+e;else if(e.includes("--\x3e")){const t=this.o(e,a);t&&(this.a=new n.b(t[0],t[1],t[2].join(" ")),this.a.id=this.l,this.c=n.a.Cue)}this.l=e}o(e,n){return super.o(e.replace(i,"."),n)}}var s=Object.freeze({__proto__:null,SRTParser:l,default:function(){return new l}});const o={p:()=>new n.P({code:n.c.BadSignature,reason:"missing WEBVTT file header",line:1}),q:(e,a)=>new n.P({code:n.c.BadTimestamp,reason:`cue start timestamp \`${e}\` is invalid on line ${a}`,line:a}),r:(e,a)=>new n.P({code:n.c.BadTimestamp,reason:`cue end timestamp \`${e}\` is invalid on line ${a}`,line:a}),s:(e,a,t)=>new n.P({code:n.c.BadTimestamp,reason:`cue end timestamp \`${a}\` is greater than start \`${e}\` on line ${t}`,line:t}),w:(e,a,t)=>new n.P({code:n.c.BadSettingValue,reason:`invalid value for cue setting \`${e}\` on line ${t} (value: ${a})`,line:t}),v:(e,a,t)=>new n.P({code:n.c.UnknownSetting,reason:`unknown cue setting \`${e}\` on line ${t} (value: ${a})`,line:t}),u:(e,a,t)=>new n.P({code:n.c.BadSettingValue,reason:`invalid value for region setting \`${e}\` on line ${t} (value: ${a})`,line:t}),t:(e,a,t)=>new n.P({code:n.c.UnknownSetting,reason:`unknown region setting \`${e}\` on line ${t} (value: ${a})`,line:t}),N:(e,a)=>new n.P({code:n.c.BadFormat,reason:`format missing for \`${e}\` block on line ${a}`,line:a})};var r=Object.freeze({__proto__:null,ParseErrorBuilder:o});return{get a(){return s},get e(){return r},s:t}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q");SML.di("./tmkhvHLxT3.js",import.meta.url,"tmkhvHLxT3"); SML.dm("Cj45kFzx5i",["C42E8rVVpA","BFDJQElz9q","tmkhvHLxT3"],(async(i,a,r)=>{var t;!function(i){i.Forward="forward",i.Backward="backward"}(t||(t={}));const e=(r,t,e)=>i.b({source:"gallery",action:"view",noun:"media"},{...a.g(r),gallery:{num_items:e,position:t}}),n=(r,t,e,n)=>i.b({source:"gallery",action:"click",noun:t},{...a.g(r),gallery:{num_items:n,position:e}});return{get G(){return t},a:e,g:n,h:(a,o,m)=>{const d=n(a,o.detail.direction===r.C.FORWARDS?t.Forward:t.Backward,o.detail.prevPositionIndex,o.detail.num_items),s=e(a,o.detail.currPositionIndex,o.detail.num_items);m&&(d.ad_metadata={impression_id:m},s.ad_metadata={impression_id:m}),i.f(a,d),i.f(a,s)}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./7ymiBBk8xO.js",import.meta.url,"7ymiBBk8xO");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./CZFRGXDPUQ.js",import.meta.url,"CZFRGXDPUQ"); SML.dm("ClL48310I8",["C42E8rVVpA","7ymiBBk8xO","CsxDAjmHZE","CZFRGXDPUQ"],(async(e,t,a)=>{SML.di("./D_F1vtGIq1.js",import.meta.url,"D_F1vtGIq1"),SML.di("./5YOkNVVwii.js",import.meta.url,"5YOkNVVwii"),SML.di("./CZU1X6W5t6.js",import.meta.url,"CZU1X6W5t6");let i=e.C,o=class extends a.s{static get styles(){return[e.t]}constructor(){super(),this.isUserLoggedIn=!1,this.postId="",this.shouldShowPollCoachmark=!1,this.voteRequestPending=!1,this.isHidden=!1,this.pollCoachmarkRef=e.U(),this.handleInput=e=>{this.selectedOptionId=e.target?.value,this._button?.removeAttribute("disabled")},this.handleShowCoachmark=e=>{e.preventDefault(),this.showPollCoachmark()},this.handleCoachmarkButtonClick=e=>{e.target.closest('[data-action="show-poll-coachmark"]')&&(e.stopPropagation(),this.showPollCoachmark())},this.handleVote=async()=>{if(e.f(this,e.b({source:"post",action:"click",noun:"vote"})),this.isUserLoggedIn)try{this.voteRequestPending=!0;const t=await this.makeVoteRequest();this.voteRequestPending=!1,t?.data?.updatePostPollVoteState?.ok?(this.isHidden=!0,await this.reloadPollPost()):this.handleVoteError(e.b8.QueryBadResponse)}catch(t){this.handleVoteError(e.bt(t))}},this.reloadPollPost=async()=>{e.p(e.T.PostUpdated,{postId:this.postId,action:t.a.updateContent,value:!0})},this._button=this.querySelector("button")}connectedCallback(){super.connectedCallback(),this._button?.addEventListener("click",this.handleVote),this.addEventListener("show-poll-coachmark",this.handleShowCoachmark),this.addEventListener("click",this.handleCoachmarkButtonClick,!0),this.shouldShowPollCoachmark&&this.showPollCoachmark()}disconnectedCallback(){super.disconnectedCallback(),this._button?.removeEventListener("click",this.handleVote),this.removeEventListener("show-poll-coachmark",this.handleShowCoachmark),this.removeEventListener("click",this.handleCoachmarkButtonClick,!0)}redirect(e){window.location.href=e}async makeVoteRequest(){return i({operation:e.H.UpdatePostPollVoteState,variables:{input:{postId:this.postId,optionId:this.selectedOptionId}}})}handleVoteError(t){this.voteRequestPending=!1,this.dispatchEvent(e.c("faceplate-alert",{level:e.X.error,message:"Something went wrong",cause:t}))}showPollCoachmark(){const e=this.querySelector("#poll-legend-anchor"),t=this.pollCoachmarkRef.value;t&&e&&(t.anchor=e,t.show())}render(){return this.isHidden?"":a.x` ${this.voteRequestPending?a.x`
    ${a.U({attributes:{className:"animate-spin"},size:a.I.Medium})}
    `:""}
    ${"Who are core contributors?"}
    ${"Core contributors have visited or contributed to this community consistently in the past month."}
    ${e.Z({attributes:{slot:"close-button",id:"close-poll-coachmark-button"},leadingIcon:a.c(),appearance:"plainInverted",size:e.ac.Small})}
    `;}};return e._([e.aC({context:e.b3}),e.n({attribute:!1})],o.prototype,"isUserLoggedIn",void 0),e._([e.n({type:String,attribute:"post-id"})],o.prototype,"postId",void 0),e._([e.n({attribute:!1})],o.prototype,"selectedOptionId",void 0),e._([e.n({type:Boolean,attribute:"show-poll-coachmark"})],o.prototype,"shouldShowPollCoachmark",void 0),e._([e.v()],o.prototype,"voteRequestPending",void 0),o=e._([e.e("shreddit-post-poll")],o),{get ShredditPostPoll(){return o}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("Cm1OoSEr5r",["C42E8rVVpA"],(async t=>{var e,i;!function(t){t.FocusSearchBar="focusSearchBar",t.RegisterAuth="registerAuth",t.UpvoteAuth="upvoteAuth"}(e||(e={})),function(t){t.Sort="sort",t.Filter="filter",t.EntityFilterId="entityFilterId",t.InlineRefresh="inline-refresh",t.SctTopLevelComment="sct-top-level-comment",t.ForceLegacySCT="force-legacy-sct"}(i||(i={}));const n=/(\.|\/\/)(reddit\.com|snoo\.dev|redditstatic\.com|redd\.it|redditmedia\.com)$/;class r extends t.b4{constructor(e,i){super(e),this.events=new t.E(this,(()=>this._host)),this.handleMouseClick=(t,e)=>{if(t.isLinkClickHandled)return;const i=t.composedPath();for(const n of i){if(!(n instanceof HTMLAnchorElement))continue;const i=n.getAttribute("href")||"";if(this.isOutboundUrl(i))return this.trackOutboundLinkClick(i,e),void(t.isLinkClickHandled=!0)}},this.events.define("click",(t=>{this.handleMouseClick(t,i())}))}isOutboundUrl(t){if(t.startsWith("/"))return!1;try{return null==new URL(t).origin.match(n)}catch(t){return!1}}trackOutboundLinkClick(e,i){t.f(this._host,this.outboundLinkClickEvent(e,i))}outboundLinkClickEvent(e,i){return t.b({source:"link",action:"click",noun:"outbound_link"},{outbound:{url:e},action_info:{page_type:i.pageType},...i.postId?{post:{id:i.postId}}:{},...i.subredditId?{subreddit:{id:i.subredditId}}:{},...i.commentId?{comment:{id:i.commentId}}:{}})}}return{get M(){return e},O:r,P:"pdp-chained-right-rail-related-posts",R:"right-rail-entity-panel-root",S:"#subreddit-right-rail-tabs",a:"remove-flair",get b(){return i},g:function(t){return`update-post-flair-modal-${t}`}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("CoWPctolKZ",["C42E8rVVpA","DUzIBJc2in","CsxDAjmHZE"],(async(e,t,i)=>{let s=class extends i.s{constructor(){super(...arguments),this.zoomedIn=!1,this.disabled=!1,this.media=null,this._events=new e.E(this),this._click=this._events.define("click",this.onClick),this.fullImageWidth=0,this.fullImageHeight=0,this.checkMediaSize=()=>{this.media?.complete&&(this.fullImageWidth=this.media.naturalWidth,this.fullImageHeight=this.media.naturalHeight,this.disabled=this.fullImageWidth<=this.clientWidth&&this.fullImageHeight<=this.clientHeight,this.zoomedIn=!this.disabled&&this.zoomedIn)},this.checkMediaSizeDebounced=e.a7(this.checkMediaSize,100)}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.media=this.querySelector("img"),this.media&&this.media.addEventListener("load",this.checkMediaSize,{once:!0}),requestAnimationFrame(this.checkMediaSize),window.addEventListener("resize",this.checkMediaSizeDebounced)}firstUpdated(){this.checkMediaSize()}onClick(e){if(this.media&&e.target===this.media&&!this.disabled){let t=0,i=0;if(!this.zoomedIn){const s=this.media.getBoundingClientRect(),h=e.clientX-s.left,l=e.clientY-s.top,d=h/s.width*100,a=l/s.height*100;i=this.fullImageWidth*d/100-this.clientWidth/2,t=this.fullImageHeight*a/100-this.clientHeight/2}this.zoomedIn=!this.zoomedIn,requestAnimationFrame((()=>{this.scrollTo({top:t,left:i})}))}}render(){this.media&&this.media.setAttribute("class",this.getChildClassList()),this.setAttribute("class",this.getClasslist())}getClasslist(){return t.j("flex",this.zoomedIn?"fixed top-0 left-0 w-screen h-screen overflow-auto":"w-full h-full justify-center items-center overflow-hidden")}getChildClassList(){return t.j("z-1",this.disabled?"max-h-full max-w-full":this.zoomedIn?"max-w-none max-h-none m-auto cursor-zoom-out":"max-h-full max-w-full object-contain cursor-zoom-in")}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("resize",this.checkMediaSizeDebounced),this.zoomedIn=!1}};e._([e.v()],s.prototype,"zoomedIn",void 0),e._([e.v()],s.prototype,"disabled",void 0),s=e._([e.e("zoomable-img")],s)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q"); SML.dm("CsrVq94Zej",["C42E8rVVpA","BFDJQElz9q"],(async(E,R)=>{const D=R=>R===E.a5.ModApproved,e=R=>R===E.a5.AdminApproved,o=R=>R===E.a5.ModRemoved||R===E.a5.ModSpammed,M=R=>R===E.a5.AdminRemoved||R===E.a5.AdminSpammed;var P;!function(E){E.UNMODERATED="UNMODERATED",E.APPROVED="APPROVED",E.REMOVED="REMOVED",E.SPAM="SPAM",E.REPORTED="REPORTED",E.FILTERED="FILTERED"}(P||(P={}));const d=(E,R)=>(E===P.FILTERED||R)&&E!==P.APPROVED&&E!==P.REMOVED;return{get M(){return P},a:d,b:(D,e)=>(D===R.P.ModQueue||D===R.P.ModQueueAll)&&e===E.a6.ModQueueCompactView,c:E=>[P.REPORTED,P.FILTERED,P.UNMODERATED,P.REMOVED,P.SPAM].includes(E),d:E=>[P.APPROVED,P.UNMODERATED,P.REPORTED].includes(E),e:({moderationState:E,isSpamFilteredPost:R,isRemoved:D,isPromotedPost:e})=>(d(E,R)||!D)&&!e,f:({isPromotedPost:E})=>!E,h:E=>D(E)||e(E)||o(E)||M(E),i:E=>D(E)||e(E),s:(E,R,D,e)=>E===P.REMOVED&&!e&&!R&&!d(E,D)}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./DMFEgBklTz.js",import.meta.url,"DMFEgBklTz");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./7ymiBBk8xO.js",import.meta.url,"7ymiBBk8xO");SML.di("./Ceb0ABsHlF.js",import.meta.url,"Ceb0ABsHlF"); SML.dm("CvOrQNTrjb",["C42E8rVVpA","DMFEgBklTz","DUzIBJc2in","7ymiBBk8xO","Ceb0ABsHlF"],(async(e,t,i,s)=>{const r=new Set(["t3_103b4tl","t3_u1cuyg","t3_103bmpv","t3_xipqoc","t3_xipsi3"]);function n(e){const t=new Map;return e.forEach((e=>{const i=t.get(e.type)||[];i.push(e),t.set(e.type,i)})),t}function a(e){return!!e.encryptedTrackingId}function o(e,t){return e.encryptedTrackingId+t.additionalEventMetadata}function d({pixelEvent:e,pixelRequestBody:t,metadata:i,target:s}){if(!e.encryptedTrackingId)return;if(h(e.type))return o(e,t);const r=i?function(e){return Object.entries(e).reduce(((e,[t,i])=>(e[t]=i.toString(),e)),{})}(i):{};return fetch("https://alb.reddit.com/track",{method:"POST",mode:"no-cors",body:JSON.stringify({encryptedTrackingId:e.encryptedTrackingId,encryptedTrackingPayload:t.encryptedTrackingPayload,additionalEventMetadata:t.additionalEventMetadata,clientImpressionID:t.impressionId,...r})}).then((()=>{m(s,"succeeded",e)})).catch((t=>{const i="Sentry"in window?window.Sentry:void 0;i?.captureException&&i.captureException(new Error(`Error in POST response from pixel server for pixel of type ${e.type}: ${t}`)),m(s,"failed",e)})),o(e,t)}function l(t){return!!e.ee.includes(t)||e.ef.some((({experimentName:i,pixelEventTypes:s})=>e.at(i)&&s.includes(t)))}function h(t){return e.ej.some((({experimentName:i,pixelEventTypes:s})=>e.at(i)&&s.includes(t)))}function u({pixelEvent:t,impressionId:s,displayMetadata:r,videoMetadata:n,pixelRequestBody:o}){const d=e.eg[t.type];if(!d)return;const l={impression_id:s,event_timestamp:Math.floor(Date.now()),display_metadata:r,video_metadata:n,additional_metadata:o.additionalEventMetadata};if(a(t))l.encrypted_tracking_id=t.encryptedTrackingId,l.encrypted_tracking_payload=o.encryptedTrackingPayload;else{if(!i.ak(t.url))return;const{encryptedTrackingId:e,encryptedTrackingPayload:s}=function(e){const t=new URL(e);return{encryptedTrackingPayload:t.searchParams.get("za")||"",encryptedTrackingId:t.searchParams.get("zp")||""}}(t.url);l.encrypted_tracking_id=e,l.encrypted_tracking_payload=s}const h={client_ad_event_metadata:l,video_watch_metadata:e.eh[t.type],vendor_fully_in_view_metadata:e.ei[t.type],screen:{height:window.screen.height,width:window.screen.width}},u=document.querySelector("shreddit-app");u&&e.f(u,e.b(d,h))}function m(t,s,r){if(e.at(e.ek))return;if(!a(r)&&!i.ak(r.url))return;const n=e.el({name:"ads_igif_requests_total",value:1,label_values:[`tracking_type,${e.bZ[r.type]}`,`request_stage,${s}`]});e.f(t,n)}class T{constructor(t,i){this.impressionTimestamp=0,this.wasEverViewableTimer={fired:!1},this.largeAdFullViewTimer={fired:!1},this.hasDispatchedViewEvent=!1,this.resetTimers=()=>{for(const e of this.pixelTimers.keys())this.clearPixelTimer(e);for(const e of this.continuousTimers.keys())this.unsetContinuousTimer(e);for(const e of this.cumulativeTimers.keys())this.pauseCumulativeTimer(e);this.wasEverViewableTimer.timer&&(clearTimeout(this.wasEverViewableTimer.timer),this.wasEverViewableTimer.timer=void 0),this.largeAdFullViewTimer.timer&&(clearTimeout(this.largeAdFullViewTimer.timer),this.largeAdFullViewTimer.timer=void 0)},this.pixelFiringController=i,this.getFiredRedditPixelsCount=t.getFiredRedditPixelsCount,this.postId=t.postId,this.impressionId=t.impressionId,this.postElement=t.postElement,this.galleryItems=t.galleryItems,this.pixelTimers=new Map,this.cumulativeTimers=new Map,this.continuousTimers=new Map,this.setupUnloadFiring(),this.isProductAd=t.events.some((t=>t.type===e.bZ.PRODUCT_CLICK||t.type===e.bZ.PRODUCT_IMPRESSION))}setupUnloadFiring(){if(window.addEventListener(e.ax.eventType,(()=>this.handleUnload())),r.has(this.postId)){const t=new URLSearchParams(e.e4.search),i=Number.parseInt(t.get(e.em)||"");isNaN(i)||window.setTimeout((()=>this.fireUnloadPixel()),i)}}getCumulativeTimes(t){const i=this.updateCumulativeTimer(e.e6.ANY_TOTAL_VIEW_TIME,t),s=this.updateCumulativeTimer(e.e6.FIFTY_TOTAL_VIEW_TIME,t),r=this.updateCumulativeTimer(e.e6.FULL_TOTAL_VIEW_TIME,t),n=this.updateCumulativeTimer(e.e6.EIGHTY_TOTAL_VIEW_TIME,t);return{totalViewTime:i?.cumulativeTime||0,fiftyViewTime:s?.cumulativeTime||0,fullViewTime:r?.cumulativeTime||0,eightyViewTime:n?.cumulativeTime||0}}getContinuousTimes(t){const i=this.updateContinuousTimer(e.e6.ANY_CONTINUOUS_VIEW_TIME,t),s=this.updateContinuousTimer(e.e6.FIFTY_CONTINUOUS_VIEW_TIME,t),r=this.updateContinuousTimer(e.e6.FULL_CONTINUOUS_VIEW_TIME,t),n=this.updateContinuousTimer(e.e6.EIGHTY_CONTINUOUS_VIEW_TIME,t),a=this.updateContinuousTimer(e.e6.THIRTY_CONTINUOUS_VIEW_TIME,t);return{maxAnyViewTime:i?.maxContinuousTime||0,maxFiftyViewTime:s?.maxContinuousTime||0,maxFullViewTime:r?.maxContinuousTime||0,maxEightyViewTime:n?.maxContinuousTime||0,maxThirtyViewTime:a?.maxContinuousTime||0}}getMetadata(t){const i=Date.now(),{totalViewTime:s,fiftyViewTime:r,fullViewTime:n,eightyViewTime:a}=this.getCumulativeTimes(i),{maxAnyViewTime:o,maxFiftyViewTime:d,maxFullViewTime:l,maxEightyViewTime:h,maxThirtyViewTime:u}=this.getContinuousTimes(i),m=this.pixelTimers.get(e.bZ.GROUP_M_VIEWABLE)?.fired||t===e.bZ.GROUP_M_VIEWABLE,T=t===e.bZ.VIEWABLE_IMPRESSION||this.wasEverViewableTimer.fired;t===e.bZ.IMPRESSION&&0===this.impressionTimestamp&&(this.impressionTimestamp=i);const c=this.postElement?.getBoundingClientRect(),E=Math.floor(c?.width??0),_=Math.floor(c?.height??0),I=this.getFiredRedditPixelsCount?.()||0,p=new URLSearchParams(e.e4.search).get(e.en);return{[e.e6.ANY_TOTAL_VIEW_TIME]:s,[e.e6.FIFTY_TOTAL_VIEW_TIME]:r,[e.e6.EIGHTY_TOTAL_VIEW_TIME]:a,[e.e6.FULL_TOTAL_VIEW_TIME]:n,[e.e6.ANY_CONTINUOUS_VIEW_TIME]:o,[e.e6.FIFTY_CONTINUOUS_VIEW_TIME]:d,[e.e6.THIRTY_CONTINUOUS_VIEW_TIME]:u,[e.e6.EIGHTY_CONTINUOUS_VIEW_TIME]:h,[e.e6.FULL_CONTINUOUS_VIEW_TIME]:l,[e.e6.GLOBAL_COUNT]:I,[e.e6.GROUP_M_VIEWABLE]:m?1:0,[e.e6.AD_LOAD_TIME]:this.impressionTimestamp,[e.e6.TIMESTAMP]:i,[e.e6.WAS_EVER_VIEWABLE]:T?1:0,[e.e6.LARGE_AD_FULL_VIEW]:this.largeAdFullViewTimer.fired?1:0,[e.e6.HEIGHT]:_,[e.e6.WIDTH]:E,[e.e6.SCREEN_HEIGHT]:window.screen.height,[e.e6.SCREEN_WIDTH]:window.screen.width,...null!==p&&{[e.e6.TEST_ID]:p}}}getAdEventDisplayMetadata(){const e=Date.now(),{totalViewTime:t,fiftyViewTime:i,eightyViewTime:s,fullViewTime:r}=this.getCumulativeTimes(e),{maxAnyViewTime:n,maxThirtyViewTime:a,maxFiftyViewTime:o,maxEightyViewTime:d,maxFullViewTime:l}=this.getContinuousTimes(e),h=this.postElement?.getBoundingClientRect(),u=Math.floor(h?.width??0),m=Math.floor(h?.height??0);return{any_total_view_time_ms:Math.floor(t),fifty_total_view_time_ms:Math.floor(i),eighty_total_view_time_ms:Math.floor(s),full_total_view_time_ms:Math.floor(r),any_continuous_view_time_ms:Math.floor(n),thirty_continuous_view_time_ms:Math.floor(a),fifty_continuous_view_time_ms:Math.floor(o),eighty_continuous_view_time_ms:Math.floor(d),full_continuous_view_time_ms:Math.floor(l),height:m,width:u,screen_width:Math.floor(window.screen.width),screen_height:Math.floor(window.screen.height)}}getAdEventVideoMetadata(){}getPixelScalingFields(e){return{encryptedTrackingPayload:this.postElement.encryptedTrackingPayload||"",additionalEventMetadata:this.postElement.additionalEventMetadata?this.postElement.additionalEventMetadata[e||0]:"",impressionId:this.impressionId}}firePixel(e,t){const i=l(e);this.pixelFiringController.firePixel({pixelEventType:e,metadata:this.getMetadata(e),displayMetadata:i?this.getAdEventDisplayMetadata():void 0,videoMetadata:i?this.getAdEventVideoMetadata():void 0,galleryIndex:t})}fireUnloadPixel(){this.firePixel(e.bZ.UNLOAD)}measureViewChange(t){const i=this.postElement?.getBoundingClientRect(),s=Math.floor(i?.width??0),r=Math.floor(i?.height??0),n=r*s,a=n>=242500,o=r>document.documentElement.clientHeight;if(t.intersectionRatio){this.setCumulativeTimer(e.e6.ANY_TOTAL_VIEW_TIME),this.setContinuousTimer(e.e6.ANY_CONTINUOUS_VIEW_TIME),this.measureImpressionPixel(),this.galleryItems?.length?this.measureGalleryItemImpression():this.isProductAd&&this.measureProductImpression(),e.eo.queuePostForUnload(this.postId,this.impressionId,this.getMetadata.bind(this),this.pixelFiringController.firePixel.bind(this),this.getPixelScalingFields.bind(this));const t=this.postElement,i=this.galleryItems;if(!this.hasDispatchedViewEvent&&t&&!t.isBlank){const s=e.c("observe-post-view-ad",{postId:this.postId,post:t,galleryItems:i||[]});this.postElement.dispatchEvent(s),this.hasDispatchedViewEvent=!0}}else this.unsetContinuousTimer(e.e6.ANY_CONTINUOUS_VIEW_TIME),this.pauseCumulativeTimer(e.e6.ANY_TOTAL_VIEW_TIME);if(t.intersectionRatio>=e.bY.LARGE_AD_FULL_VIEW_THRESHOLD?this.setContinuousTimer(e.e6.THIRTY_CONTINUOUS_VIEW_TIME):this.unsetContinuousTimer(e.e6.THIRTY_CONTINUOUS_VIEW_TIME),t.intersectionRatio>=e.bY.VIEWABILITY_THRESHOLD){this.setCumulativeTimer(e.e6.FIFTY_TOTAL_VIEW_TIME),this.setContinuousTimer(e.e6.FIFTY_CONTINUOUS_VIEW_TIME),this.pixelTimers.has(e.bZ.VIEWABLE_IMPRESSION)||this.setPixelTimer(e.bZ.VIEWABLE_IMPRESSION,1e3),this.wasEverViewableTimer.timer||this.wasEverViewableTimer.fired||(this.wasEverViewableTimer.timer=setTimeout((()=>{this.wasEverViewableTimer.timer&&(this.wasEverViewableTimer.fired=!0,this.wasEverViewableTimer.timer=void 0)}),1e3));const t=this.cumulativeTimers.get(e.e6.FIFTY_TOTAL_VIEW_TIME);t&&(this.pixelTimers.has(e.bZ.VENDOR_FULLY_IN_VIEW_5_SECS)||this.setPixelTimer(e.bZ.VENDOR_FULLY_IN_VIEW_5_SECS,5e3-t.cumulativeTime),this.pixelTimers.has(e.bZ.VENDOR_FULLY_IN_VIEW_15_SECS)||this.setPixelTimer(e.bZ.VENDOR_FULLY_IN_VIEW_15_SECS,15e3-t.cumulativeTime))}else this.pixelTimers.has(e.bZ.VIEWABLE_IMPRESSION)&&this.clearPixelTimer(e.bZ.VIEWABLE_IMPRESSION),this.pixelTimers.has(e.bZ.VENDOR_FULLY_IN_VIEW_5_SECS)&&this.clearPixelTimer(e.bZ.VENDOR_FULLY_IN_VIEW_5_SECS),this.pixelTimers.has(e.bZ.VENDOR_FULLY_IN_VIEW_15_SECS)&&this.clearPixelTimer(e.bZ.VENDOR_FULLY_IN_VIEW_15_SECS),this.pauseCumulativeTimer(e.e6.FIFTY_TOTAL_VIEW_TIME),this.unsetContinuousTimer(e.e6.FIFTY_CONTINUOUS_VIEW_TIME);t.intersectionRatio>=e.bY.EIGHTY_VIEWABILITY_THRESHOLD?(this.setCumulativeTimer(e.e6.EIGHTY_TOTAL_VIEW_TIME),this.setContinuousTimer(e.e6.EIGHTY_CONTINUOUS_VIEW_TIME)):(this.pauseCumulativeTimer(e.e6.EIGHTY_TOTAL_VIEW_TIME),this.unsetContinuousTimer(e.e6.EIGHTY_CONTINUOUS_VIEW_TIME)),t.intersectionRatio>=e.bY.FULL_VIEWABILITY_THRESHOLD?(this.setCumulativeTimer(e.e6.FULL_TOTAL_VIEW_TIME),this.setContinuousTimer(e.e6.FULL_CONTINUOUS_VIEW_TIME)):(this.pauseCumulativeTimer(e.e6.FULL_TOTAL_VIEW_TIME),this.unsetContinuousTimer(e.e6.FULL_CONTINUOUS_VIEW_TIME)),t.intersectionRatio=e.bY.LARGE_AD_FULL_VIEW_THRESHOLD||t.intersectionRatio>=e.bY.FULL_VIEWABILITY_THRESHOLD?this.largeAdFullViewTimer.timer||this.largeAdFullViewTimer.fired||(this.largeAdFullViewTimer.timer=setTimeout((()=>{this.largeAdFullViewTimer.timer&&(this.largeAdFullViewTimer.fired=!0,this.largeAdFullViewTimer.timer=void 0)}),1e3)):this.largeAdFullViewTimer.timer&&(clearTimeout(this.largeAdFullViewTimer.timer),this.largeAdFullViewTimer.timer=void 0),o?1!==t.intersectionRatio||this.pixelTimers.has(e.bZ.GROUP_M_VIEWABLE)?n*t.intersectionRatio<1&&this.pixelTimers.has(e.bZ.GROUP_M_VIEWABLE)&&this.clearPixelTimer(e.bZ.GROUP_M_VIEWABLE):this.setPixelTimer(e.bZ.GROUP_M_VIEWABLE,1e3):t.intersectionRatio>=e.bY.FULL_VIEWABILITY_THRESHOLD?(this.pixelTimers.has(e.bZ.GROUP_M_VIEWABLE)||this.setPixelTimer(e.bZ.GROUP_M_VIEWABLE,1e3),this.pixelTimers.has(e.bZ.VENDOR_FULLY_IN_VIEW)||this.setPixelTimer(e.bZ.VENDOR_FULLY_IN_VIEW,100)):(this.pixelTimers.has(e.bZ.GROUP_M_VIEWABLE)&&this.clearPixelTimer(e.bZ.GROUP_M_VIEWABLE),this.pixelTimers.has(e.bZ.VENDOR_FULLY_IN_VIEW)&&this.clearPixelTimer(e.bZ.VENDOR_FULLY_IN_VIEW))}clearPixelTimer(e){const t=this.pixelTimers.get(e);t?.timer&&(clearTimeout(t.timer),this.pixelTimers.delete(e))}setPixelTimer(e,t){const i=this.pixelTimers.get(e)?.fired;i||(this.pixelTimers.get(e)?.timer&&this.clearPixelTimer(e),this.pixelTimers.set(e,{timer:setTimeout((()=>{this.pixelTimers.get(e)&&(this.firePixel(e),this.pixelTimers.set(e,{fired:!0,timer:void 0}))}),t)}))}handleClickRedirect(i,s){const r=this.getMetadata(e.bZ.CLICK);this.pixelFiringController.fireDebugPixel({pixel:t.a(i,r),pixelEvent:{url:i,type:e.bZ.CLICK,metadata:r},impressionId:this.impressionId,postId:this.postId}),this.isProductAd&&this.firePixel(e.bZ.PRODUCT_CLICK,s)}measureImpressionPixel(){this.firePixel(e.bZ.IMPRESSION)}measureGalleryItemImpression(t=0){this.firePixel(e.bZ.GALLERY_ITEM_IMPRESSION,t),this.isProductAd&&this.firePixel(e.bZ.PRODUCT_IMPRESSION,t)}measureProductImpression(){this.firePixel(e.bZ.PRODUCT_IMPRESSION)}handleUnload(){e.eo.fireQueuedUnloadPixels()}setCumulativeTimer(e){const t=this.cumulativeTimers.get(e),i=Date.now();if(t&&t.previousDate){const s=i-t.previousDate+t.cumulativeTime;this.cumulativeTimers.set(e,{previousDate:i,cumulativeTime:s})}else this.cumulativeTimers.set(e,{previousDate:i,cumulativeTime:t?.cumulativeTime||0})}updateCumulativeTimer(e,t){const i=this.cumulativeTimers.get(e);if(i&&i.previousDate){const s=t-i.previousDate+(i.cumulativeTime||0);this.cumulativeTimers.set(e,{previousDate:t,cumulativeTime:s})}return this.cumulativeTimers.get(e)}pauseCumulativeTimer(e){const t=this.updateCumulativeTimer(e,Date.now());t&&this.cumulativeTimers.set(e,{previousDate:null,cumulativeTime:t.cumulativeTime||0})}setContinuousTimer(e){const t=this.continuousTimers.get(e),i=Date.now();if(t&&t.previousDate){const s=t.currentContinuousTime+(i-t.previousDate),r=Math.max(s,t.maxContinuousTime);this.continuousTimers.set(e,{previousDate:i,currentContinuousTime:s,maxContinuousTime:r})}else this.continuousTimers.set(e,{previousDate:i,currentContinuousTime:t?.currentContinuousTime||0,maxContinuousTime:t?.maxContinuousTime||0})}updateContinuousTimer(e,t){const i=this.continuousTimers.get(e);if(i&&i.previousDate){const s=i.currentContinuousTime+(t-i.previousDate),r=Math.max(s,i.maxContinuousTime);this.continuousTimers.set(e,{previousDate:t,currentContinuousTime:s,maxContinuousTime:r})}return this.continuousTimers.get(e)}unsetContinuousTimer(e){const t=this.continuousTimers.get(e),i=Date.now();if(t&&t.previousDate){const s=Math.max(t.currentContinuousTime+(i-t.previousDate),t.maxContinuousTime);this.continuousTimers.set(e,{previousDate:null,currentContinuousTime:0,maxContinuousTime:s})}}}function c(e=0){return 1e3*e}class E extends T{get visible(){return!!this.videoIntersectionRatio}get viewable(){return(this.videoIntersectionRatio||0)>=e.bY.VIEWABILITY_THRESHOLD}get currentQuartileState(){switch((this.viewable?1:0)+(this.videoVolume&&this.videoVolume>0?2:0)){case 0:return e.ep.NOT_VISIBLE_NOT_AUDIBLE;case 1:return e.ep.VISIBLE_NOT_AUDIBLE;case 2:return e.ep.AUDIBLE_NOT_VISIBLE;case 3:return e.ep.VISIBLE_AND_AUDIBLE;default:return e.ep.NO_EVENT}}constructor(e,i){super(e,i),this.videoDuration=1/0,this.videoCurrentTime=0,this.seekingInitialized=!1,this.hasSeeked=!1,this.accumulatedWatchedTime=0,this.videoWasFullscreen=!1,this.videoWasVisible=!1,this.quartileState=new Map,this.dimensions=e.dimensions,this.thresholds=t.g(t.b)}minTimeRequired({timePercent:e=1/0,time:t=1/0}){const i=Number.isFinite(e)?e*this.videoDuration:1/0,s=Number.isFinite(t)?t:1/0;return Math.min(i,s)}setViewablePixelTimer(e){const t=Date.now(),i=this.pixelTimers.get(e.pixelEvent);if(i?.fired||i?.timer)return;let s=e.time;e.timePercent&&this.videoDuration&&(s=Math.min(this.videoDuration*e.timePercent,e.time));const r=i?.timeLeft?i?.timeLeft:s;this.pixelTimers.set(e.pixelEvent,{timer:setTimeout((()=>{this.firePixel(e.pixelEvent),this.pixelTimers.set(e.pixelEvent,{fired:!0,timer:void 0})}),r),timeLeft:r,lastSetTime:t})}resetViewablePixelTimer(e){const t=this.pixelTimers.get(e.pixelEvent);t?.fired||t&&!t.fired&&this.clearPixelTimer(e.pixelEvent)}pauseViewablePixelTimer(e){const t=this.pixelTimers.get(e.pixelEvent);if(t&&!t?.fired&&void 0!==this.videoCurrentTime&&void 0!==this.videoDuration){const i=Date.now();if(t.timer&&t.lastSetTime){const s=e.time-(i-t.lastSetTime);clearTimeout(t.timer),this.pixelTimers.set(e.pixelEvent,{timeLeft:s})}}}videoStateChange(){this.visible&&!this.videoWasVisible&&(this.videoWasVisible=!0),this.videoPlaying&&(this.updateQuartileState(),this.firePixel(e.bZ.VIDEO_STARTED),this.videoVolume&&this.firePixel(e.bZ.VIDEO_PLAYED_WITH_SOUND),e.eq.forEach((e=>{this.videoViewabilityStateChange(e)}))),e.er.forEach((e=>{this.videoWatchedPercentStateChange(e)})),e.es.forEach((e=>{this.videoWatchedSecondsStateChange(e)})),this.videoGroupMViewableChange()}videoViewabilityStateChange(e){this.videoIntersectionRatio&&this.videoIntersectionRatio>=e.threshold?this.videoPlaying?this.setViewablePixelTimer(e):this.pauseViewablePixelTimer(e):this.resetViewablePixelTimer({pixelEvent:e.pixelEvent,time:e.time})}videoWatchedPercentStateChange(t){if("number"==typeof this.videoCurrentTime&&"number"==typeof this.videoDuration){this.videoCurrentTime/this.videoDuration>=t.timePercent&&(t.quartileKey&&!this.quartileState.has(t.quartileKey)&&(t.quartileKey!==e.et.VIDEO_STATE_Q0||this.videoPlaying)&&this.quartileState.set(t.quartileKey,this.currentQuartileState),e.eu(t)&&this.firePixel(t.pixelEvent))}}updateQuartileState(){e.er.forEach((e=>{if(e.quartileKey&&"number"==typeof this.videoCurrentTime&&"number"==typeof this.videoDuration){this.videoCurrentTime/this.videoDuration>=e.timePercent&&e.quartileKey&&!this.quartileState.has(e.quartileKey)&&this.quartileState.set(e.quartileKey,this.currentQuartileState)}}))}videoWatchedSecondsStateChange(e){this.accumulatedWatchedTime>=this.minTimeRequired(e)&&this.firePixel(e.pixelEvent)}setMediaDetails(e){Number.isFinite(e.volume)&&(this.videoVolume=e.muted?0:e.volume),Number.isFinite(e.duration)&&(this.videoDuration=c(e.duration)),Number.isFinite(e.currentTime)&&(this.videoCurrentTime=c(e.currentTime))}updateAccumulatedWatchTime(e){const t=e-this.videoCurrentTime;return this.accumulatedWatchedTime+=t,t}updateThresholds(e){const{visibleThresholds:t}=this.getHiddenAndVisibleThresholds();t.forEach((t=>{this.thresholds[t.key].totalTime+=e,this.thresholds[t.key].currentContinuousTime+=e;const{currentContinuousTime:i,maxContinuousTime:s}=this.thresholds[t.key];i>s&&(this.thresholds[t.key].maxContinuousTime=i)})),this.resetContinuousTimerForHiddenThresholds()}getHiddenAndVisibleThresholds(){const e=[],i=[];return t.V.forEach((t=>{this.meetsViewabilityRequirements(t)?e.push(t):i.push(t)})),{visibleThresholds:e,hiddenThresholds:i}}resetContinuousTimerForHiddenThresholds(){this.resetContinuousTimerForThresholds(this.getHiddenAndVisibleThresholds().hiddenThresholds)}resetContinuousTimerForThresholds(e){e.forEach((e=>{this.thresholds[e.key].currentContinuousTime=0}))}measureViewChange(e){e.isVideoPlayer?this.videoIntersectionRatio=e.intersectionRatio:super.measureViewChange(e),this.videoStateChange(),this.resetContinuousTimerForHiddenThresholds()}measureVideoPlay(e){this.videoPlaying=!0,this.setMediaDetails(e),this.videoStateChange()}measureVideoPause(t){this.videoPlaying=!1,this.setMediaDetails(t),this.videoStateChange(),e.eq.forEach((e=>{this.pauseViewablePixelTimer(e)}))}measureVideoSeek(t){this.hasSeeked=!0,this.seekingInitialized||(this.videoPlaying=!1,this.setMediaDetails(t),e.eq.forEach((e=>{this.resetViewablePixelTimer({pixelEvent:e.pixelEvent,time:e.time})})),this.seekingInitialized=!0)}measureVideoSeeked(e){this.seekingInitialized=!1,this.hasSeeked=!0,this.videoCurrentTime=c(e.currentTime),e.paused||this.measureVideoPlay(e)}measureVolumeChange(t){this.setMediaDetails(t),this.videoStateChange(),t.volume&&!t.muted&&this.videoPlaying&&e.eq.forEach((e=>{this.firePixel(e.pixelEvent),this.pixelTimers.set(e.pixelEvent,{fired:!0})}))}measureFullscreenChange(t){this.videoFullscreen=t.fullscreen,this.videoStateChange(),t.fullscreen&&(this.videoWasFullscreen=!0,this.firePixel(e.bZ.VIDEO_PLAYED_EXPANDED),this.videoPlaying&&e.eq.forEach((e=>{this.firePixel(e.pixelEvent),this.pixelTimers.set(e.pixelEvent,{fired:!0})})))}measureVideoTimeUpdate(e){const t=this.updateAccumulatedWatchTime(c(e.currentTime));this.updateThresholds(t),this.videoCurrentTime=c(e.currentTime),this.videoStateChange()}getMetadata(t){const i=super.getMetadata(t),s=this.thresholds.HALF_DURATION_80_IN_VIEW_AUDIBLE.totalTime;return{...i,[e.e7.IS_VIDEO_AD]:1,[e.e7.TOTAL_MRC_VIEWABLE_TIME]:Math.floor(this.thresholds.TOTAL_MRC_VIEWABLE_TIME.totalTime),[e.e7.VIDEO_AD_DURATION]:isFinite(this.videoDuration)?Math.floor(this.videoDuration):0,[e.e7.TOTAL_PLAY_TIME]:Math.floor(this.accumulatedWatchedTime),[e.e7.VOLUME]:Math.floor(100*(this.videoVolume??0)),[e.e7.IS_VISIBLE]:this.visible?1:0,[e.e7.VIDEO_HEIGHT]:this.visible&&this.dimensions?this.dimensions.height:0,[e.e7.TOTAL_AUDIBLE_TIME]:Math.floor(this.thresholds.TOTAL_AUDIBLE_TIME.totalTime),[e.e7.VIDEO_STATE_Q0]:this.quartileState.get(e.et.VIDEO_STATE_Q0)??e.ep.NO_EVENT,[e.e7.VIDEO_STATE_Q1]:this.quartileState.get(e.et.VIDEO_STATE_Q1)??e.ep.NO_EVENT,[e.e7.VIDEO_STATE_Q2]:this.quartileState.get(e.et.VIDEO_STATE_Q2)??e.ep.NO_EVENT,[e.e7.VIDEO_STATE_Q3]:this.quartileState.get(e.et.VIDEO_STATE_Q3)??e.ep.NO_EVENT,[e.e7.VIDEO_STATE_Q4]:this.quartileState.get(e.et.VIDEO_STATE_Q4)??e.ep.NO_EVENT,[e.e7.VIDEO_WIDTH]:this.visible&&this.dimensions?this.dimensions.width:0,[e.e7.WAS_FULL_SCREEN]:this.videoWasFullscreen?1:0,[e.e7.HALF_DURATION_80_IN_VIEW_AUDIBLE]:s>=15e3||this.videoDuration&&s>=.5*this.videoDuration?1:0,[e.e7.FULL_IN_VIEW_AUDIBLE_TIME]:Math.floor(this.thresholds.FULL_IN_VIEW_AUDIBLE_TIME.totalTime),[e.e7.EIGHTY_TOTAL_VIDEO_VIEW_TIME]:Math.floor(this.thresholds.EIGHTY_IN_VIEW_TIME.totalTime),[e.e7.FULL_IN_VIEW_TIME]:Math.floor(this.thresholds.FULL_IN_VIEW_TIME.totalTime),[e.e7.WAS_FULL_IN_VIEW_1SEC]:this.thresholds.FULL_IN_VIEW_TIME.maxContinuousTime>=1e3?1:0,[e.e7.ANY_CONTINUOUS_VIDEO_VIEW_TIME]:Math.floor(this.thresholds.ANY_IN_VIEW_TIME.maxContinuousTime),[e.e7.FIFTY_CONTINUOUS_VIDEO_VIEW_TIME]:Math.floor(this.thresholds.FIFTY_IN_VIEW_TIME.maxContinuousTime),[e.e7.FULL_CONTINUOUS_VIDEO_VIEW_TIME]:Math.floor(this.thresholds.FULL_IN_VIEW_TIME.maxContinuousTime),[e.e7.HAS_SEEKED]:this.hasSeeked?1:0}}getAdEventVideoMetadata(){return{is_video:!0,total_mrc_viewable_time_ms:Math.floor(this.thresholds.TOTAL_MRC_VIEWABLE_TIME.totalTime),video_ad_duration:isFinite(this.videoDuration)?Math.floor(this.videoDuration):0,total_play_time:Math.floor(this.accumulatedWatchedTime),volume:Math.floor(100*(this.videoVolume??0)),total_audible_time:Math.floor(this.thresholds.TOTAL_AUDIBLE_TIME.totalTime),was_full_screen:this.videoWasFullscreen,video_state_q1:(this.quartileState.get(e.et.VIDEO_STATE_Q1)??e.ep.NO_EVENT).toString(),video_state_q2:(this.quartileState.get(e.et.VIDEO_STATE_Q2)??e.ep.NO_EVENT).toString(),video_state_q3:(this.quartileState.get(e.et.VIDEO_STATE_Q3)??e.ep.NO_EVENT).toString(),video_state_q4:(this.quartileState.get(e.et.VIDEO_STATE_Q4)??e.ep.NO_EVENT).toString(),full_in_view_audible_time_ms:Math.floor(this.thresholds.FULL_IN_VIEW_AUDIBLE_TIME.totalTime),full_in_view_time_ms:Math.floor(this.thresholds.FULL_IN_VIEW_TIME.totalTime),video_height:this.visible&&this.dimensions?this.dimensions.height:0,video_width:this.visible&&this.dimensions?this.dimensions.width:0,fifty_continuous_video_view_time_v2_ms:Math.floor(this.thresholds.FIFTY_IN_VIEW_TIME.maxContinuousTime),eighty_total_video_view_time_v2_ms:Math.floor(this.thresholds.EIGHTY_IN_VIEW_TIME.totalTime),any_continuous_video_view_time_v2_ms:Math.floor(this.thresholds.ANY_IN_VIEW_TIME.maxContinuousTime),full_continuous_video_view_time_v2_ms:Math.floor(this.thresholds.FULL_IN_VIEW_TIME.maxContinuousTime)}}isAdequatelyInView(e){return!!this.videoFullscreen||(this.videoIntersectionRatio||0)>=e}meetsViewabilityRequirements(e){return this.isAdequatelyInView(e.threshold)&&(!e.playing||this.videoPlaying)&&(!e.withSound||this.videoVolume&&this.videoVolume>0)}videoGroupMViewableChange(){const t=this.dimensions?.height*this.dimensions?.width;let i=this.thresholds.FULL_IN_VIEW_AUDIBLE_TIME.totalTime;t>=3e5&&(i=this.thresholds.HALF_DURATION_80_IN_VIEW_AUDIBLE.totalTime),i/this.videoDuration>=e.bY.VIEWABILITY_THRESHOLD&&this.firePixel(e.bZ.VIDEO_GROUP_M_VIEWABLE)}}const _=(e,{ignoredTags:t=new Set}={})=>{const i=(e=>{const t=window.getComputedStyle(e).borderRadius,i=Number.parseInt(t)/2,s=e.getBoundingClientRect();return document.elementFromPoint(s.left+i,s.top+i)})(e);return{overlappingElement:i,isOverlapped:!(!i||e.isSameNode(i)||e.contains(i)||t.has(i.tagName)||!((e,t)=>{const i=e.getBoundingClientRect(),s=t.getBoundingClientRect();return!(i.top>s.bottom||i.rights.right)})(e,i))}},I=(e,t)=>{if((e=>{const t=e.getBoundingClientRect();if(t.width*t.height==0)return!0;const i=window.innerWidth||document.documentElement.clientWidth,s=window.innerHeight||document.documentElement.clientHeight;return t.right<0||t.bottom<0||t.left>i||t.top>s})(e))return 0;const i=e.getBoundingClientRect(),s=t.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,n=Math.min(r,i.bottom);return Math.max(0,n-s.bottom)/i.height},p=(e,t)=>{if(!e||!e.title)return 0;if(!1===e.renderTitleTruncation)return e.title.length;const i=e?.querySelector('[click-location="title"]')?.shadowRoot?.querySelector("a"),s=document.body,r=document.createElement("div");if(r.id="dummyDiv",r.className=i?.className,r.className=r.className.replace(/line-clamp-\d+/,""),r.classList.add("px-md"),t||(r.classList.add("font-normal"),r.classList.add("text-14")),r.style.position="absolute",r.style.left="-9999px",r.style.top="-9999px",r.style.visibility="hidden",s?.appendChild(r),r.style.width=i?.clientWidth+"px",r.textContent=e.title,r.offsetHeight<=i?.offsetHeight)return r?.remove(),e.title.length;let n=0;r.textContent="โ€ฆ";for(let t=0;ti?.offsetHeight)break;n+=1}return r?.remove(),n},v=({postId:t,post:s,galleryItems:r,page_request_id:n,adsCorrelationId:a})=>{const o=s?.querySelector(`[click-location=${e.w.MEDIA}]`);let d;o&&(d=o.getBoundingClientRect());const l={post:{id:t,subreddit_id:s?.subredditId,subreddit_name:s?.subredditPrefixedName,author_id:s?.authorId,promoted:!0,title:s?.postTitle||s?.title,domain:s?.domain,nsfw:s?.nsfw,number_comments:s?.commentCount,type:s?.postType,created_timestamp:e.cv(s?.createdTimestamp||""),spoiler:s?.spoiler,url:s?.outboundLinkUrl},ad_metadata:{impression_id:s?.impressionId||"",placement:i.bd({post:s}),ad_correlation_id:a},feed:e.ev(),action_info:{page_request_id:n},screen:{height:window.screen.height,width:window.screen.width}};s&&i.be(s)&&(l.action_info||(l.action_info={}),l.action_info.position=s.feedIndex,l.screen||(l.screen={}),l.screen={},l.screen.view_type=e.ew(s.viewType));const h=r&&r.length>0||!1;if(s&&i.bf(s)&&(l.view_stats={characters_displayed:p(s,h)},l.parent={post_id:s?.parentElement?.querySelector("shreddit-post")?.id},l.action_info||(l.action_info={}),l.action_info.position=(t=>{if(t.shouldTrackPosition&&!t.isBlank)return t.placement===e.a8.COMMENTS_PAGE?0:[...document.querySelectorAll('shreddit-comments-page-ad[placement="comments_page"], shreddit-comments-page-ad[placement="comment_trees"], shreddit-comment[depth="0"]')].findIndex((e=>e.id===t.id))||void 0})(s)),r&&r.length>0){const e=r.map((e=>e.media?.id||""));l.gallery={num_items:r.length,media_ids:e,id:r[0].id},l.media={id:r[0].media?r[0].media.id:"",width:r[0].media?r[0].media.width:0,height:r[0].media?r[0].media.height:0}}else d&&(l.media={id:t,height:Math.round(d?.height),width:Math.round(d?.width)});return e.b(e.ex,l)},g=t=>t.map((t=>{const i=e.bZ[t.type];return{...t,type:i}}));class V{constructor(s){this.firedPixels=new Set,this.firedRedditPixels=new Set,this.firePixel=({pixelEventType:e,metadata:t,galleryIndex:i,displayMetadata:s,videoMetadata:r})=>{const n=this.postEvents?.get(e)||[];if(this.host.galleryItems){const t=this.getGalleryUrls(e,i)||[];n.push(...t)}const a=this.getPixelScalingFields(i);return this.firePixelsFromEvents({pixelEvents:n,metadata:t,pixelRequestBody:a,displayMetadata:s,videoMetadata:r})},this.fireDebugPixel=t=>{const i=e.c("pixelFired",t);window.dispatchEvent(i)},this.firePixelsFromEvents=({pixelEvents:e,metadata:t,pixelRequestBody:i,displayMetadata:s,videoMetadata:r})=>{const n=[];return e.forEach((e=>{const a=this.firePixelRequest({pixelEvent:e,metadata:t,pixelRequestBody:i,displayMetadata:s,videoMetadata:r});a&&n.push(a)})),n},this.firePixelRequest=({pixelEvent:s,metadata:r,pixelRequestBody:n,displayMetadata:T,videoMetadata:c})=>{if(this.hasPixelAlreadyFired(s,n))return;let E;return m(this.host,"queued",s),a(s)?E=d({pixelEvent:s,metadata:r,pixelRequestBody:n,target:this.host}):(E=function(e,s,r){const n=!i.ak(e.url);if(h(e.type)&&!n)return e.url;const a=new Image;a.onload=()=>{m(r,"succeeded",e)},a.onerror=t=>{const i="Sentry"in window?window.Sentry:void 0;i?.captureException&&i.captureException(new Error(`Error in GET response from pixel server for pixel of type ${e.type}: ${t}`)),m(r,"failed",e)};let o=e.url;return s&&!n&&(o=t.a(o,s)),a.src=o,e.url}(s,r,this.host),i.ak(s.url)||s.type!==e.bZ.IMPRESSION||function(t){const i=t===e.aT.DESKTOP?"shreddit_desktop":"shreddit_mobile";e.ak({type:e.al.Counter,name:"ads_third_party_impression_tracker_total",value:1,labels:{client_platform:i}})}(this.deviceType)),l(s.type)&&u({pixelEvent:s,impressionId:this.host.impressionId,displayMetadata:T,videoMetadata:c,pixelRequestBody:n}),E&&(this.firedPixels.add(E),(a(s)||i.ak(E))&&this.firedRedditPixels.add(E)),a(s)?this.fireDebugPixel({pixel:o(s,n),pixelEvent:{encryptedTrackingId:s.encryptedTrackingId,type:s.type,metadata:r},encryptedTrackingPayload:n.encryptedTrackingPayload,additionalEventMetadata:n.additionalEventMetadata,postId:this.host.postId,impressionId:this.host.impressionId}):this.fireDebugPixel({pixel:s.url,pixelEvent:{url:s.url,type:s.type,metadata:i.ak(s.url)?r:void 0},postId:this.host.postId,impressionId:this.host.impressionId}),E},this.hasPixelAlreadyFired=(e,t)=>a(e)?this.firedPixels.has(o(e,t)):this.firedPixels.has(e.url),this.deviceType=document.querySelector("shreddit-app")?.deviceType||e.aT.MOBILE,this.host=s,this.host.addController(this)}hostConnected(){const e=g(this.host.adEvents);this.postEvents=n(e),this.host.galleryItems&&(this.galleryEvents=this.host.galleryItems.map((e=>n(g(e.adEvents||[])))))}get firedRedditPixelsCount(){return this.firedRedditPixels.size}getPixelScalingFields(e){return{encryptedTrackingPayload:this.host.encryptedTrackingPayload||"",additionalEventMetadata:this.host.additionalEventMetadata?this.host.additionalEventMetadata[e||0]:"",impressionId:this.host.impressionId}}getGalleryUrls(t,i){const s=void 0===i&&t===e.bZ.IMPRESSION,r=s?0:i;if(void 0===r)return;const n=s?e.bZ.GALLERY_ITEM_IMPRESSION:t;return this.galleryEvents?.[r]&&this.galleryEvents[r].get(n)||[]}}class f{constructor({host:t,isVideoAd:i,onIntersectionEvent:s}){this.host=t,this.isVideoAd=i,this.onIntersectionEvent=s,this.observer=new IntersectionObserver((e=>{e.forEach((e=>{this.triggerIntersectionEventCallback(e)}))}),{threshold:e.ey,rootMargin:`-${this._getHeaderHeight()}px 0px 0px 0px`}),this.host.addController(this)}get shredditPlayer(){return this.host.querySelector(e.ez)}hostConnected(){this.observer.observe(this.host),this.isVideoAd&&this.shredditPlayer&&this.observer.observe(this.shredditPlayer)}hostDisconnected(){this.observer.disconnect()}triggerIntersectionEventCallback(e){const t=e.target===this.shredditPlayer;this.onIntersectionEvent({isVideoPlayer:t,intersectionRatio:e.intersectionRatio})}_getHeaderHeight(){let e=0;const t=document.querySelector("shreddit-app");if(t){const i=getComputedStyle(t).getPropertyValue("--shreddit-header-height");e=parseInt(i,10)||0}return e}}const C=Symbol("mixins/with-ad-observer"),y=new Set(["SHREDDIT-APP","FACEPLATE-PARTIAL"]);return{W:function(t){const r=t;if(e.d4(r,C))return r;class n extends r{constructor(){super(...arguments),this.eventController=new e.E(this),this.pubsub=new e.m(this),this.isOverlapped=!1,this.isVideo=!1,this.isGallery=!1,this.visibilityChangeHandler=this.onVisibilityChange.bind(this),this.isAdObserved=!1,this.onCommentCreated=()=>{this.firePixel(e.bZ.COMMENT)},this.onCommentUpvoted=()=>{this.firePixel(e.bZ.COMMENT_UPVOTE)},this.onCommentDownvoted=()=>{this.firePixel(e.bZ.COMMENT_DOWNVOTE)},this.onHideAd=({impressionId:e,action:t})=>{this.impressionId===e&&t===s.a.hide&&this.adMeasurer?.resetTimers()},this.checkAndMeasureIfAdIsBeingOverlapped=e.a7((()=>{if(!this.postElement||!this.postElement.isConnected)return;const{hidden:e}=this.getHiddenAndVisibilityChangeForDocument();if(document[e])return void this.measureOutOfViewChange();const{isOverlapped:t,overlappingElement:i}=_(this.postElement,{ignoredTags:y});if(t&&i){this.isOverlapped=!0;const e={intersectionRatio:I(this.postElement,i)};this.adMeasurer?.measureViewChange(e),this.updateViewChangeDetails(e)}else this.isOverlapped&&(this.isOverlapped=!1,this.measureBackInViewChange())}),30),this.updateViewChangeDetails=e=>{e.isVideoPlayer?this.lastVideoIOEvent=e:(this.lastAdIOEvent=e,e.intersectionRatio>0&&(this.lastVisibleAdIOEvent=e))},this.measureOutOfViewChange=()=>{const e={intersectionRatio:0};if(this.adMeasurer?.measureViewChange(e),this.updateViewChangeDetails(e),this.isVideo){const t={...e,isVideo:!0};this.adMeasurer?.measureViewChange(t),this.updateViewChangeDetails(t)}},this.measureBackInViewChange=()=>{this.lastVisibleAdIOEvent&&(this.adMeasurer?.measureViewChange(this.lastVisibleAdIOEvent),this.updateViewChangeDetails(this.lastVisibleAdIOEvent),this.isVideo&&this.lastVideoIOEvent&&(this.adMeasurer?.measureViewChange(this.lastVideoIOEvent),this.updateViewChangeDetails(this.lastVideoIOEvent)))},this.handleAnalyticEvent=this.eventController.define("faceplate-track",(t=>{const i=t.detail;if(i.post?.id!==this.postId)return;const{source:s,action:r,noun:n}=i;if("gallery"===s&&this.isGallery){if("forward"!==n&&"backward"!==n)return;const e="forward"===n?this.galleryIndex+1:this.galleryIndex-1;if(e<0||e>=this.galleryItemLength)return;this.galleryIndex=e,this.adMeasurer?.measureGalleryItemImpression(this.galleryIndex),this.lastAdIOEvent&&this.adMeasurer?.measureViewChange(this.lastAdIOEvent)}if("post_detail"===s&&"click"===r)switch(n){case"upvote_comment":this.firePixel(e.bZ.COMMENT_UPVOTE);break;case"downvote_comment":this.firePixel(e.bZ.COMMENT_DOWNVOTE);break;case"submit_comment":this.firePixel(e.bZ.COMMENT)}if("post"===s&&"click"===r)switch(n){case"comments":this.firePixel(e.bZ.COMMENTS_VIEW);break;case"upvote":this.firePixel(e.bZ.UPVOTE);break;case"downvote":this.firePixel(e.bZ.DOWNVOTE)}})),this.handlePostViewAdEvent=this.eventController.define("observe-post-view-ad",(t=>{const i=t.detail.post,{postId:s,galleryItems:r}=t.detail,n=e.cj();e.f(this,v({postId:s,post:i,galleryItems:r,page_request_id:n,adsCorrelationId:i.adsCorrelationId}))})),this.handleAdClickEvent=this.eventController.define("observe-ad-click",(t=>{const{postId:s,impressionId:r,outboundUrl:n,galleryIndex:a}=t.detail;if(s!==this.postId&&r!==this.impressionId)return;i.am(n)&&(this.adMeasurer?.handleClickRedirect(n,a),this.fireAnalyticsEventForClickRedirect({outboundUrl:n,impressionId:r,galleryIndex:a}));const o=a??this.galleryIndex;this.firePixel(e.bZ.CLICK,o)})),this.handleLeadGenSubmissionEvent=this.eventController.define(e.eA,(t=>{this.firePixel(e.bZ.LEAD_GENERATION)})),this.handleAdEngagedClickEvent=this.eventController.define(e.dV,(t=>{this.firePixel(e.bZ.ENGAGED_CLICK)}))}getMetadataForPixelEvent(e){return this.adMeasurer?.getMetadata(e)}enableAdObserver(t){try{if(this.isAdObserved)return;const{adType:i,...s}=t;this.postId=t.postId,this.impressionId=t.impressionId,this.postElement=t.postElement,this.isVideo=i===e.eB.VIDEO,Array.isArray(t.galleryItems)&&(this.isGallery=!0,this.galleryIndex=0,this.galleryItemLength=t.galleryItems.length),this.overlappingObserver=new MutationObserver(this.checkAndMeasureIfAdIsBeingOverlapped),new f({host:t.postElement,isVideoAd:this.isVideo,onIntersectionEvent:this.isIntersectingChange.bind(this)}),this.pixelFiringController=new V(t.postElement),s.getFiredRedditPixelsCount=()=>this.pixelFiringController?.firedRedditPixelsCount||0,this.adMeasurer=this.isVideo?new E(s,this.pixelFiringController):new T(s,this.pixelFiringController),this.isVideo&&this.setupVideoEvents(),this.isGallery&&this.setupGalleryEvents(),this.setupVisibilityTracking(),this.isAdObserved=!0,this.impressionId||this.fireInitializationErrorMetricEvent("missing_impression_id")}catch(e){window.Sentry?.captureException?.(`enableAdObserver | ${e.stack}`),this.fireInitializationErrorMetricEvent("exception")}}connectedCallback(){super.connectedCallback(),this.pubsub.subscribe(e.T.AdUpdated,this.onHideAd),this.postElement&&this.postElement.isPDP&&(this.pubsub.subscribe(e.T.CommentCreated,this.onCommentCreated),this.pubsub.subscribe(e.T.CommentUpvoted,this.onCommentUpvoted),this.pubsub.subscribe(e.T.CommentDownvoted,this.onCommentDownvoted))}disconnectedCallback(){super.disconnectedCallback(),this.teardownVisibilityTracking(),this.measureOutOfViewChange()}firePixel(e,t){if(!this.adMeasurer||!this.pixelFiringController)return;const i=l(e);this.pixelFiringController.firePixel({pixelEventType:e,metadata:this.adMeasurer.getMetadata(e),displayMetadata:i?this.adMeasurer.getAdEventDisplayMetadata():void 0,videoMetadata:i?this.adMeasurer.getAdEventVideoMetadata():void 0,galleryIndex:t})}measureOutOfViewChangeIgnoringPrompts(e){e.relatedTarget&&this.measureOutOfViewChange()}onVisibilityChange(){const{hidden:e}=this.getHiddenAndVisibilityChangeForDocument();this.lastAdIOEvent&&(document[e]?this.measureOutOfViewChange():this.measureBackInViewChange())}setupVisibilityTracking(){const{visibilityChange:e}=this.getHiddenAndVisibilityChangeForDocument();document.addEventListener(e,this.visibilityChangeHandler),window.addEventListener("blur",this.measureOutOfViewChangeIgnoringPrompts),window.addEventListener("focus",this.measureBackInViewChange),this.overlappingObserver?.observe(document.body,{childList:!0,subtree:!0,attributes:!0,characterData:!1})}teardownVisibilityTracking(){const{visibilityChange:e}=this.getHiddenAndVisibilityChangeForDocument();document.removeEventListener(e,this.visibilityChangeHandler),window.removeEventListener("blur",this.measureOutOfViewChangeIgnoringPrompts),window.removeEventListener("focus",this.measureBackInViewChange),this.overlappingObserver?.disconnect()}isIntersectingChange(e){this.updateViewChangeDetails(e),this.adMeasurer?.measureViewChange(e),(e.intersectionRatio||this.isOverlapped)&&this.checkAndMeasureIfAdIsBeingOverlapped()}getHiddenAndVisibilityChangeForDocument(){let t=e.eC.Standard,i=e.eD.hidden;return void 0!==document.hidden?(t=e.eC.Standard,i=e.eD.hidden):void 0!==document.webkitHidden&&(t=e.eC.Webkit,i=e.eD.webkitHidden),{hidden:t,visibilityChange:i}}setupVideoEvents(){this.handleVideoFullscreenEvent=this.eventController.define(e.eE,(e=>{this.adMeasurer?.measureFullscreenChange(e.detail)})),this.handleVideoPauseEvent=this.eventController.define(e.eF,(e=>{this.adMeasurer?.measureVideoPause(e.detail)})),this.handleVideoPlayEvent=this.eventController.define(e.eG,(e=>{this.adMeasurer?.measureVideoPlay(e.detail)})),this.handleVideoVolumeEvent=this.eventController.define(e.eH,(e=>{this.adMeasurer?.measureVolumeChange(e.detail)})),this.handleVideoSeekingEvent=this.eventController.define(e.eI,(e=>{e.detail.fromReconnect||this.adMeasurer?.measureVideoSeek(e.detail)})),this.handleVideoSeekedEvent=this.eventController.define(e.eJ,(e=>{e.detail.fromReconnect||this.adMeasurer?.measureVideoSeeked(e.detail)})),this.handleVideoTimeUpdateEvent=this.eventController.define(e.eK,(e=>{setTimeout((()=>{this.adMeasurer?.measureVideoTimeUpdate(e.detail)}))}))}setupGalleryEvents(){this.handleGalleryItemImpressionEvent=this.eventController.define(i.O,(e=>{const{postId:t,itemIndex:i}=e.detail;t===this.postId&&this.adMeasurer?.measureGalleryItemImpression(i)}))}fireAnalyticsEventForClickRedirect({outboundUrl:t,impressionId:i,galleryIndex:s}){l(e.bZ.CLICK)&&this.adMeasurer&&this.postElement&&u({pixelEvent:{type:e.bZ.CLICK,url:t},impressionId:i,pixelRequestBody:this.adMeasurer.getPixelScalingFields(s),displayMetadata:this.adMeasurer.getAdEventDisplayMetadata(),videoMetadata:this.adMeasurer.getAdEventVideoMetadata()})}fireInitializationErrorMetricEvent(t){const i=e.el({name:"shreddit_ad_init_failure",value:1,label_values:[`error_type,${t}`,`post_id,${this.postId}`,`impression_id,${this.impressionId}`]});e.f(this.postElement,i)}}return n[C]=!0,n},e:g}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("CyHfZd1TKD",["CsxDAjmHZE"],(async l=>{const{svg:c}=l.g();return{p:l.m(c``,"0 0 20 20","profile-fill")}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("D7hQQ1YBGe",["C42E8rVVpA","CsxDAjmHZE"],(async(t,e)=>{const s=t=>{const e=window.getComputedStyle(t).display;return""!==e?"none"===e:!!t.classList.contains("hidden")&&!t.classList.contains("contents")};let i=class extends e.s{constructor(){super(...arguments),this.resetBreakpoints=[768,1200],this.onlyFullRows=!1,this._events=new t.E(this,(()=>window)),this._lastBreakpoint=0,this.onResize=this._events.define("resize",(()=>{const t=this.determineCurrentBreakpoint();t!==this._lastBreakpoint&&this.reset(t)})),this.handleShowMore=()=>{const t=this.getVisibilityState(),e=t.initiallyVisible.length;for(let s=0;s=s:e>0)}disconnectedCallback(){super.disconnectedCallback(),this.showMoreButton?.removeEventListener("click",this.handleShowMore)}render(){return e.x` `}};t._([t.n({type:Array,attribute:"reset-breakpoints"})],i.prototype,"resetBreakpoints",void 0),t._([t.n({type:Boolean,attribute:"only-full-rows"})],i.prototype,"onlyFullRows",void 0),t._([t.l({slot:"show_more"})],i.prototype,"showMoreElements",void 0),i=t._([t.e("show-more-grid")],i)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./PaIPteKyLX.js",import.meta.url,"PaIPteKyLX");SML.di("./BkjgI35gdl.js",import.meta.url,"BkjgI35gdl");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./CUdNoUn2BN.js",import.meta.url,"CUdNoUn2BN");SML.di("./CeSBv4aKUm.js",import.meta.url,"CeSBv4aKUm");SML.di("./CcDgzSlONg.js",import.meta.url,"CcDgzSlONg");SML.di("./CEuDX0j-qf.js",import.meta.url,"CEuDX0j-qf");SML.di("./CPd-IV5dE-.js",import.meta.url,"CPd-IV5dE-");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./JaGlTj3I-9.js",import.meta.url,"JaGlTj3I-9");SML.di("./BI1JuD5RPj.js",import.meta.url,"BI1JuD5RPj"); SML.dm("D82XDppqGm",["C42E8rVVpA","PaIPteKyLX","BkjgI35gdl","CsxDAjmHZE","CUdNoUn2BN","CeSBv4aKUm","CcDgzSlONg","CPd-IV5dE-","CEuDX0j-qf","DUzIBJc2in","JaGlTj3I-9","BI1JuD5RPj"],(async(e,t,n,a,r,i,o,s)=>{const{svg:c}=a.g(),l=a.m(c``,"0 0 20 20","custom-feed-fill");var $,u;!function(e){e.QUERY="query",e.SUBREDDIT="subreddit",e.MULTIREDDIT="multireddit",e.PROFILE="profile"}($||($={})),function(e){e.COLLAPSED_SECTIONS="collapsedSections",e.CONVERSATION_ID="cId",e.FLAIR="flair",e.QUERY="query",e.RECENT_SEARCHES_COUNT="recentSearchesCount"}(u||(u={}));const E="recent-search-item";let T=class extends a.s{constructor(){super(...arguments),this.handleKeyDown=t=>{"Tab"===t.key&&t.target instanceof HTMLElement&&(t.shiftKey&&t.target.className.includes(e.gf)?(this.focus(),t.preventDefault(),t.stopPropagation()):t.shiftKey||t.target.className.includes(e.gf)||(this.querySelector(`.${e.gf}`)?.focus(),t.preventDefault(),t.stopPropagation()))}}focus(){this.shadowRoot?.querySelector("a")?.focus()}render(){if(!this.recentSearchItem)return;const{flair:c,icon:E,isNsfw:T,isQuarantined:I,name:d,path:R,type:m}=this.recentSearchItem;let S,h;if(m!==$.QUERY)S=R;else try{const t=new URL(R,window.location.origin);t.searchParams.set(u.CONVERSATION_ID,s.a.get(e.dQ.Qf)),S=t.toString()}catch{S=R}if(E||T){const e=T?"Recent search not safe for work icon":`${d} icon`,t=T?`${window?.CLIENT_CONFIG?.STATIC_BASE_URL}assets/avatar_over18.png`:E;h=a.x``}else h=function(e){return e===$.SUBREDDIT?a.x`${i.c({size:a.I.Small,attributes:{"aria-hidden":"true",className:"flex items-center justify-center h-100 ml-px"}})}`:e===$.MULTIREDDIT?a.x`${l({size:a.I.Small,attributes:{"aria-hidden":"true",className:"flex items-center justify-center h-100 ml-px"}})} `:r.c({size:a.I.Small})}(m);const k=I?a.x` ${t.c(t.g()[t.C.QUARANTINED])} `:a.x``,p=c?a.x` ${o.a({backgroundColor:c.colorHint?.backgroundColor,className:"text-12 px-sm py-xs",text:c.text,color:"DEFAULT"===c.colorHint?.textColor?e.eL.Dark:c.colorHint?.textColor,richText:c.richtext})} `:a.x``;return n.l({anchorAttributes:{"aria-label":`Recent search for ${d} ${c?.text??""}`,onkeydown:this.handleKeyDown},attributes:{"data-label":m===$.QUERY?d:"",role:"menuitem",tabindex:"-1"},href:S,onClick:this.onClickLink,leadingAvatar:h,label:a.x`
    ${d}
    ${p}
    `,trailingSlot:a.x``,description:k});}};return T.styles=[e.t],e._([e.n({type:Function})],T.prototype,"onClickLink",void 0),e._([e.n({type:Function})],T.prototype,"onClickDismiss",void 0),e._([e.n({type:Object})],T.prototype,"recentSearchItem",void 0),T=e._([e.e(E)],T),{R:E,get S(){return u},get a(){return $},c:l}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./cjhvxMuwOm.js",import.meta.url,"cjhvxMuwOm"); SML.dm("D9SW9I8HSz",["C42E8rVVpA","CsxDAjmHZE","DUzIBJc2in","cjhvxMuwOm"],(async(e,t,o,i)=>{const a=new WeakSet;function n(e,t,o){e&&e.value&&(e.value[t]=o)}class s extends e.R{constructor(){super(...arguments),this.contentSlotRef=e.U(),this.defaultSlotRef=e.U(),this.hovercardBodyRef=e.U(),this.popperRef=e.U(),this.anchorElement=null,this.interactionController=new o.a1(this,{isInteractedWith:e=>e.open,hoverDelayStart:t=>e.bM(getComputedStyle(t).getPropertyValue("--show-delay")),hoverDelayEnd:t=>e.bM(getComputedStyle(t).getPropertyValue("--hide-delay")),delayOpenOnFocus:!0}),this.placement=i.P.Top,this.disabled=!1,this.distance=4,this.open=!1,this.skidding=0,this.trigger="hover focus",this.hoist=!1,this.noAnimate=!1,this.arrow=!1,this.eventUsedMap=new WeakMap,this.handleDocumentKeyDown=e=>{"Escape"===e.key&&(e.stopPropagation(),this.hide(),this.defaultSlotRef.value&&this.focusFirstTabbableElement(this.defaultSlotRef.value))},this.handleDocumentClick=e=>{if(!(e.target instanceof HTMLElement)||this.hidden)return;this.eventUsedMap.has(e)||o.a2(this,e.target)||this.hide()},this.handleLegacyHovercardOpen=e=>{e.target!==this&&this.open&&this.hide()}}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("keydown",this.handleDocumentKeyDown),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("faceplate-hovercard:open",this.handleLegacyHovercardOpen)}willUpdate(e){e.has("open")&&this.hasUpdated&&this.handleOpenChange(),e.has("disabled")&&this.handleDisabledChange(),(e.has("content")||e.has("distance")||e.has("hoist")||e.has("placement")||e.has("skidding"))&&this.handleOptionsChange()}firstUpdated(){this.hovercardBodyRef.value&&(this.hovercardBodyRef.value.hidden=!0),this.open&&this.popperRef.value&&this.handleOpenChange()}startInteraction(e,t){this.eventUsedMap.has(e)||(this.interactionController.interactionTrigger=t,this.eventUsedMap.set(e,!0),this.show())}finishInteraction(e){this.eventUsedMap.set(e,!0),this.hide()}focusFirstTabbableElement(t){const o=e.cD(t)[0];o&&"focus"in o&&"function"==typeof o.focus&&(o.addEventListener("focusin",(e=>{this.eventUsedMap.set(e,!0)}),{once:!0,capture:!0}),o.focus({preventScroll:!0}))}focusFirstTabbableBodyElement(e){return this.focusFirstTabbableElement(e)}async handleOpenChange(){if(!this.disabled&&this.contentSlotRef.value&&this.hovercardBodyRef.value&&this.popperRef.value)if(this.open){this.emitter.dispatch("show"),this.dispatchEvent(new CustomEvent("faceplate-hovercard:open",{bubbles:!0}));const t=(async(t,o="faceplate-partial")=>{const i=o.toLowerCase(),n=e.cC((e=>e.tagName.toLowerCase()===i&&(e=>"loading"in e&&"load"in e&&"function"==typeof e?.load)(e)),t);return(await Promise.all(n.map((async e=>!e||a.has(e)||"programmatic"!==e.loading?Promise.resolve(!1):(a.add(e),e.load().then((()=>!0))))))).filter(Boolean).length>0})(this.contentSlotRef.value);document.addEventListener("keydown",this.handleDocumentKeyDown),document.addEventListener("click",this.handleDocumentClick),document.addEventListener("faceplate-hovercard:open",this.handleLegacyHovercardOpen),await e.bN(this.hovercardBodyRef.value),n(this.hovercardBodyRef,"hidden",!1),n(this.popperRef,"active",!0),this.updateAnchorElementAria();const{keyframes:o,options:i}=e.bO(this,"hovercard.show");await e.bP(this.popperRef.value?.popup,o,i),this.popperRef.value?.reposition(),await t,!this.hovercardBodyRef.value||"focus"!==this.interactionController.interactionTrigger&&"click"!==this.interactionController.interactionTrigger||this.focusFirstTabbableBodyElement(this.hovercardBodyRef.value),this.emitter.dispatch("after-show")}else{this.emitter.dispatch("hide"),document.removeEventListener("keydown",this.handleDocumentKeyDown),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("faceplate-hovercard:open",this.handleLegacyHovercardOpen),await e.bN(this.hovercardBodyRef.value);const{keyframes:t,options:o}=e.bO(this,"hovercard.hide");await e.bP(this.popperRef.value?.popup,t,o),n(this.popperRef,"active",!1),n(this.hovercardBodyRef,"hidden",!0),this.updateAnchorElementAria(),this.emitter.dispatch("after-hide")}}async handleOptionsChange(){this.hasUpdated&&this.popperRef.value&&(await this.updateComplete,this.popperRef.value?.reposition())}handleAnchorSlotChange(){this.defaultSlotRef.value&&(this.anchorElement=e.cC((e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement||["button","link","menuitem","tab","checkbox","combobox","gridcell","application","treeitem"].includes(e?.getAttribute("role")??"")),this.defaultSlotRef.value)[0]??null,this.updateAnchorElementAria())}updateAnchorElementAria(){this.anchorElement?.setAttribute("aria-haspopup","dialog"),this.anchorElement?.setAttribute("aria-expanded",this.open?"true":"false")}handleDisabledChange(){this.disabled&&this.open&&this.hide()}async show(){if(!this.open)return this.open=!0,e.bQ(this,this.emitter.eventId("after-show"))}async hide(){if(this.open)return this.open=!1,e.bQ(this,this.emitter.eventId("after-hide"))}render(){return t.x` `}}return e._([e.n()],s.prototype,"placement",void 0),e._([e.n({type:Boolean,reflect:!0})],s.prototype,"disabled",void 0),e._([e.n({type:Number})],s.prototype,"distance",void 0),e._([e.n({type:Boolean,reflect:!0})],s.prototype,"open",void 0),e._([e.n({type:Number})],s.prototype,"skidding",void 0),e._([e.n()],s.prototype,"trigger",void 0),e._([e.n({type:Boolean})],s.prototype,"hoist",void 0),e._([e.n({type:Boolean,attribute:"no-animate"})],s.prototype,"noAnimate",void 0),e._([e.n({type:Boolean})],s.prototype,"arrow",void 0),e.bL("hovercard.show",{keyframes:[{opacity:0,scale:.8},{opacity:1,scale:1}],options:{duration:150,easing:"ease"}}),e.bL("hovercard.hide",{keyframes:[{opacity:1,scale:1},{opacity:0,scale:.8}],options:{duration:150,easing:"ease"}}),{H:s}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./D9SW9I8HSz.js",import.meta.url,"D9SW9I8HSz");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./cjhvxMuwOm.js",import.meta.url,"cjhvxMuwOm"); SML.dm("DAt93EM4d4",["C42E8rVVpA","D9SW9I8HSz","CsxDAjmHZE","DUzIBJc2in","cjhvxMuwOm"],(async(r,o,a)=>{var e=a.i`${r.Y}:host{--max-width:20rem;--hide-delay:500ms;--show-delay:750ms;display:contents}:host,:host([appearance=neutral]){--rpl-hovercard-background-color:var(--color-neutral-background);--rpl-hovercard-color:var(--color-neutral-content-strong)}:host([appearance=inverted]){--rpl-hovercard-background-color:var(--color-inverted-neutral-background);--rpl-hovercard-color:var(--color-inverted-neutral-content-strong)}.hovercard{--arrow-color:var(--rpl-hovercard-background-color)}.hovercard::part(popup){z-index:var(--rpl-z-index-hovercard,var(--faceplate-hovercard-z-index,1))}.hovercard[placement^=top]::part(popup){transform-origin:bottom}.hovercard[placement^=bottom]::part(popup){transform-origin:top}.hovercard[placement^=left]::part(popup){transform-origin:right}.hovercard[placement^=right]::part(popup){transform-origin:left}.hovercard-body{display:flex;flex-direction:column;width:fit-content;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;border-radius:1rem;box-shadow:var(--elevation-md);z-index:var(--rpl-hovercard-z-index,var(--faceplate-tooltip-z-index,1));font:var(--font-12-16-semibold);background-color:var(--rpl-hovercard-background-color);color:var(--rpl-hovercard-color);padding:8px}`;const t="neutral";let c=class extends o.H{constructor(){super(...arguments),this.appearance=t}};c.styles=e,r._([r.n({type:String,reflect:!0})],c.prototype,"appearance",void 0),c=r._([r.e("rpl-hovercard")],c)})); SML.dm("DFBfgTBypk",[],(async()=>{var e;!function(e){e.ListingBelow="listing-below",e.PostQuerySearch="post-query-search"}(e||(e={}));var t;!function(e){e.Related="related",e.Recent="recent"}(t||(t={}));return{get P(){return t},S:"variant_1",get a(){return e},b:"tabId",c:"variant_2"}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("DMFEgBklTz",["C42E8rVVpA","CsxDAjmHZE","DUzIBJc2in"],(async(t,e,i)=>{const n=[{key:"TOTAL_MRC_VIEWABLE_TIME",playing:!0,threshold:t.bY.VIEWABILITY_THRESHOLD},{key:"TOTAL_AUDIBLE_TIME",playing:!0,threshold:0,withSound:!0},{key:"HALF_DURATION_80_IN_VIEW_AUDIBLE",playing:!0,withSound:!0,threshold:t.bY.EIGHTY_VIEWABILITY_THRESHOLD},{key:"FULL_IN_VIEW_AUDIBLE_TIME",playing:!0,threshold:t.bY.FULL_VIEWABILITY_THRESHOLD,withSound:!0},{key:"FULL_IN_VIEW_TIME",playing:!0,threshold:t.bY.FULL_VIEWABILITY_THRESHOLD},{key:"ANY_IN_VIEW_TIME",playing:!0,threshold:t.bY.VISIBILITY_THRESHOLD},{key:"FIFTY_IN_VIEW_TIME",playing:!0,threshold:t.bY.VIEWABILITY_THRESHOLD},{key:"EIGHTY_IN_VIEW_TIME",playing:!0,threshold:t.bY.EIGHTY_VIEWABILITY_THRESHOLD}];function o(t,e){const i=new URL(t);return Object.entries(e).forEach((([t,e])=>{i.searchParams.set(t,String(e))})),i.toString()}const r=n.map((t=>t.key));const a="noopener nofollow sponsored";let s=class extends e.s{constructor(){super(...arguments),this.impressionId="0",this.clickLocation=t.w.UNKNOWN,this.renderAsButton=!1,this.ButtonProps={},this.anchorStyleClass="",this.isOutboundLinkInitialized=!1}static get styles(){return[t.t,t.K("a {\n color: inherit;\n text-decoration: none;\n}\nbutton {\n all: unset;\n display: inline-block;\n height: 100%;\n width: 100%;\n background: transparent;\n cursor: pointer;\n}\n")]}get effectiveOutboundLink(){const t=this.outboundLinkOverride??(this.outboundLinkUrl||"");return i.ak(t)&&this.metadata?o(t,this.metadata):t}get calculatedTabIndex(){return this.disableKeyboardNav?"-1":""===this.effectiveOutboundLink?"0":void 0}connectedCallback(){super.connectedCallback(),void 0===this.outboundLinkOverride&&(this.outboundLinkUrl=this.getOutboundLinkUrlFromParent(),this.isOutboundLinkInitialized=!0)}updated(t){void 0===this.outboundLinkOverride&&t.has("galleryIndex")&&(this.outboundLinkUrl=this.getOutboundLinkUrlFromParent())}getOutboundLinkUrlFromParent(){const t=i.al(this);if(!t)return;if(void 0===this.galleryIndex)return t.getAttribute("outbound-link-url");const e=t.getAttribute("gallery-items");let n;try{n=JSON.parse(e||"[]")}catch{n=[]}return n[this.galleryIndex]?.outboundUrl}fetchAndUpdateMetadata(){if(!i.ak(this.effectiveOutboundLink))return;const e=i.al(this);if(!e)return;const n=e.getMetadataForPixelEvent(t.bZ.CLICK);n&&(this.metadata=n)}handleClick(e){if("auxclick"===e.type&&1!==e.button)return;void 0!==this.outboundLinkOverride||this.isOutboundLinkInitialized||(this.outboundLinkUrl=this.getOutboundLinkUrlFromParent(),this.isOutboundLinkInitialized=!0),i.am(this.effectiveOutboundLink)&&"_blank"===this.target&&t.b_(this.impressionId),this.fetchAndUpdateMetadata(),i.t({el:this,clickLocation:this.clickLocation,galleryIndex:this.galleryIndex});if(this.clickLocation===t.w.PROMOTED_LABEL&&this.hasAttribute("promoted-label-experiment")||i.an({el:this,clickLocation:this.clickLocation,outboundUrl:this.effectiveOutboundLink,galleryIndex:this.galleryIndex}),function(e){const i=t=>{try{return t()}catch{return null}};let n=i((()=>new URL(e)));return n||(n=i((()=>new URL(e,location.origin)))),!!n&&"1"===n.searchParams.get(t.bX)}(this.effectiveOutboundLink)){const t=this.closest("shreddit-ad-post");if(!t)return;i.ao({impressionId:this.impressionId,adEvents:t.adEvents,clickRedirectUrl:this.effectiveOutboundLink}),i.ap(t.adUserTargeting)}i.am(this.effectiveOutboundLink)&&"contextmenu"!==e.type&&t.at(t.b$)&&(e.preventDefault(),this.fetchAndUpdateMetadata(),window.open(this.effectiveOutboundLink,this.target||"_self"))}render(){const n=this.effectiveOutboundLink||void 0,o=e.x``;if(this.renderAsButton)return t.Z({appearance:i.aq()?"secondary":"bordered",children:o,size:t.ac.Medium,attributes:{href:n,onclick:this.handleClick,oncontextmenu:this.handleClick,target:this.target,rel:a,className:this.anchorStyleClass},...this.ButtonProps});const r=this.effectiveOutboundLink||"_self"===this.target,s=i.j(this.anchorStyleClass,r?"cursor-pointer":"cursor-default");return e.x` ${o} `}};return t._([t.n({type:String,attribute:"outbound-link-override",reflect:!0})],s.prototype,"outboundLinkOverride",void 0),t._([t.n({type:String,attribute:"impression-id"})],s.prototype,"impressionId",void 0),t._([t.n({type:String,attribute:"click-location"})],s.prototype,"clickLocation",void 0),t._([t.n({type:String,attribute:"post-id"})],s.prototype,"postId",void 0),t._([t.n({type:Number,attribute:"gallery-index",reflect:!0})],s.prototype,"galleryIndex",void 0),t._([t.n({type:String})],s.prototype,"target",void 0),t._([t.n({type:Boolean,attribute:"disable-keyboard-nav"})],s.prototype,"disableKeyboardNav",void 0),t._([t.n({type:Boolean,attribute:"render-as-button"})],s.prototype,"renderAsButton",void 0),t._([t.n({type:Object,attribute:"button-props"})],s.prototype,"ButtonProps",void 0),t._([t.n({type:String,attribute:"anchor-style-class"})],s.prototype,"anchorStyleClass",void 0),t._([t.Q("a")],s.prototype,"anchorEl",void 0),t._([t.Q("slot")],s.prototype,"slotEl",void 0),t._([t.v()],s.prototype,"outboundLinkUrl",void 0),t._([t.v()],s.prototype,"metadata",void 0),s=t._([t.e("shreddit-dynamic-ad-link")],s),{get S(){return s},V:n,a:o,b:r,g:t=>t.reduce(((t,e)=>(t[e]={maxContinuousTime:0,currentContinuousTime:0,totalTime:0},t)),{})}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./Bo8KKK1jP_.js",import.meta.url,"Bo8KKK1jP_");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./BFDJQElz9q.js",import.meta.url,"BFDJQElz9q");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("DMLIZ0D7jc",["C42E8rVVpA","Bo8KKK1jP_","CsxDAjmHZE","BFDJQElz9q","DUzIBJc2in"],(async(e,t,s)=>{function i(e){return e?.split(",")}function n(e){const[t,s,i]=e.split("/");return{source:t,action:s,noun:i}}function l(t,s,i){return()=>s.forEach((s=>{const{source:l,action:h,noun:a}=n(s);l&&h&&a&&e.f(t,{source:l,action:h,noun:a,...i})}))}class h{constructor(e,t){this.host=e,this.onChange=t,this.host.addController(this)}hostConnected(){e.ay(this.onChange,{immediate:!0})}hostDisconnected(){e.az(this.onChange)}}class a{constructor(e,t){this.host=e,this.onChange=t,this.host.addController(this)}hostConnected(){e.ax.subscribe(this.onChange)}hostDisconnected(){e.ax.unsubscribe(this.onChange)}}class r{constructor(t,s,i,n){this.lastVisibleTimestamp=0,this.dwellIndex=0,this.visible=!1,this.elapsedTime=0,this.handleEnter=()=>{this.visible||(this.visible=!0,this.lastVisibleTimestamp=Date.now(),this.scheduleNext())},this.handleLeave=()=>{this.pause(),this.visible=!1},this.handleVisibilityChange=()=>{document.hidden?this.pause():this.visible&&(this.lastVisibleTimestamp=Date.now(),this.scheduleNext())},this.checkAndFireDwell=()=>{if(this.visible){if(this.elapsedTime+=Date.now()-this.lastVisibleTimestamp,this.lastVisibleTimestamp=Date.now(),this.dwellIndex=this.dwellTimeMsStack[this.dwellIndex]){const e=this.onDwellStack[this.dwellIndex];e&&e(),this.dwellIndex++}this.dwellIndexnew t.C(this,n(e))));this.controllers.push(new h(this,(e=>i.forEach((t=>t.handleDocumentVisibilityChange(e)))))),this.controllers.push(new a(this,(()=>i.forEach((e=>e.onBeforeUnloadCallback()))))),e.push((()=>i.forEach((e=>e.handleIntersectionObserverEnter())))),s.push((()=>i.forEach((e=>e.handleIntersectionObserverLeave()))))}setupEnterLeaveTracking(){const t=[],s=[],i=[];this.viewEventSANs.length&&this.setupViewEventTracking(t),this.leaveEventSANs.length&&this.setupLeaveEventTracking(i),this.consumeEventSANs.length&&this.setupConsumeEventTracking(t,i),this.loadEventSANs.length&&this.setupLoadEventTracking(s);let n=!1;this.controllers.push(function({host:t,target:s,enterCallback:i,leaveCallback:n,options:l}){const h=new e.b4(t);new e.ar(h,s,l);const a=new e.E(h,(()=>s));return i&&a.define("faceplate-enter",(e=>i(e))),n&&a.define("faceplate-leave",(e=>n(e))),h}({host:this,target:this,enterCallback:t.length||s.length?()=>{t.forEach((e=>e())),n||(n=!0,s.forEach((e=>e())))}:void 0,leaveCallback:i.length?()=>i.forEach((e=>e())):void 0,options:{rootMargin:"0px"}}))}setupDwellEventTracking(){this.dwellEventSANs.length&&this.dwellTriggerTimers?.length&&this.dwellEventSANs.forEach(((e,t)=>{const s=this.dwellTriggerTimers[t].split("/").map(Number),i=s.map((t=>l(this,[e],{...this.trackingContext,timer:{millis:t,referrer:"search_results"}})));this.controllers.push(new r(this,this,s,i))}))}setupLoadEventTracking(e){e.push(l(this,this.loadEventSANs,this.trackingContext))}setupControllers(){this.clickEventSANs.length&&this.setupClickEventTracking(),this.dwellEventSANs.length&&this.setupDwellEventTracking(),!this.viewEventSANs.length&&this.leaveEventSANs.length&&this.consumeEventSANs.length||this.setupEnterLeaveTracking()}tearDownControllers(){for(const t of this.controllers)e.s(this,t);this.controllers=[]}connectedCallback(){super.connectedCallback(),this.disabled||this.setupControllers()}disconnectedCallback(){super.disconnectedCallback(),this.tearDownControllers()}updated(e){super.updated(e),e.has("disabled")&&void 0!==e.get("disabled")&&this[this.disabled?"tearDownControllers":"setupControllers"]()}createRenderRoot(){return this}};return e._([e.n({type:Object,attribute:"data-faceplate-tracking-context"})],c.prototype,"trackingContext",void 0),e._([e.n({attribute:"click-events",converter:i})],c.prototype,"clickEventSANs",void 0),e._([e.n({attribute:"view-events",converter:i})],c.prototype,"viewEventSANs",void 0),e._([e.n({attribute:"leave-events",converter:i})],c.prototype,"leaveEventSANs",void 0),e._([e.n({attribute:"load-events",converter:i})],c.prototype,"loadEventSANs",void 0),e._([e.n({attribute:"consume-events",converter:i})],c.prototype,"consumeEventSANs",void 0),e._([e.n({attribute:"dwell-events",converter:i})],c.prototype,"dwellEventSANs",void 0),e._([e.n({attribute:"dwell-trigger-timers",converter:i})],c.prototype,"dwellTriggerTimers",void 0),e._([e.n({type:Boolean})],c.prototype,"disabled",void 0),c=e._([e.e(o)],c),{S:o}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DQwL-Ar9xx",["CsxDAjmHZE"],(async a=>{const{svg:h}=a.g();return{t:a.m(h``,"0 0 20 20","translate-off")}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./CxBOcTjMlj.js",import.meta.url,"CxBOcTjMlj");SML.di("./BcUlF1uWDA.js",import.meta.url,"BcUlF1uWDA");SML.di("./DW4Y66xecc.js",import.meta.url,"DW4Y66xecc");SML.di("./CndptGkkPK.js",import.meta.url,"CndptGkkPK");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in"); SML.dm("DUaETbwyQ9",["C42E8rVVpA","CsxDAjmHZE","CxBOcTjMlj","BcUlF1uWDA","DW4Y66xecc","CndptGkkPK","DUzIBJc2in"],(async(e,n,t)=>{let i=class extends t.T{constructor(){super(...arguments),this.hasChips=!1,this.hasTrailingContent=!1,this.clearable=!0,this.hideLeadingIconWithInput=!1,this.centerPlaceholder=!1}static get styles(){return[super.styles,n.i`:host{margin:var(--spacer-2xs) var(--spacer-md);display:inline-flex}label{flex-grow:1}input{background:0 0;border:none;outline:0;width:100%;text-overflow:ellipsis}input::placeholder{color:var(--color-neutral-content-weak)}:host([center-placeholder]) .leadingIcon:not(:empty)~.input-container input::placeholder{text-align:center}:host([center-placeholder]) .label-container:not(.label-container-trailing) .leadingIcon:not(:empty)~.input-container input::placeholder{transform:translateX(var(--spacer-sm))}:host([center-placeholder]) .label-container-trailing .leadingIcon:not(:empty)~.input-container input::placeholder{transform:translateX(var(--spacer-lg))}.label-container,:host([faceplate-validity=invalid]) .label-container,:host([faceplate-validity=valid]) .label-container{border:var(--rem2) solid var(--color-input-border);box-shadow:0 0 0 var(--rem2) transparent}.label-container{align-items:center;box-sizing:border-box;border-radius:var(--radius-full);border:var(--rem2) solid var(--color-input-plain-border);padding-inline:var(--spacer-md)}.label-container-chips{background:var(--color-input-plain)}.label-container:focus-within{background:var(--color-input-plain);border-color:var(--color-neutral-border-strong)}@media (hover:hover){.label-container:focus-within:hover,.label-container:hover{background:var(--color-input-secondary-hover)}}:host .label-container{padding-inline-end:var(--spacer-2xs)}:host faceplate-form-helper-text:not(.helper-text-without-label-with-trailing){padding-inline-end:var(--spacer-2xs)}.label-container.label-container-trailing{padding-inline-end:var(--rem2)}.input-container{align-items:center;display:flex;font:var(--font-14-20-regular);position:relative;transform:translateY(0);transition:transform 150ms ease;width:100%;padding-block:var(--spacer-xs)}.leadingIcon{display:inline-flex;font-size:var(--rem16);margin-inline-end:var(--spacer-xs)}:host([hide-leading-icon-with-input]) .label-container:has(input:not(:placeholder-shown)) .leadingIcon{display:none}.label-container-chips slot[name=chips]{display:inline-flex;margin-inline-end:var(--spacer-xs)}.clear-icon-container{height:var(--rem32);width:var(--rem32);flex-shrink:0}.trailing-content-container{display:none;align-items:center;flex-shrink:0}.trailing-content-container.has-trailing-content{display:flex}.trailing-divider{height:var(--rem24);border:0;border-inline-start:var(--rem1) solid var(--color-neutral-border-weak);margin:0;margin-inline-start:var(--spacer-2xs);margin-inline-end:var(--spacer-2xs);flex-shrink:0}.leadingIcon,:slot[name=chips],:slot[name=clearIcon],:slot[name=trailingContent]{display:flex;flex-shrink:0}`]}render(){return n.x` `}};return e._([e.v()],i.prototype,"hasChips",void 0),e._([e.v()],i.prototype,"hasTrailingContent",void 0),e._([e.l({slot:"chips"})],i.prototype,"chipElements",void 0),e._([e.l({slot:"trailingContent"})],i.prototype,"trailingContentElements",void 0),e._([e.Q(".label-container")],i.prototype,"labelContainer",void 0),e._([e.n({type:String})],i.prototype,"enterkeyhint",void 0),e._([e.n({type:String})],i.prototype,"maxlength",void 0),e._([e.n({type:Boolean})],i.prototype,"clearable",void 0),e._([e.n({type:Boolean,attribute:"hide-leading-icon-with-input"})],i.prototype,"hideLeadingIconWithInput",void 0),e._([e.n({type:Boolean,attribute:"center-placeholder"})],i.prototype,"centerPlaceholder",void 0),i=e._([e.e("faceplate-search-input")],i),{get F(){return i}}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DXq5Aj1CdK",["CsxDAjmHZE"],(async a=>{const{svg:h}=a.g();return{n:a.m(h``,"0 0 20 20","new",!0)}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUaETbwyQ9.js",import.meta.url,"DUaETbwyQ9");SML.di("./FcQsMjK8eg.js",import.meta.url,"FcQsMjK8eg");SML.di("./D82XDppqGm.js",import.meta.url,"D82XDppqGm");SML.di("./BYmwHsayzU.js",import.meta.url,"BYmwHsayzU");SML.di("./DMLIZ0D7jc.js",import.meta.url,"DMLIZ0D7jc");SML.di("./CEuDX0j-qf.js",import.meta.url,"CEuDX0j-qf");SML.di("./CPd-IV5dE-.js",import.meta.url,"CPd-IV5dE-");SML.di("./C9S3A50Ur_.js",import.meta.url,"C9S3A50Ur_");SML.di("./BkjgI35gdl.js",import.meta.url,"BkjgI35gdl");SML.di("./B7v2ktuRzR.js",import.meta.url,"B7v2ktuRzR");SML.di("./CeSBv4aKUm.js",import.meta.url,"CeSBv4aKUm");SML.di("./CyHfZd1TKD.js",import.meta.url,"CyHfZd1TKD");SML.di("./CxBOcTjMlj.js",import.meta.url,"CxBOcTjMlj");SML.di("./BgXAJ8KoWz.js",import.meta.url,"BgXAJ8KoWz");SML.di("./DMFEgBklTz.js",import.meta.url,"DMFEgBklTz");SML.di("./CU5rE0Nzqh.js",import.meta.url,"CU5rE0Nzqh");SML.di("./0Jw_Y6qiJT.js",import.meta.url,"0Jw_Y6qiJT");SML.di("./BHU9gAlx9d.js",import.meta.url,"BHU9gAlx9d");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./DFBfgTBypk.js",import.meta.url,"DFBfgTBypk");SML.di("./DmB8tAFMW-.js",import.meta.url,"DmB8tAFMW-"); SML.dm("DYKfbW42IT",["C42E8rVVpA","CsxDAjmHZE","D82XDppqGm","CEuDX0j-qf","CPd-IV5dE-","C9S3A50Ur_","BkjgI35gdl","B7v2ktuRzR","CeSBv4aKUm","CyHfZd1TKD","CxBOcTjMlj","DUzIBJc2in","DFBfgTBypk","DmB8tAFMW-","DUaETbwyQ9","FcQsMjK8eg","BYmwHsayzU","DMLIZ0D7jc","BgXAJ8KoWz","DMFEgBklTz","CU5rE0Nzqh","0Jw_Y6qiJT","BHU9gAlx9d"],(async(e,t,r,i,a,n,s,o,d,h,c,l,p,u)=>{var m;!function(e){e.PRIMARY="primary",e.SECONDARY="secondary"}(m||(m={}));var S,y,b=t.i`${e.Y}:host{border:1px solid var(--rpl-input-chip-border-color);color:var(--rpl-input-chip-text-color);background:var(--rpl-input-chip-background-color);font-weight:600;font-size:var(--rem12)}:host([appearance=bordered]){--rpl-input-chip-border-color:var(--color-neutral-border);--rpl-input-chip-text-color:var(--color-secondary-plain);--rpl-input-chip-disabled-background-color:var(--color-interactive-content-disabled);--rpl-input-chip-disabled-text-color:var(--color-interactive-content-disabled);--rpl-input-chip-disabled-border-color:var(--color-neutral-border-weak);--rpl-input-chip-selected-background-color:var(--color-secondary-background-selected);--rpl-input-chip-selected-border-color:var(--color-neutral-border);--rpl-input-chip-hover-background-color:var(--color-secondary-background-hover)}:host([appearance=media]){--rpl-input-chip-border-color:var(--color-media-border-weak);--rpl-input-chip-background-color:var(--color-media-background);--rpl-input-chip-text-color:var(--color-media-onbackground);--rpl-input-chip-disabled-text-color:var(--color-media-onbackground-disabled);--rpl-input-chip-disabled-background-color:var(--color-media-background);--rpl-input-chip-disabled-border-color:var(--color-media-border-weak);--rpl-input-chip-hover-background-color:var(--color-media-background-hover);--rpl-input-chip-selected-background-color:var(--color-media-background-selected);--rpl-input-chip-selected-border-color:var(--color-media-border-selected)}:host([selected]){--rpl-input-chip-background-color:var(--rpl-input-chip-selected-background-color);--rpl-input-chip-border-color:var(--rpl-input-chip-selected-border-color)}:host([disabled]){--rpl-input-chip-background-color:var(--rpl-input-chip-disabled-background-color);--rpl-input-chip-border-color:var(--rpl-input-chip-disabled-border-color);--rpl-input-chip-text-color:var(--rpl-input-chip-disabled-text-color)}:host([type=in-field]){height:var(--rem20);padding:var(--rem1) 0;border-radius:var(--rem4);align-items:center}:host([type=standalone]){height:var(--rem32);padding-block:calc(var(--rem4) - var(--rem1));padding-inline-start:calc(var(--rem12) - var(--rem1));padding-inline-end:calc(var(--rem6) - var(--rem1));border-radius:var(--rem8)}:host([type=standalone][dragged]){box-shadow:0 var(--rem4) var(--rem8) 0 var(--color-elevation-medium2),0 var(--rem6) var(--rem12) 0 var(--color-elevation-medium1);--rpl-input-chip-background-color:var(--rpl-input-chip-selected-background-color);--rpl-input-chip-border-color:var(--rpl-input-chip-selected-border-color)}:host(.hover:not([disabled])),:host(:hover:not([disabled])){background:var(--rpl-input-chip-hover-background-color)}::slotted([slot=leading]){display:inline-flex;margin-inline-start:var(--spacer-2xs);height:100%}::slotted([slot=trailing]){display:inline-flex}slot:not([name]){width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block}a,button{height:100%;align-items:center}:host([type=in-field]) slot:not([name]){margin-inline-start:calc(var(--rem6) - var(--rem1))}:host([type=standalone]) ::slotted([slot=leading]){margin-block:calc(var(--rem8) - var(--rem1));margin-inline-start:calc(-1 * (var(--rem4) - var(--rem1)));margin-inline-end:var(--rem4)}:host([type=in-field]) ::slotted([slot=trailing]){margin-inline-start:calc(var(--rem6) - var(--rem1));margin-inline-end:calc(var(--rem6) - var(--rem1))}.close-icon-container{height:var(--rem24);width:var(--rem24);display:inline-flex;align-items:center;justify-content:center}`;!function(e){e.Bordered="bordered",e.Media="media"}(S||(S={})),function(e){e.Standalone="standalone",e.InField="in-field"}(y||(y={}));let E=class extends n.R{constructor(){super(...arguments),this.appearance=S.Bordered,this.type=y.InField,this.dragged=!1}static get styles(){return[n.R.styles,b]}renderTrailingContent(){return t.x`${t.A}`}render(){return t.x` ${super.render()} `}};e._([e.n({type:String})],E.prototype,"appearance",void 0),e._([e.n({type:String})],E.prototype,"type",void 0),e._([e.n({type:Boolean})],E.prototype,"dragged",void 0),E=e._([e.e("rpl-input-chip")],E);const{svg:g}=t.g(),v=t.m(g``,"0 0 20 20","trend");function R(t){return!!t&&[e.ah.SearchResults,e.ah.SearchResultsTrending].includes(t)}const T="reddit-recent-searches-partial-container",f="reddit-suggested-search-queries-container",k="search-input",I="search-input-remove-filter",D="search-dropdown-results-container",_="reddit-trending-searches-partial-container",w="reddit-typeahead-results-partial-container",N="/svc/shreddit",x=`${N}/trending-searches`,$={size:t.I.Small,attributes:{"aria-hidden":"true",className:"flex items-center justify-center h-100 ml-px"}};var A,C,L;function O(){return Object.entries(l.v(e.a1.SearchTypeaheadExpanded)??{}).reduce(((e,[t,r])=>(r||e.push(t),e)),[]).join(",")}!function(e){e.Backspace="pill-backspace",e.Click="pill-click"}(A||(A={})),function(e){e.SearchDropdown="search_dropdown"}(C||(C={})),function(e){e.QUERY="query",e.TRENDING="trending",e.TYPEAHEAD="typeahead",e.SUBREDDIT_POST_FLAIR="subreddit_post_flair"}(L||(L={}));class P{constructor(e){this.host=e}async fetchTypeaheadResults(){const t={[r.S.QUERY]:(i=this.host.query,i?i.toLowerCase().trimStart().replace(/\s+/g," "):""),[r.S.CONVERSATION_ID]:a.a.get(e.dQ.Qf)};var i;this.host.recentSearchesController.items.length>0&&(t[r.S.RECENT_SEARCHES_COUNT]=this.host.recentSearchesController.items.length.toString());const n=O();n&&(t[r.S.COLLAPSED_SECTIONS]=n),this.host.activeSearchScopeFlair&&(t[r.S.FLAIR]=this.host.activeSearchScopeFlair);const s=new URLSearchParams(t),o=await this.host.partialRequest.request(`${N}${this.host.activeSearchScope.path}search-typeahead?${s.toString()}`);if(this.host.partialRequest.isRequestInProgress)return;const d=await(o?.text());return d?e.b7(d):void 0}}let F;const U=new Uint8Array(16);function M(){if(!F&&(F="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!F))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return F(U)}var B=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const H=[];for(let e=0;e<256;++e)H.push((e+256).toString(16).slice(1));function q(e,t=0){return(H[e[t+0]]+H[e[t+1]]+H[e[t+2]]+H[e[t+3]]+"-"+H[e[t+4]]+H[e[t+5]]+"-"+H[e[t+6]]+H[e[t+7]]+"-"+H[e[t+8]]+H[e[t+9]]+"-"+H[e[t+10]]+H[e[t+11]]+H[e[t+12]]+H[e[t+13]]+H[e[t+14]]+H[e[t+15]]).toLowerCase()}function z(e){if(!function(e){return"string"==typeof e&&B.test(e)}(e))throw TypeError("Invalid UUID");let t;const r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}function j(e,t,r){function i(e,i,a,n){var s;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r>>9<<4)+1}function V(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function G(e,t,r,i,a,n){return V((s=V(V(t,e),V(i,n)))<<(o=a)|s>>>32-o,r);var s,o}function Y(e,t,r,i,a,n,s){return G(t&r|~t&i,e,t,a,n,s)}function K(e,t,r,i,a,n,s){return G(t&i|r&~i,e,t,a,n,s)}function Z(e,t,r,i,a,n,s){return G(t^r^i,e,t,a,n,s)}function J(e,t,r,i,a,n,s){return G(r^(t|~i),e,t,a,n,s)}j("v3",48,(function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r>5]>>>a%32&255,n=parseInt(i.charAt(r>>>4&15)+i.charAt(15&r),16);t.push(n)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[i/8])<>>32-t}j("v5",80,(function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r>>0;h=d,d=o,o=te(s,30)>>>0,s=a,a=n}r[0]=r[0]+a>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+d>>>0,r[4]=r[4]+h>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]}));const re=/^m\/([\w+-]+)\/?/,ie=/^r\/([\w+-]+)\/?/,ae=/^u\/([\w+-]+)\/?/;class ne{constructor(t){this._items=null,this.syncWithAnotherInstance=e=>{this._items=e.items},this.removeItem=e=>{this.items=this.items.filter((t=>t.uuid!==e)),this.host.requestUpdate()},this.addItem=({clickedElement:e,flairData:t,type:r})=>{const i=this.buildRecentSearchItem({clickedElement:e,flairData:t,type:r});if(!i)return;const a=this.items.filter((e=>e.path!==i.path));a.length>=this.host.maxRecentSearches&&a.pop(),a.unshift(i),this.items=a},this.moveItemToTop=e=>{let t;const r=this.items.reduce(((r,i)=>(i.uuid===e?t=i:r.push(i),r)),[]);t&&(r.unshift(t),this.items=r)},this.extractDropdownItemTrackingContext=t=>{const r=t?.closest(`[data-type="${e.hZ}"]`)?.getAttribute("data-faceplate-tracking-context")??"{}";return JSON.parse(r)},this.extractDropdownItemName=t=>t?.querySelector(`[data-type="${e.h_}"]`)?.textContent,this.buildDropdownItemTrackingContext=(e,t)=>{const r=this.extractDropdownItemTrackingContext(t);return r.search={...e.search,...r.search},delete r.search.impression_id,delete r.search.conversation_id,r},this.getClickedElementHref=e=>{const t=new URL(e.href);return t.searchParams.delete(i.S.ConversationId),t.searchParams.delete(i.S.ImpressionId),t.toString()},this.buildTrendingRecentSearchItem=({baseTrackingContext:e,clickedElement:t,query:i,uuid:a})=>{if(!t)return null;const n=this.getClickedElementHref(t),s=this.extractDropdownItemName(t);if(!s||!n)return null;return{name:s,path:n,rawQuery:i,trackingContext:this.buildDropdownItemTrackingContext(e,t),type:r.a.QUERY,uuid:a}},this.buildTypeaheadRecentSearchItem=({baseTrackingContext:e,clickedElement:t,query:i,uuid:a})=>{if(!t)return null;const n=this.getClickedElementHref(t),s=this.extractDropdownItemName(t);if(!s||!n)return null;const o=this.buildDropdownItemTrackingContext(e,t),d=t.querySelector("faceplate-img,img")?.src,h=!!t.getElementsByClassName("text-alert-caution").length,c=!!t.getElementsByClassName("text-category-nsfw").length;let l=r.a.QUERY;return ie.test(s)?l=r.a.SUBREDDIT:re.test(s)?l=r.a.MULTIREDDIT:ae.test(s)&&(l=r.a.PROFILE),{icon:d,isNsfw:c,isQuarantined:h,name:s,path:n,rawQuery:i,trackingContext:o,type:l,uuid:a}},this.buildSubredditPostFlairRecentSearchItem=({baseTrackingContext:e,flairData:t,uuid:a})=>{if(!t)return null;const n=t?.href,s=t?.chip,o=`${i.g(this.host.activeSearchScope)}`;if(!s||!n||!o)return null;const d=this.host.subreddit?.communityIcon;return{flair:s,icon:d,name:o,path:n,rawQuery:"",trackingContext:e,type:r.a.SUBREDDIT,uuid:a}},this.buildQueryRecentSearchItem=({baseTrackingContext:t,query:a,uuid:n})=>{if(!a)return null;const{activeSearchScope:s,multireddit:o,profile:d,subreddit:h}=this.host,c=i.g(s),l={[e.a2.GLOBAL]:"",[e.a2.COMMUNITY]:h?.communityIcon,[e.a2.CUSTOM_FEED]:o?.icon,[e.a2.PROFILE]:d?.icon}[s.type],p=a.trim();let u=p;s.type!==e.a2.GLOBAL&&(u=`${c} ${u}`);return{icon:l,name:u,path:i.b({cursor:{},query:p,scope:s}),rawQuery:a,trackingContext:t,type:r.a.QUERY,uuid:n}},this.buildRecentSearchItem=({clickedElement:e,flairData:t,type:r})=>{const{activeSearchScope:i,query:a}=this.host,n={search:{query:a,scope_path:i.path,scope_type:i.type}},s=W();switch(r){case L.TRENDING:return this.buildTrendingRecentSearchItem({baseTrackingContext:n,clickedElement:e,query:a,uuid:s});case L.TYPEAHEAD:return this.buildTypeaheadRecentSearchItem({baseTrackingContext:n,clickedElement:e,query:a,uuid:s});case L.SUBREDDIT_POST_FLAIR:return this.buildSubredditPostFlairRecentSearchItem({baseTrackingContext:n,flairData:t,uuid:s});case L.QUERY:return this.buildQueryRecentSearchItem({baseTrackingContext:n,query:a,uuid:s})}},this.host=t}hostDisconnected(){this._items=null}get items(){return this._items=this._items??l.v(e.a1.RecentSearches)??[],this._items}set items(t){this._items=t,l.u(e.a1.RecentSearches,t)}}class se extends t.s{constructor(){super(...arguments),this.scope=e.h$,this.scopedTypeaheadVariant="",this.scopedTypeaheadExperimentName="",this.scopedTypeaheadExperimentVersion="",this.askButtonVariant="",this.askButtonExperimentName="",this.askButtonExperimentVersion="",this.homeRevampVariant="",this.homeRevampExperimentName="",this.homeRevampExperimentVersion="",this.typeaheadDebounceVariant="",this.typeaheadDebounceExperimentName="",this.typeaheadDebounceExperimentVersion="",this.mobileExpandSearchBar=!1,this.isPdpSeekerM2=!1,this.openSearchInSeekerPostQueue=!1,this.suggestedSearchQueries=[],this.showFiltersEntrypoint=!1,this.isSduiZeroStateEnabled=!1,this.typeaheadDebounceDelay=300,this.maxRecentSearches=e.i0,this.showAskButton=!1,this.showAskText=!1,this.showSnooLeadingIcon=!1,this.globalLeaveScreenEventEnabled=!1,this.homeRevampEnabled=!1,this.query="",this.isSearchScopeEnabled=!1,this.trendingSearches=null,this.isFocused=!1,this.typeaheadResults=null,this.showDropdown=!1,this.loadingSearchResults=!1,this.hasFiredScopedTypeaheadExposeEvent=!1,this.hasFiredAskButtonExposeEvent=!1,this.hasFiredHomeRevampExposeEvent=!1,this.hasFiredTypeaheadDebounceExposeEvent=!1,this.isScopedTypeaheadEnabled=!1,this.isScopedTypeaheadPrimaryAdjusterDismissed=!1,this.isScopedTypeaheadSecondaryAdjusterDismissed=!1,this.hasEditedQuery=!1,this.hasFiredDropdownShownInFocusSession=!1,this.isFiltersEntrypointEnabled=!1,this.getPageType=e.x,this.partialRequest=new e.aJ(this),this.exposeClientExperiment=e.an,this.activateFeature=e.j,this.pubsub=new e.m(this),this.sduiTypeaheadRequestController=new P(this),this.recentSearchesController=new ne(this),this.searchScrollBlockingController=null,this.handleDeleteRecentSearchItem=(e,t)=>{e.stopPropagation(),e.preventDefault(),this.recentSearchesController.removeItem(t)},this.handleRecentSearchDataUpdate=(e,t,r)=>{let i;t&&t.target instanceof HTMLElement&&(i="menuitem"===t.target.role?t.target:t.target.closest('[role="menuitem"]')),this.recentSearchesController.addItem({clickedElement:i??void 0,flairData:r,type:e})},this.debouncedSearch=()=>{this.debounceHandler||(this.debounceHandler=e.a7(this.fetchTypeaheadResults,this.typeaheadDebounceDelay)),this.debounceHandler(),this.maybeFireTypeaheadDebounceExposure()},this.handleSearchTypeaheadScopeAdjusterDismiss=({scopedTypeaheadChipDismissed:e})=>{e===m.PRIMARY?(this.isScopedTypeaheadPrimaryAdjusterDismissed=!0,this.isScopedTypeaheadSecondaryAdjusterDismissed=!0,this.isSearchScopeEnabled=!1):e===m.SECONDARY&&(this.isScopedTypeaheadSecondaryAdjusterDismissed=!0),this.typeaheadResults=null,this.focusSearchInput(),this.maybeFetchDropdownItems()},this.handleSearchTypeaheadFlairClick=e=>{this.handleRecentSearchDataUpdate(L.SUBREDDIT_POST_FLAIR,void 0,e)},this.handlePageDataReceived=t=>{const{profile:r,search:i,subreddit:a,multireddit:n}=t;i?.query&&this.pageType===e.ah.SearchResults&&(this.query=i.query),this.subreddit=a||void 0,this.profile=r||void 0,this.multireddit=n||void 0},this.handleEmptyTypeahead=()=>{this.typeaheadResults=null,this.maybeFetchDropdownItems()},this.handleSearchInput=e=>{this.handleQueryChange(e.target.value)},this.handleQueryChange=t=>{this.query!==t&&(a.S.update(e.dQ.Qf),this.query=t,this.hasEditedQuery=!0,t?this.query&&this.debouncedSearch():this.handleEmptyTypeahead())},this.handleSubmit=(e,t=this.activeSearchScope)=>{e.preventDefault(),this.isPdpSeekerM2?this.reloadPostQueueOrRedirect(this.query):(this.handleRecentSearchDataUpdate(L.QUERY),this.redirect(this.getSearchUrl(t)))},this.redirect=e.bU,this.handleClear=()=>{this.handleQueryChange(""),this.input&&this.input.checkVisibility()&&(this.input.value="",this.input.focus())},this.focusSearchInput=()=>{this.input?.focus()},this.handleRemoveFilter=t=>{this.isSearchScopeEnabled&&this.searchScopePillDismissButton&&(e.f(this.searchScopePillDismissButton,{source:"search",action:"click",noun:"disable_scope",action_info:{type:t}}),this.typeaheadResults=null,this.isSearchScopeEnabled=!1,this.focusSearchInput(),this.maybeFetchDropdownItems())},this.handleFilterClick=e=>{e.preventDefault()},this.resetIsSearchScopeEnabled=()=>{this.isSearchScopeEnabled=this.isSearchScopeInitiallyEnabled},this.updateFlairExpansionState=t=>{this.pubsub.publish(e.T.SearchFlairExpansionStateChanged,{isExpanded:t})},this.handleClickAway=e=>{e.target===this||this.shadowRoot.contains(e.target)||this.handleBlur()},this.handleScreenLeaveTracking=()=>{const t=this.closest("shreddit-app"),r=t?._visibilityChange._screenviewId;if(this.globalLeaveScreenEventEnabled){const t={action_info:{page_type:e.ah.SearchDropdown},screenview_id:r};e.f(this,{source:"global",action:"leave",noun:"screen",...t})}t?.screenInstanceIdController.clearCustomId()},this.handleTrendingSearchesClick=e=>{this.handleRecentSearchDataUpdate(L.TRENDING,e),this.isPdpSeekerM2&&this.handlePostQueueActionForItem(e)},this.maybeUpdateDropdownState=()=>{const e=Boolean(this.isFocused&&(this.query&&this.typeaheadResults||!this.query&&this.trendingSearches||!this.query&&this.isSearchScopeEnabled&&this.isScopedTypeaheadEnabled&&this.typeaheadResults));this.searchIsVisible&&this.showDropdown!==e&&(!this.showDropdown&&e?(this.showDropdown=!0,this.hasFiredDropdownShownInFocusSession||this.handleDropdownShown()):this.showDropdown=!1)},this.handleDropdownShown=()=>{this.closest("shreddit-app")?.screenInstanceIdController.requestCustomId("search-dropdown"),e.f(this.searchDropdownResultsContainer,{source:"global",action:"view",noun:"screen",action_info:{page_type:e.ah.SearchDropdown}}),this.dispatchEvent(new Event(l.au)),this.hasFiredDropdownShownInFocusSession=!0},this.renderSeekerSearchQueries=e=>t.x` `,this.handlePostQueueActionForItem=e=>{const t=e.target?.closest("li");t&&t.dataset.label&&(e.preventDefault(),this.reloadPostQueueOrRedirect(t.dataset.label))},this.handleRecentSearchClick=(e,t)=>{this.recentSearchesController.moveItemToTop(t.uuid),this.isPdpSeekerM2&&t.type===r.a.QUERY&&t.name&&(e.preventDefault(),this.reloadPostQueueOrRedirect(t.name))},this.renderRecentSearchItem=r=>{const{trackingContext:i}=r,a=e.Z({appearance:"plain",attributes:{className:e.gf,slot:"dismiss-button-container",tabindex:"-1"},leadingIcon:t.R({size:t.I.Small}),screenReaderContent:this.getRecentSearchDeleteButtonScreenReaderContent(r.name),shape:"pill",size:e.ac.Small});return t.x` ${a} `},this.handleShowFiltersEntrypointUpdate=({isEnabled:e})=>{this.isFiltersEntrypointEnabled=e}}static get styles(){return[e.t,e.K(".search-input {\n -webkit-appearance: none;\n}\n.search-input::-webkit-search-cancel-button {\n display: none;\n}\n@media screen and (max-width: 768px) {\n faceplate-search-input {\n --font-14-20-regular: var(--font-16-20-regular);\n }\n}\n.search-input-wrapper {\n display: flex;\n position: relative;\n border-radius: var(--radius-full);\n}\n.search-input-gradient {\n --color-secondary-background: var(--color-neutral-background);\n --color-input-secondary: var(--color-neutral-background);\n --color-input-secondary-hover: var(--color-neutral-background-hover);\n position: relative;\n height: var(--rem40);\n border: 1px solid var(--color-neutral-border);\n border-radius: var(--radius-full);\n background-color: var(--color-neutral-background);\n}\n.search-input-gradient faceplate-search-input {\n --color-input-plain-border: transparent;\n --color-input-border: transparent;\n}\n.search-input-gradient > * {\n position: relative;\n z-index: 1;\n}\n.search-input-gradient:not(:focus-within) {\n border-color: transparent;\n}\n.search-input-gradient:not(:focus-within)::before {\n content: '';\n position: absolute;\n inset: -1px;\n border: inherit;\n border-radius: inherit;\n background: linear-gradient(var(--color-neutral-background), var(--color-neutral-background)) padding-box, linear-gradient(90deg, var(--color-global-brand-orangered), #FFBF0B) border-box;\n pointer-events: none;\n}\n.search-input-gradient:not(:focus-within)::after {\n content: '';\n position: absolute;\n inset: -1px;\n border: inherit;\n border-radius: inherit;\n background: linear-gradient(var(--color-neutral-background), var(--color-neutral-background)) padding-box, linear-gradient(90deg, var(--color-global-brand-orangered), #FFBF0B) border-box;\n z-index: -1;\n filter: blur(4px);\n opacity: 0.75;\n pointer-events: none;\n}\n.last-dropdown-item [role='menuitem'],\n.last-dropdown-item:hover [role='menuitem'],\n.last-dropdown-item:active [role='menuitem'],\n.last-dropdown-item:focus [role='menuitem'] {\n border-bottom-left-radius: 1.25rem;\n border-bottom-right-radius: 1.25rem;\n}\n.last-dropdown-section:not([open]) summary,\n.last-dropdown-section:not([open]):hover summary,\n.last-dropdown-section:not([open]):active summary,\n.last-dropdown-section:not([open]):focus summary,\n.last-dropdown-section:not([open]) summary [tabindex='-1'],\n.last-dropdown-section:not([open]):hover summary [tabindex='-1'],\n.last-dropdown-section:not([open]):active summary [tabindex='-1'],\n.last-dropdown-section:not([open]):focus summary [tabindex='-1'] {\n border-bottom-left-radius: 1.25rem;\n border-bottom-right-radius: 1.25rem;\n}\n")]}connectedCallback(){super.connectedCallback(),this.pageType=this.getPageType(),this.isSearchScopeEnabled=this.isSearchScopeInitiallyEnabled,this.isScopedTypeaheadEnabled=e.i2(this.scopedTypeaheadVariant),this.query=this.initialQuery??"",this.pubsub.subscribe(e.T.PageDataLoaded,this.handlePageDataReceived),this.shouldFireExposureOnRender()&&this.maybeFireScopedTypeaheadExposure(),this.omitDynamicId&&(a.a.shouldOverrideId=!0,a.S.shouldOverrideId=!0,a.b.shouldOverrideId=!0),this.isSearchScopeEnabled&&this.isScopedTypeaheadEnabled&&(this.pubsub.subscribe(e.T.SearchTypeaheadScopeAdjusterDismiss,this.handleSearchTypeaheadScopeAdjusterDismiss,!1),this.pubsub.subscribe(e.T.SearchTypeaheadFlairClick,this.handleSearchTypeaheadFlairClick,!1)),this.showFiltersEntrypoint&&R(this.pageType)&&this.pubsub.subscribe(e.T.SearchShowFiltersEntrypoint,this.handleShowFiltersEntrypointUpdate)}disconnectedCallback(){super.disconnectedCallback(),this.isFiltersEntrypointEnabled=!1,this.handleBlur(),this.typeaheadResults=null,this.trendingSearches=null}updated(e){this.loadingSearchResults&&(e.has("typeaheadResults")||e.has("trendingSearches"))&&(this.loadingSearchResults=!1)}getAdParam(){return new URL(window.location.href).searchParams.get(i.S.Ad)}hydrateSduiRecentSearches(t){if(!t)return;const i=t.reduce(((e,t)=>{if(t.tagName.toLowerCase()===r.R)e.push(t);else{t.querySelectorAll(r.R).forEach((t=>e.push(t)))}return e}),[]);for(let t=0;tthis.handleRecentSearchClick(e,a),r.onClickDismiss=t=>{this.handleDeleteRecentSearchItem(t,a.uuid),r.remove(),0===this.recentSearchesController.items.length&&this.trendingSearchesContainer?.querySelector(`[id$="${e.i4}"]`)?.remove()}}}async fetchTrendingSearches(){if(this.isSearchScopeEnabled)return;let t;if(this.loadingSearchResults=!0,this.isSduiZeroStateEnabled)t=await this.sduiTypeaheadRequestController.fetchTypeaheadResults(),this.hydrateSduiRecentSearches(t);else{const r=this.getAdParam(),n=new URLSearchParams({[i.S.ConversationId]:a.a.get(e.dQ.Qf),...(r ? {[i.S.Ad]:r} : {})}),s=await this.partialRequest.request(`${x}?${n.toString()}`),o=await(s?.text());t=o?e.b7(o):void 0}t&&this.trendingSearchesContainer&&(this.isSduiZeroStateEnabled||function(t){const r=t.find((t=>t.attributes.getNamedItem(e.ic.IsPromoted)));r&&r.querySelector("[role=menuitem]")?.addEventListener("keydown",(function(e){"Enter"===e.key&&e.target?.dispatchEvent(new MouseEvent("click",{bubbles:!0}))}))}(t),this.trendingSearches=t)}async fetchTypeaheadResults(){const e=this.isSearchScopeEnabled&&!this.isScopedTypeaheadPrimaryAdjusterDismissed&&!this.isScopedTypeaheadEnabled&&!this.query,t=!this.isSearchScopeEnabled&&!this.query;if(e||t)return;this.loadingSearchResults=!0;const r=await this.sduiTypeaheadRequestController.fetchTypeaheadResults();r&&this.typeaheadResultsContainer&&(this.typeaheadResults=r)}get isSearchScopeInitiallyEnabled(){return this.scope.type!==e.a2.GLOBAL&&!document.querySelector("#shreddit-forbidden")}get isSearchSmall(){return this.tagName.toLowerCase()===e.k.SearchInputSmall}get activeSearchScope(){return this.isSearchScopeEnabled?this.scope:e.h$}get activeSearchScopeFlair(){const t=this.scope.type===e.a2.COMMUNITY&&this.scope.flair;return t&&this.isSearchScopeEnabled&&!this.isScopedTypeaheadSecondaryAdjusterDismissed?t:void 0}async maybeFetchDropdownItems(){const e=!this.query,t=!!this.trendingSearches,r=!!this.typeaheadResults,{isSearchScopeEnabled:i,isScopedTypeaheadEnabled:a}=this;i&&this.maybeFireScopedTypeaheadExposure(),!e||t||i?e&&(!a||t)||r||this.debouncedSearch():this.fetchTrendingSearches()}handleFocus(){this.isFocused||(this.isFocused=!0,e.f(this.input,{source:"search",action:"click",noun:"search_bar"}),this.mobileExpandSearchBar&&e.f(this.input,{source:"nav",action:"click",noun:"search_opened"}),this.searchScrollBlockingController?.blockPageScrollingForSearch(),this.maybeFetchDropdownItems(),this.updateFlairExpansionState(!1),this.isSearchSmall&&(this.homeRevampVariant&&!this.hasFiredHomeRevampExposeEvent&&this.maybeFireHomeRevampExposure(),this.askButtonVariant&&!this.hasFiredAskButtonExposeEvent&&this.maybeFireAskButtonExposure()),window.requestAnimationFrame((()=>{window.addEventListener("click",this.handleClickAway)})))}handleBlur(){this.input?.blur(),this.isFocused=!1,window.removeEventListener("click",this.handleClickAway),this.searchScrollBlockingController?.unblockPageScrollingForSearch(),a.S.update(e.dQ.Qf),a.a.set(e.dQ.Qf),this.typeaheadResults=null,this.trendingSearches=null,this.hasFiredDropdownShownInFocusSession=!1,this.isScopedTypeaheadEnabled&&(this.isScopedTypeaheadPrimaryAdjusterDismissed||this.isScopedTypeaheadSecondaryAdjusterDismissed)&&(this.isScopedTypeaheadPrimaryAdjusterDismissed=!1,this.isScopedTypeaheadSecondaryAdjusterDismissed=!1,this.resetIsSearchScopeEnabled()),this.updateFlairExpansionState(!1),this.hasFiredTypeaheadDebounceExposeEvent=!1}getSearchUrl(t){return i.b({conversationId:a.a.get(e.dQ.Qf),cursor:{},impressionId:a.S.getUUID(),query:this.query,flair:this.activeSearchScopeFlair,scope:t})}get searchTelemetryData(){const t={action_info:{pane_name:C.SearchDropdown},search:{conversation_id:a.a.get(e.dQ.Qf),impression_id:a.S.get(e.dQ.Qf),origin_element:"search_bar",origin_page_type:this.pageType??"",query:this.query,query_id:a.b.get({query:this.query,scope:e.h$},e.dQ.Qf),range:e.i5.ALL,sort:e.i6,typeahead_active:this.isFocused}};if(this.isSearchScopeEnabled||this.isSearchScopeTelemetryExperimentEnabled){const{type:r,path:i}=this.isSearchScopeEnabled?this.scope:e.h$;t.search=((t,r,{subreddit_id:i,subreddit_name:a,custom_feed_id:n,scope_type:s,scope_id:o,scope_name:d,scope_path:h}={},c)=>{if(c){const e={...(d ? {scope_name:d} : {}),...(o ? {scope_id:o} : {})};return{...t,...e,scope_type:s,scope_path:h}}return{[e.a2.COMMUNITY]:{...t,subreddit_id:i,subreddit_name:a},[e.a2.CUSTOM_FEED]:{...t,custom_feed_id:n},[e.a2.PROFILE]:t,[e.a2.GLOBAL]:t,[e.a2.PDP]:t}[r]})(t.search,r,{scope_id:this.isSearchScopeEnabled?this.subreddit?.id:"",scope_name:this.isSearchScopeEnabled?this.subreddit?.name:"",scope_type:r,scope_path:i,subreddit_id:this.subreddit?.id,subreddit_name:this.subreddit?.name,custom_feed_id:this.multireddit?.path},this.isSearchScopeTelemetryExperimentEnabled)}return t}handleTypeaheadResultsClick(t,r=L.TYPEAHEAD){const i=document.querySelector("shreddit-good-visit-tracker");i&&(i.pageType=e.ah.SearchDropdown,i.setScreenViewData({...this.searchTelemetryData,action_info:{...this.searchTelemetryData.action_info,page_type:e.ah.SearchDropdown}})),this.handleRecentSearchDataUpdate(r,t),this.isPdpSeekerM2&&this.handlePostQueueActionForItem(t)}get searchIsVisible(){return!0}willUpdate(){this.maybeUpdateDropdownState()}handleDropdownKeyDown(e){"Enter"===e.key&&this.isPdpSeekerM2&&this.handlePostQueueActionForItem(e)}handleKeyDown(t){if("Backspace"!==t.key||this.query||this.scope.type===e.a2.GLOBAL){if("Enter"===t.key&&this.query&&t.target.id===k){const{activeSearchScope:r}=this;e.f(this.input,{...e.i7,source:this.getFullSearchButtonSource()}),this.handleSubmit(t,r)}}else this.isScopedTypeaheadEnabled||this.handleRemoveFilter(A.Backspace)}renderSearchInput(r=!1,a){const n=this.placeholderText||i.c(this.activeSearchScope,this.mobileExpandSearchBar,this.showAskButton,this.homeRevampEnabled),s={action_info:{type:`input-${this.activeSearchScope.type}`}},o=r&&(this.showAskButton||this.homeRevampEnabled)&&!this.isSearchScopeEnabled&&!this.isFocused,d=r||!this.isSearchScopeEnabled||this.isSearchScopeEnabled&&this.isScopedTypeaheadEnabled||this.mobileExpandSearchBar&&!this.isFocused&&!this.showDropdown;return t.x` ${this.renderLeadingIcon()} ${this.renderScopedSearchPill()} ${e.Z({attributes:{className:this.mobileExpandSearchBar&&!this.isFocused?"hidden":"",id:"search-input-clear-button",slot:"clearIcon",type:"button",onclick:this.handleClear,style:!this.showAskButton&&!this.homeRevampEnabled||!this.isSearchScopeEnabled&&this.showAskButton?"":"margin-inline-start: 2px;"},appearance:"plain",size:e.ac.Small,screenReaderContent:"Clear search",leadingIcon:this.showAskButton||this.homeRevampEnabled?t.c({size:t.I.Small,attributes:{style:"color: var(--color-neutral-content-weak);"}}):t.R({size:t.I.Small})})} ${this.showAskButton&&!this.isSearchScopeEnabled?t.x`
    ${this.renderAskButton()}
    `:t.A}
    `;}handleShowFiltersEntrypointClick(){this.pubsub.publish(e.T.SearchActivateFilterModal)}renderShowFiltersEntryPoint(){if(!this.shouldShowFiltersEntrypoint||this.isSearchSmall&&this.isFocused)return t.A;let r="ms-xs",i=e.ac.Medium;return this.isSearchSmall&&(r="ms-[var(--rem6)]",i=e.ac.Small),t.x`${e.Z({appearance:"plain",attributes:{"aria-label":"Open filters menu",className:r,onclick:this.handleShowFiltersEntrypointClick,type:"button"},leadingIcon:u.f({size:t.I.Medium}),size:i})}`;}async maybeFireScopedTypeaheadExposure(){this.scopedTypeaheadVariant&&!this.hasFiredScopedTypeaheadExposeEvent&&this.exposeClientExperiment({experimentName:this.scopedTypeaheadExperimentName,experimentVersion:this.scopedTypeaheadExperimentVersion,variant:this.scopedTypeaheadVariant}).then((()=>{this.hasFiredScopedTypeaheadExposeEvent=!0})).catch((()=>{}))}async maybeFireAskButtonExposure(){this.askButtonVariant&&!this.hasFiredAskButtonExposeEvent&&(this.hasFiredAskButtonExposeEvent=!0,this.exposeClientExperiment({experimentName:this.askButtonExperimentName,experimentVersion:this.askButtonExperimentVersion,variant:this.askButtonVariant}).then((()=>{})).catch((()=>{})))}async maybeFireHomeRevampExposure(){this.homeRevampVariant&&!this.hasFiredHomeRevampExposeEvent&&this.showAskButton&&this.exposeClientExperiment({experimentName:this.homeRevampExperimentName,experimentVersion:this.homeRevampExperimentVersion,variant:this.homeRevampVariant}).then((()=>{this.hasFiredHomeRevampExposeEvent=!0})).catch((()=>{}))}async maybeFireTypeaheadDebounceExposure(){this.typeaheadDebounceVariant&&!this.hasFiredTypeaheadDebounceExposeEvent&&this.exposeClientExperiment({experimentName:this.typeaheadDebounceExperimentName,experimentVersion:this.typeaheadDebounceExperimentVersion,variant:this.typeaheadDebounceVariant}).then((()=>{this.hasFiredTypeaheadDebounceExposeEvent=!0})).catch((()=>{}))}reloadPostQueueOrRedirect(t){if(!this.openSearchInSeekerPostQueue)return this.handleQueryChange(t),this.handleBlur(),this.handleRecentSearchDataUpdate(L.QUERY),void this.redirect(this.getSearchUrl(this.activeSearchScope));this.activateFeature({name:e.bV,queryParams:{context:p.a.PostQuerySearch,q:t,forceScrollToTop:"true",forceLoadFirstPdp:"true",triggerGoodVisit:"true"},renderMode:e.P.Contents}),this.handleQueryChange(t),this.handleBlur()}getRecentSearchDeleteButtonScreenReaderContent(e){return `Delete ${e} from recent searches`;}renderLeadingIcon(){return this.isSearchSmall&&(this.showAskButton||this.homeRevampEnabled)?t.x``:this.showSnooLeadingIcon?t.x`${e.cA(`${e.i9}`)}`:t.A}renderRecentSearches(){const r=this.recentSearchesController.items.map(this.renderRecentSearchItem);return t.x`
      ${r}
    `}renderTrendingSearches(){const r=this.query||!this.trendingSearches;return t.x`
    ${v({attributes:{"aria-hidden":"true",className:"me-2xs"},size:t.I.Small})} ${"TRENDING TODAY"}
    `;}renderTypeaheadResults(r=!1){return t.x``}renderScopedSearchPill(){if(this.scope.type===e.a2.GLOBAL||!this.isSearchScopeEnabled||this.isSearchScopeEnabled&&this.isScopedTypeaheadEnabled)return t.A;const r=i.g({type:this.scope.type,path:this.scope.path}),a={search:{origin_element:i.d.SearchBarPill},...(this.subreddit ? {subreddit:{id:this.subreddit.id,quarantined:this.subreddit.isQuarantined,nsfw:this.subreddit.isNsfw,name:this.subreddit.name}} : {})};return this.showAskButton||this.homeRevampEnabled?t.x` ${this.getChipIcon()} ${t.c({size:t.I.ExtraSmall})} `:l.at({attributes:{id:"search-input-chip",onclick:this.handleFilterClick,slot:"chips",className:this.mobileExpandSearchBar?"max-w-[8rem]":""},deleteButtonConfig:{screenReaderContent:`Remove ${r} filter and expand search to all of Reddit`,attributes:{"data-faceplate-tracking-context":JSON.stringify(a),id:I,onclick:()=>this.handleRemoveFilter(A.Click),type:"button"}},screenReaderContent:`Current search is within ${r}`,selected:!0,leadingIcon:this.getChipIcon(),children:t.x``});}getFullSearchButtonSource(){return this.isPdpSeekerM2?"post_detail":"search"}getChipIcon(){if(this.scope.type===e.a2.GLOBAL)return t.x``;const{defaultIcon:i,iconUrl:a,isScopeNsfw:n}={[e.a2.COMMUNITY]:{defaultIcon:d.c,iconUrl:this.subreddit?.communityIcon,isScopeNsfw:this.subreddit?.isNsfw},[e.a2.CUSTOM_FEED]:{defaultIcon:r.c,iconUrl:this.multireddit?.icon,isScopeNsfw:this.multireddit?.isNsfw},[e.a2.PROFILE]:{defaultIcon:h.p,iconUrl:this.profile?.icon,isScopeNsfw:this.profile?.isNsfw}}[this.scope.type];return n&&!this.isNsfwEnabled?t.x`${t.O($)}`:a?t.x`
    `:t.x`${i($)}`}renderDropdownContent(e){const t=[],r=!this.query,i=this.isSearchScopeEnabled&&this.isScopedTypeaheadEnabled;return this.isPdpSeekerM2&&this.suggestedSearchQueries?.length>0&&!this.hasEditedQuery&&t.push(this.renderSeekerSearchQueries(this.suggestedSearchQueries)),r&&this.recentSearchesController.items?.length&&!i&&!this.isSduiZeroStateEnabled&&t.push(this.renderRecentSearches()),r&&!i?t.push(this.renderTrendingSearches()):t.push(this.renderTypeaheadResults(e)),t}shouldFireExposureOnRender(){return!!this.isSearchScopeEnabled&&(!this.isSearchSmall||this.mobileExpandSearchBar&&Boolean(this.pageType&&this.pageType===e.ah.SearchResults))}get shouldShowFiltersEntrypoint(){return this.showFiltersEntrypoint&&this.isFiltersEntrypointEnabled}renderAskButton(){if(!this.showAskButton||this.isSearchScopeEnabled)return t.A;!this.askButtonVariant||this.hasFiredAskButtonExposeEvent||this.isSearchSmall||this.maybeFireAskButtonExposure(),!this.homeRevampVariant||this.hasFiredHomeRevampExposeEvent||this.isSearchSmall||this.maybeFireHomeRevampExposure();const r=this.searchTelemetryData.search,i=e.ia({conversationID:W(),query:this.query,source:this.pageType===e.ah.SearchResults?e.ib.AskButtonSerp:e.ib.AskButtonTypeahead,upstreamConversationId:r.conversation_id,upstreamImpressionId:r.impression_id,upstreamQuery:this.query,upstreamQueryId:r.query_id,upstreamQueryType:this.pageType===e.ah.SearchResults?"search_ask":"typeahead_ask"});return t.x` ${e.Z({size:e.ac.Small,appearance:"plain",leadingIcon:o.a({size:t.I.Small,attributes:{className:"text-secondary",style:"color:var(--color-upvote-plain-weaker);"}}),children:this.showAskText?"Ask":void 0,attributes:{href:this.query.trim().length>0?i:e.ga,className:"text-neutral-content no-underline hover:no-underline"}})} `;}}return e._([e.n({attribute:"initial-query",type:String})],se.prototype,"initialQuery",void 0),e._([e.n({attribute:"scope",type:Object})],se.prototype,"scope",void 0),e._([e.n({attribute:"omit-dynamic-id",type:Boolean})],se.prototype,"omitDynamicId",void 0),e._([e.n({attribute:"is-nsfw-enabled",type:Boolean})],se.prototype,"isNsfwEnabled",void 0),e._([e.n({attribute:"scoped-typeahead-variant",type:String})],se.prototype,"scopedTypeaheadVariant",void 0),e._([e.n({attribute:"scoped-typeahead-experiment-name",type:String})],se.prototype,"scopedTypeaheadExperimentName",void 0),e._([e.n({attribute:"scoped-typeahead-experiment-version",type:String})],se.prototype,"scopedTypeaheadExperimentVersion",void 0),e._([e.n({attribute:"ask-button-variant",type:String})],se.prototype,"askButtonVariant",void 0),e._([e.n({attribute:"ask-button-experiment-name",type:String})],se.prototype,"askButtonExperimentName",void 0),e._([e.n({attribute:"ask-button-experiment-version",type:String})],se.prototype,"askButtonExperimentVersion",void 0),e._([e.n({attribute:"home-revamp-variant",type:String})],se.prototype,"homeRevampVariant",void 0),e._([e.n({attribute:"home-revamp-experiment-name",type:String})],se.prototype,"homeRevampExperimentName",void 0),e._([e.n({attribute:"home-revamp-experiment-version",type:String})],se.prototype,"homeRevampExperimentVersion",void 0),e._([e.n({attribute:"typeahead-debounce-variant",type:String})],se.prototype,"typeaheadDebounceVariant",void 0),e._([e.n({attribute:"typeahead-debounce-experiment-name",type:String})],se.prototype,"typeaheadDebounceExperimentName",void 0),e._([e.n({attribute:"typeahead-debounce-experiment-version",type:String})],se.prototype,"typeaheadDebounceExperimentVersion",void 0),e._([e.n({attribute:"is-search-scope-telemetry-experiment-enabled",type:Boolean})],se.prototype,"isSearchScopeTelemetryExperimentEnabled",void 0),e._([e.n({type:Boolean,attribute:"mobile-expand-search-bar"})],se.prototype,"mobileExpandSearchBar",void 0),e._([e.n({type:Boolean,attribute:"is-pdp-seeker-m2"})],se.prototype,"isPdpSeekerM2",void 0),e._([e.n({type:Boolean,attribute:"open-search-in-seeker-post-queue"})],se.prototype,"openSearchInSeekerPostQueue",void 0),e._([e.n({type:Array,attribute:"suggested-search-queries"})],se.prototype,"suggestedSearchQueries",void 0),e._([e.n({attribute:"show-filters-entrypoint",type:Boolean})],se.prototype,"showFiltersEntrypoint",void 0),e._([e.n({type:Boolean,attribute:"is-sdui-zero-state-enabled"})],se.prototype,"isSduiZeroStateEnabled",void 0),e._([e.n({type:Number,attribute:"typeahead-debounce-delay"})],se.prototype,"typeaheadDebounceDelay",void 0),e._([e.n({type:String,attribute:"placeholder"})],se.prototype,"placeholderText",void 0),e._([e.n({type:Number,attribute:"max-recent-searches"})],se.prototype,"maxRecentSearches",void 0),e._([e.n({type:Boolean,attribute:"show-ask-button"})],se.prototype,"showAskButton",void 0),e._([e.n({type:Boolean,attribute:"show-ask-text"})],se.prototype,"showAskText",void 0),e._([e.n({type:Boolean,attribute:"show-snoo-leading-icon"})],se.prototype,"showSnooLeadingIcon",void 0),e._([e.n({type:Boolean,attribute:"global-leave-screen-event-enabled"})],se.prototype,"globalLeaveScreenEventEnabled",void 0),e._([e.Q(".search-input",!0)],se.prototype,"input",void 0),e._([e.Q(`#${w}`)],se.prototype,"typeaheadResultsContainer",void 0),e._([e.Q("#typeahead-results-nsfw-section")],se.prototype,"typeaheadResultsNsfwSection",void 0),e._([e.Q(`#${_}`)],se.prototype,"trendingSearchesContainer",void 0),e._([e.Q(`#${T}`)],se.prototype,"recentSearchesContainer",void 0),e._([e.Q(`#${I}`)],se.prototype,"searchScopePillDismissButton",void 0),e._([e.Q(`#${D}`)],se.prototype,"searchDropdownResultsContainer",void 0),e._([e.Q(`#${f}`)],se.prototype,"suggestedSearchResultsContainer",void 0),e._([e.n({type:Boolean,attribute:"home-revamp-enabled"})],se.prototype,"homeRevampEnabled",void 0),e._([e.v()],se.prototype,"query",void 0),e._([e.v()],se.prototype,"subreddit",void 0),e._([e.v()],se.prototype,"profile",void 0),e._([e.v()],se.prototype,"multireddit",void 0),e._([e.v()],se.prototype,"pageType",void 0),e._([e.v()],se.prototype,"isSearchScopeEnabled",void 0),e._([e.v()],se.prototype,"trendingSearches",void 0),e._([e.v()],se.prototype,"isFocused",void 0),e._([e.v()],se.prototype,"typeaheadResults",void 0),e._([e.v()],se.prototype,"showDropdown",void 0),e._([e.v()],se.prototype,"loadingSearchResults",void 0),e._([e.v()],se.prototype,"hasFiredScopedTypeaheadExposeEvent",void 0),e._([e.v()],se.prototype,"hasFiredAskButtonExposeEvent",void 0),e._([e.v()],se.prototype,"hasFiredHomeRevampExposeEvent",void 0),e._([e.v()],se.prototype,"hasFiredTypeaheadDebounceExposeEvent",void 0),e._([e.v()],se.prototype,"isScopedTypeaheadEnabled",void 0),e._([e.v()],se.prototype,"isScopedTypeaheadPrimaryAdjusterDismissed",void 0),e._([e.v()],se.prototype,"isScopedTypeaheadSecondaryAdjusterDismissed",void 0),e._([e.v()],se.prototype,"hasEditedQuery",void 0),e._([e.v()],se.prototype,"hasFiredDropdownShownInFocusSession",void 0),e._([e.v()],se.prototype,"isFiltersEntrypointEnabled",void 0),{R:se,S:D,p:R}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./CHpnYscvgU.js",import.meta.url,"CHpnYscvgU");SML.di("./1i4g9fLWHY.js",import.meta.url,"1i4g9fLWHY");SML.di("./CKuUwv2_dV.js",import.meta.url,"CKuUwv2_dV"); SML.dm("DYzo2YMMuI",["C42E8rVVpA","CsxDAjmHZE","CHpnYscvgU","1i4g9fLWHY","CKuUwv2_dV"],(async(t,a,e)=>{const i=a.s,n="translation-intervention-modal",{I18nPostTranslationOverride:s,I18nCommentTranslationOverride:o}=t.T,r=()=>!!t.a0.getItem(t.a1.I18nTranslationInterventionShown),d=()=>t.a0.setItem(t.a1.I18nTranslationInterventionShown,"true");let l=class extends i{constructor(){super(...arguments),this.translationContextValue=t.aD,this.open=!1,this.pubsub=new t.m(this),this.handleTranslationOverride=t=>{t.isContextUpdateEvent||r()||this.open||(this.translationOverrideActive=t.isTranslationActive,this.translationSourceId=t.id,this.show())},this.show=()=>{r()||(this.open=!0,this.modal?.showModal(),d())},this.close=()=>{this.translationOverrideActive=void 0,this.translationSourceId=void 0,this.open&&(this.modal?.close(),this.open=!1,this.dispatchEvent(new CustomEvent("translation-intervention-modal:close",{bubbles:!0,composed:!0})))},this.getThingTelemetryMetadata=()=>({post:"post"===this.mode?{id:this.translationSourceId,translation_state:!!this.translationOverrideActive}:"mtseo-post"===this.mode?{id:this.translationSourceId}:void 0,comment:"comment"===this.mode?{id:this.translationSourceId,translation_state:!!this.translationOverrideActive}:void 0}),this.handleDismiss=()=>{t.f(this,e.f({isImmersiveTranslationsActive:!!this.translationContextValue.isTranslationActive,isImmersiveVisit:this.isImmersiveVisit,...this.getThingTelemetryMetadata()})),this.close()},this.handleClick=a=>{t.f(this,e.g({actionType:a,isImmersiveTranslationsActive:"keep"===a?!!this.translationContextValue.isTranslationActive:!this.translationContextValue.isTranslationActive,isImmersiveVisit:this.isImmersiveVisit,...this.getThingTelemetryMetadata()})),"keep"===a?this.close():this.handleSubmit()},this.handleSubmit=()=>{"mtseo-post"===this.mode&&t.a0.setItem(t.a1.I18nTranslationInterventionShown,"mtseo-disabled");const a=this.translationOverrideActive;this.dispatchContextUpdateEvent(a),this.close()}}connectedCallback(){super.connectedCallback(),r()||("post"===this.mode&&this.pubsub.subscribe(s,this.handleTranslationOverride,!1),"comment"===this.mode&&this.pubsub.subscribe(o,this.handleTranslationOverride,!1))}dispatchContextUpdateEvent(a){const e=new CustomEvent("update-translation-context",{bubbles:!0,composed:!0,detail:{...this.translationContextValue,isTranslationActive:a}});this.dispatchEvent(e),this.pubsub.publish(t.T.I18nPostTranslationOverride,{isTranslationActive:a,id:"",isContextUpdateEvent:!0,pageType:"feed"===this.pageType?"FEED":"PDP"})}render(){const e=this.translationOverrideActive?{body:"It looks like you know another language. Would you like all your content automatically translated?",confirmButton:"Continue Without Translations",cancelButton:"Turn On Translations"}:{body:"It looks like you know another language. Would you like to keep automatic translations turned on?",confirmButton:"Continue With Translations",cancelButton:"Turn off Translations"};return a.x`

    ${"Update translations on Reddit"}

    ${t.Z({attributes:{"aria-label":"Close","data-testid":"i18n-modal-close-button",onclick:this.handleDismiss},appearance:"secondary",leadingIcon:a.c({size:a.I.Small}),size:t.ac.Small})}
    ${e.body}
    ${t.Z({appearance:"primary",size:t.ac.Large,shape:"pill",attributes:{className:"flex box-border w-full","data-testid":"i18n-modal-confirm-button",onclick:this.handleClick.bind(this,"keep")},children:a.x`${e.confirmButton}`})} ${t.Z({appearance:"secondary",size:t.ac.Large,shape:"pill",attributes:{className:"flex box-border w-full","data-testid":"i18n-modal-cancel-button",onclick:this.handleClick.bind(this,"change")},children:a.x`${e.cancelButton}`})}
    `;}};l.styles=[t.t],t._([t.aC({context:t.aE,subscribe:!0}),t.v()],l.prototype,"translationContextValue",void 0),t._([t.n({type:String,attribute:"mode"})],l.prototype,"mode",void 0),t._([t.n({type:Boolean,attribute:"open"})],l.prototype,"open",void 0),t._([t.n({type:String,attribute:"page-type"})],l.prototype,"pageType",void 0),t._([t.n({type:Boolean,attribute:"is-immersive-visit"})],l.prototype,"isImmersiveVisit",void 0),t._([t.v()],l.prototype,"translationOverrideActive",void 0),t._([t.v()],l.prototype,"translationSourceId",void 0),t._([t.Q(`faceplate-modal.${n}`)],l.prototype,"modal",void 0),l=t._([t.e("translation-intervention-modal")],l)})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DdGGk_VUqP",["CsxDAjmHZE"],(async a=>{const{svg:l}=a.g();return{t:a.m(l``,"0 0 20 20","translate")}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DmB8tAFMW-",["CsxDAjmHZE"],(async c=>{const{svg:s}=c.g();return{f:c.m(s``,"0 0 20 20","filter")}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DoAaOvteiR",["C42E8rVVpA","CsxDAjmHZE"],(async(t,e)=>{var r;!function(t){t.Error="error",t.Success="success",t.Incomplete="incomplete"}(r||(r={}));const s=a(16);function o(t,e){return t-e/100*t}function a(t){return 2*Math.PI*t}let c=class extends e.s{constructor(){super(...arguments),this.value=0,this.status=r.Incomplete}static get styles(){return e.i`:host{--loader-size-base:var(--rem40);display:inline-block;position:relative}:host([status=incomplete]){color:var(--color-neutral-content,var(--color-tone-1))}:host([status=success]){color:var(--color-success-content,var(--color-alert-positive))}:host([status=error]){color:var(--color-danger-content,var(--color-alert-negative))}svg{height:var(--loader-size,var(--loader-size-base));width:var(--loader-size,var(--loader-size-base));fill:none;stroke-width:8;display:block}.bg{stroke:var(--color-neutral-content-disabled,var(--color-tone-3))}.track{stroke:currentColor;transition:.35s stroke-dashoffset;transform:rotate(-90deg);transform-origin:50% 50%}.icon{position:absolute;inset-inline-start:50%;top:50%;transform:translate(-50%,-50%)}::slotted([slot=error]),::slotted([slot=success]){display:flex}`}render(){const t=this.status===r.Success;return e.x`
    `}};t._([t.n({type:Number})],c.prototype,"value",void 0),t._([t.n({type:String,reflect:!0})],c.prototype,"status",void 0),c=t._([t.e("faceplate-progress")],c);var l=Object.freeze({__proto__:null,get FaceplateProgress(){return c},get ProgressState(){return r},calcCircumference:a,calcStokeDashOffset:o});return{get f(){return l}}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DqX5A6FOna",["C42E8rVVpA","CsxDAjmHZE"],(async(t,e)=>{let s=class extends e.s{constructor(){super(...arguments),this.impressionId="0",this.partialSrc="/svc/shreddit/dsa-transparency-modal/",this.getModal=()=>this.querySelector("rpl-dialog-sheet"),this.dispatchCloseDsaTransparencyModalEvent=()=>{this.dispatchEvent(t.c("dsa-transparency-modal-close"))},this.initDialogSheet=()=>{const e=this.getModal();e&&!e.open&&(e.addEventListener("rpl-dialog-sheet:after-show",this.setupButtons),e.addEventListener("rpl-dialog-sheet:hide",this.handleModalHide),e.showModal(),t.f(this,t.b({source:"post",action:"view",noun:"about_this_ad"},{post:{id:this.postId},ad_metadata:{impression_id:this.impressionId,placement:this.placement},screen:{height:window.screen.height,width:window.screen.width}})))},this.onCloseModal=()=>{this.getModal()?.hide()},this.setupButtons=()=>{const t=this.getModal();if(!t)return;const e=t.portalContainer?.querySelector("#dsa-transparency-modal-done");e?.addEventListener("click",this.onCloseModal)},this.handleModalHide=()=>{const t=this.getModal();if(!t||t.open)return;const e=t.portalContainer?.querySelector("#dsa-transparency-modal-done");e?.removeEventListener("click",this.onCloseModal),t.removeEventListener("rpl-dialog-sheet:after-show",this.setupButtons),t.removeEventListener("rpl-dialog-sheet:hide",this.handleModalHide),this.dispatchCloseDsaTransparencyModalEvent()},this.initModal=()=>this.initDialogSheet()}render(){return e.x``}};s.styles=[t.t],t._([t.n({type:Boolean,attribute:"is-desktop"})],s.prototype,"isDesktop",void 0),t._([t.n({type:String,attribute:"post-id"})],s.prototype,"postId",void 0),t._([t.n({type:String,attribute:"impression-id"})],s.prototype,"impressionId",void 0),t._([t.n({type:String,attribute:"placement"})],s.prototype,"placement",void 0),s=t._([t.e("dsa-transparency-modal")],s)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("DrM-WGXCsZ",["C42E8rVVpA","CsxDAjmHZE"],(async(t,e)=>{var a;!function(t){t.PLAIN="plain",t.MEDIA="media"}(a||(a={}));const i=12;let r=class extends e.s{constructor(){super(...arguments),this.pages=0,this.pageIndex=0,this.appearance=a.PLAIN,this.animationDuration=0,this.containerLabel="",this.numVisible=2,this.centerIndexPosition=3,this.setTransitionDuration=async()=>{this._dotsContainer&&(await this.updateComplete,this._dotsContainer.style.setProperty("--pagination-transition-duration",`${this.animationDuration}ms`))},this.animateInfiniteCurrentPage=t=>{if(this._currentPageIndicator){const e=[{transform:t?`translateX(${i*this.pages}px)`:"translateX(-12px)",opacity:0},{opacity:0,transform:t?"translateX(-12px)":`translateX(${i*this.pages}px)`},{opacity:1,transform:t?"translateX(0px)":`translateX(${i*(this.pages-1)}px)`}],a={duration:this.animationDuration,fill:"forwards",iterations:1};this.setDotsTrackTransform(!t),this._currentPageIndicator.animate(e,a)}},this.animateCurrentPage=async()=>{this.setDotsTrackTransform(),this.animateCurrentPageNumber()},this.animateCurrentPageNumber=()=>{if(this._currentPageIndicator){const t=[{width:"var(--rem6)"},{width:"var(--rem18)",borderRadius:"4px"},{width:"var(--rem6)",transform:`translateX(${i*this.pageIndex}px)`}],e={duration:this.animationDuration,fill:"forwards",iterations:1};this._currentPageIndicator.animate(t,e)}},this.onSelect=t=>{const e=new CustomEvent("pagination-click",{detail:{pageIndex:t},bubbles:!0,composed:!0});this.dispatchEvent(e)},this.isEdgeDot=t=>{if(this.pages>=6){const e=t===this.pageIndex-3,a=t===this.pageIndex+3;return e||a}return!1},this.getDotButton=a=>{const i=Math.abs(a-this.pageIndex),r=t=>t===this.pageIndex?`(${this.currentPageLabel??"Current Page"})`:"",n=this.getPageLabels?`${this.getPageLabels(a)} ${r(a)}`:`Page ${a+1} ${r(a)}`,o=0===i||1===i;return e.x``},this.render=()=>{if(0!==this.pages)return e.x`
    ${this.currentPageIndicator} ${[...Array(this.pages).keys()].map(((t,e)=>this.getDotButton(e)))}
    `}}static get styles(){return e.i`:host{display:inline-flex;height:var(--rem16,1rem);width:100%;justify-content:center}:host(:dir(rtl)){transform:scaleX(-1)}:host #dots-container{display:inline-flex;position:relative;height:100%;overflow:hidden;align-items:center;border-radius:var(--rem8,.5rem);padding:0 var(--rem2,.125rem);transition:width ease-in-out var(--pagination-transition-duration)}:host .dots-track-container{position:relative;height:100%;width:100%;display:flex;align-items:center}:host #dots-track{display:flex;position:absolute;inset-inline-start:0;height:var(--rem12,.75rem);overflow:hidden;box-sizing:border-box;font-size:var(--rem10,.625rem);align-items:center;transition:transform ease-in-out var(--pagination-transition-duration)}:host([appearance=media]) #dots-container{background-color:var(--color-media-background)}:host([appearance=media]) .dot{background-color:var(--color-media-onbackground-disabled)}:host .dot:focus-visible{outline:solid 1px var(--color-global-focus)}:host([appearance=media]) #current-page-indicator.number{color:var(--color-media-onbackground)}:host([appearance=media]) #current-page-indicator.dot{background-color:var(--color-media-onbackground)}:host #current-page-indicator{z-index:2;position:absolute}:host #current-page-indicator.number{color:var(--color-neutral-content);display:flex;align-items:center;justify-content:center;transition:transform ease-in-out var(--pagination-transition-duration)}:host #current-page-indicator.dot{background-color:var(--color-neutral-content)}:host .dot{height:var(--rem6,.375rem);width:var(--rem6,.375rem);border-radius:50%;box-sizing:content-box;display:inline-block;margin:calc(var(--rem2,.125rem) + var(--rem1,.0625rem));padding:0;border:none}:host #current-page-indicator.number{height:var(--rem15,.9375rem);width:var(--rem16,1rem);margin:0}:host .dot{background-color:var(--color-neutral-border);background-clip:content-box;transition:all ease-in-out var(--pagination-transition-duration)}:host .dot[tabindex='0']{cursor:pointer}:host .dot:focus{transition:none}:host .dot.edge{transform:scale(.5);flex-shrink:0}`}willUpdate(t){t.has("pageIndex")&&(this.pageIndex<0||this.pageIndex>this.pages-1)&&(this.pageIndex=0)}async updated(t){await this.updateComplete,(t.has("pageIndex")||t.has("pages"))&&this.shrinkOrStretch();const e=t.get("pageIndex")===this.pages-1&&0===this.pageIndex,a=0===t.get("pageIndex")&&this.pageIndex===this.pages-1;e||a?this.animateInfiniteCurrentPage(e):t.has("pageIndex")&&await this.animateCurrentPage(),t.has("animationDuration")&&this.setTransitionDuration()}shrinkOrStretch(){this.pages>=6?0===this.pageIndex||this.pageIndex===this.pages-1?this.numVisible=4:1===this.pageIndex||this.pageIndex===this.pages-2?this.numVisible=5:2===this.pageIndex||this.pageIndex===this.pages-3?this.numVisible=6:this.pageIndex>=3&&this.pageIndex<=this.pages-4&&(this.numVisible=7):this.numVisible=this.pages,this._dotsContainer&&(this._dotsContainer.style.width=`calc(var(--rem12, 0.75rem) * ${this.numVisible})`)}setDotsTrackTransform(t){const e=this.pageIndex-this.centerIndexPosition,a=e>0?e:0;if(this._dotsTrack){const e=`translateX(${i*a*-1}px)`;e!==this._dotsTrack.style.transform?this._dotsTrack.style.transform=e:t&&"translateX(0px)"!==this._dotsTrack.style.transform&&(this._dotsTrack.style.transform="translateX(0px)")}}get currentPageIndicator(){return e.x``}};return t._([t.n({type:Number})],r.prototype,"pages",void 0),t._([t.n({type:Number,attribute:"page-index"})],r.prototype,"pageIndex",void 0),t._([t.n({type:String})],r.prototype,"appearance",void 0),t._([t.n({type:Number,attribute:"animation-duration"})],r.prototype,"animationDuration",void 0),t._([t.n({type:String,attribute:"current-page-label"})],r.prototype,"currentPageLabel",void 0),t._([t.n()],r.prototype,"getPageLabels",void 0),t._([t.n({type:String,attribute:"container-label"})],r.prototype,"containerLabel",void 0),t._([t.Q("#dots-container")],r.prototype,"_dotsContainer",void 0),t._([t.Q("#dots-track")],r.prototype,"_dotsTrack",void 0),t._([t.Q("#current-page-indicator")],r.prototype,"_currentPageIndicator",void 0),t._([t.aY(".dot")],r.prototype,"_dots",void 0),r=t._([t.e("faceplate-pagination-indicator")],r),{get P(){return a}}})); SML.dm("JaGlTj3I-9",[],(async()=>{var e;!function(e){e[e.bold=1]="bold",e[e.italic=2]="italic",e[e.underline=4]="underline",e[e.strikethrough=8]="strikethrough",e[e.subscript=16]="subscript",e[e.superscript=32]="superscript",e[e.monospace=64]="monospace"}(e||(e={}));const r={LEFT:"L",RIGHT:"R",CENTER:"C"};return{A:"gif",B:"blockquote",C:"c/",E:"embed",get F(){return e},H:"hr",I:"img",L:"br",P:"par",R:"raw",S:"spoilertext",T:"table",U:"@",V:"video",a:"p/",b:"emoji",c:"code",d:"h",e:"li",f:"list",g:"u/",h:"r/",i:"link",j:"text",k:r,l:"L",m:"C",n:"R"}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA"); SML.dm("K26PgUrfyw",["C42E8rVVpA"],(async t=>{const e={next:"nextElementSibling",prev:"previousElementSibling"};var r,s;!function(t){t.FEED="feed",t.COMMENTS_PAGE="comments_page"}(r||(r={})),function(t){t.NEXT="next",t.PREV="prev"}(s||(s={}));return{get P(){return s},a:class{constructor(s,n){this.cache={},this.isPostOrComment=t=>["shreddit-comment","shreddit-post","shreddit-ad-post","shreddit-profile-comment"].includes(t?.tagName.toLowerCase()??""),this.traverse=t=>{const e=this.current;this._current?this.findPostOrComment(t):this._current=this.options.getFirstElement(),this.focusElement(e)},this.focusElement=e=>{if(!this.current||e===this.current)return;const s=document.activeElement;this.current?.onHotkeysFocus?this.current.onHotkeysFocus?.({preventScroll:!0}):this.current.hotkeyController?.onFocus?.({preventScroll:!0}),s===document.activeElement&&t.aU(this.current)?.focus(),this.current.style.scrollMarginTop="var(--shreddit-header-height)";const n=this.isCurrentComment?"start":this.options.type===r.COMMENTS_PAGE?"end":"center";this.current.scrollIntoView({behavior:"instant",block:n})},this.findPostOrComment=t=>{let r=this._current;for(let s=0;r&&s{const r=new WeakSet,n=async(t,{includeShadowRoot:s=!1}={})=>{const i="faceplate-partial",o=Array.from(t.querySelectorAll(i));s&&o.push(...Array.from(t.shadowRoot?.querySelectorAll(i)??[]));return(await Promise.all(o.map((async t=>!t||r.has(t)||t.loading!==e.q.Programmatic?Promise.resolve(!1):(r.add(t),t.load().then((()=>!0))))))).filter(Boolean).length>0},a=e=>t=>(e(t),t);let h=class extends o.FaceplateTooltip{constructor(){super(...arguments),this.mouseEnterDelay=750,this.mouseLeaveDelay=500,this.closeOnTrack=!1,this.disableTouchActivation=!1,this.partialLoading=e.q.Action,this.label="",this.mouseOnly=!1,this.sleepAfterEscape=!1,this.enterTimeout=-1,this.leaveTimeout=-1,this._popperController=new s.P(this,{position:this.position,referenceElementKey:"referenceElement",popperElementKey:"_tooltip"}),this._isHandlingTouch=!1,this.cleanupTimeouts=()=>{this.enterTimeout=this.leaveTimeout=-1},this.triggerEvent="hover",this.emitter=i.l(this),this.handleFocusOut=e=>{const t=e.relatedTarget;this.hidden||this.hasUserInteraction(t)||(this.close(),this.anchorEl&&(this.sleepAfterEscape=!0,this.anchorEl?.focus({preventScroll:!0})))},this.rplHovercardShowHandler=e=>{e.target===this||this.hidden||this.close()},this.onEscape=e=>{"Escape"===e.key&&(this.sleepAfterEscape=!0,this.close(),this.trigger?.focus())},this.mouseOverTrigger=e=>{this.setAttribute("trigger","mouse"),this.handleMouseenter(e)},this.handleClick=e=>{"hover"===this.triggerEvent&&this._isHandlingTouch&&this.disableTouchActivation&&(this.cleanupTimeouts(),this._isHandlingTouch=!1),super.handleClick(e)},this.handleTouchstart=()=>{this._isHandlingTouch=!0},this.handleMouseenter=t=>{if(this.mouseOnly&&"focusin"===t?.type)return;if(this.sleepAfterEscape)return void(this.sleepAfterEscape=!1);if(!this.hidden)return this.cleanupTimeouts();this.emitter.dispatch("entered"),this.partialLoading===e.q.Intent&&this.load();const s=window.setTimeout((()=>{s===this.enterTimeout&&this.hasUserInteraction()&&this.show()}),this.mouseEnterDelay);this.enterTimeout=s,document.addEventListener("keydown",this.onEscape),t?.currentTarget?.addEventListener("mouseleave",this.handleMouseleave,{once:!0})},this.handleMouseleave=()=>{if(this.hidden)return this.cleanupTimeouts();const e=window.setTimeout((()=>{e===this.leaveTimeout&&this.close()}),this.mouseLeaveDelay);this.leaveTimeout=e},this.handleMouseEnterTooltip=()=>{this.cleanupTimeouts()},this.handleMouseLeaveTooltip=()=>{this.handleMouseleave(),document.removeEventListener("keydown",this.onEscape)},this.handleFaceplateTrack=()=>{this.closeOnTrack&&this.close()},this.handleSlotChange=()=>{this.initializeFocusManager(),!this.hidden&&this.focusManager?.focus()},this.initializeFocusManager=()=>{this.content&&(this.focusManager=new e.aA(this,this.content))},this.render=()=>{const e=this._popperController.actualPosition||this.position;return t.x` `}}get content(){return this.contents[0]??null}get trigger(){return this.anchorEl??this.triggers[0]??null}get anchorEl(){try{if(this.anchor&&"string"==typeof this.anchor){return this.getRootNode().getElementById(this.anchor)}return this.anchor instanceof HTMLElement?this.anchor:null}catch{return null}}get referenceElement(){return this.trigger??this}setupAnchorElListeners(){const{anchorEl:e}=this;e&&(e.addEventListener("click",this.handleClick),e.addEventListener("touchstart",this.handleTouchstart),e.addEventListener("mouseenter",this.mouseOverTrigger),e.addEventListener("mouseleave",this.handleMouseleave),e.addEventListener("focusin",this.handleMouseenter),e.addEventListener("focusout",this.handleMouseleave))}cleanupAnchorElListeners(){const{anchorEl:e}=this;e&&(e.removeEventListener("click",this.handleClick),e.removeEventListener("touchstart",this.handleTouchstart),e.removeEventListener("mouseenter",this.mouseOverTrigger),e.removeEventListener("mouseleave",this.handleMouseleave),e.removeEventListener("focusin",this.handleMouseenter),e.removeEventListener("focusout",this.handleMouseleave))}hasUserInteraction(e){const t=Boolean(this.querySelector(":hover")||this.trigger?.matches(":hover")),s=Boolean(e&&(this.contains(e)||this.trigger?.contains(e))||this.querySelector(":focus")||this.trigger?.matches(":focus"));return t||s}hovercardShowHandler(e){e.target!==this&&this.close()}load(){return n(this).then(a(this._popperController.reposition)).then(a((e=>{this.hidden||e&&(this.focusManager?.refresh(),this.focusManager?.focus())})))}async show(){super.show(),this.partialLoading===e.q.Action&&this.load(),await this._popperController.currentState.animationFinished,this.focusManager?.focus(),this.addEventListener("focusout",this.handleFocusOut),document.addEventListener(this.emitter.eventId("open"),this.hovercardShowHandler),document.addEventListener("rpl-hovercard:show",this.rplHovercardShowHandler),this.cleanupTimeouts()}async close(){const e=super.close();document.removeEventListener(this.emitter.eventId("open"),this.hovercardShowHandler),document.removeEventListener("rpl-hovercard:show",this.rplHovercardShowHandler),this.cleanupTimeouts(),await e,this.removeTrigger()}removeTrigger(){this.removeAttribute("trigger")}handleKeydown(){this.removeTrigger()}connectedCallback(){super.connectedCallback(),this.setupAnchorElListeners()}disconnectedCallback(){this.cleanupAnchorElListeners(),super.disconnectedCallback(),this.cleanupTimeouts()}static get styles(){return[...super.styles,t.i`:host{display:contents}#faceplate-tooltip{display:flex;flex-direction:column;width:fit-content;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;border-radius:1rem;box-shadow:var(--elevation-md);z-index:var(--faceplate-hovercard-z-index,1)}#faceplate-tooltip::after{display:none}`]}};e._([e.n({type:String})],h.prototype,"anchor",void 0),e._([e.l({slot:""})],h.prototype,"triggers",void 0),e._([e.l({slot:"content"})],h.prototype,"contents",void 0),e._([e.n({type:Number,attribute:"enter-delay"})],h.prototype,"mouseEnterDelay",void 0),e._([e.n({type:Number,attribute:"leave-delay"})],h.prototype,"mouseLeaveDelay",void 0),e._([e.n({type:Boolean,attribute:"close-on-track"})],h.prototype,"closeOnTrack",void 0),e._([e.n({type:Boolean,attribute:"disable-touch-activation",reflect:!0})],h.prototype,"disableTouchActivation",void 0),e._([e.n({type:String,attribute:"partial-loading"})],h.prototype,"partialLoading",void 0),e._([e.n({type:String})],h.prototype,"label",void 0),e._([e.n({type:Boolean,attribute:"mouse-only"})],h.prototype,"mouseOnly",void 0),e._([e.v()],h.prototype,"sleepAfterEscape",void 0),h=e._([e.e("faceplate-hovercard")],h);var l=Object.freeze({__proto__:null,get FaceplateHovercard(){return h}});return{get F(){return h},get f(){return l},l:n,s:a}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DXq5Aj1CdK.js",import.meta.url,"DXq5Aj1CdK");SML.di("./BxXMRtW0Ao.js",import.meta.url,"BxXMRtW0Ao");SML.di("./CdpPgPWvJM.js",import.meta.url,"CdpPgPWvJM"); SML.dm("Lp7s0JcW39",["C42E8rVVpA","CsxDAjmHZE","DXq5Aj1CdK","BxXMRtW0Ao","CdpPgPWvJM"],(async(a,e,n,t,r)=>{const{svg:s}=e.g(),o=e.m(s``,"0 0 20 20","peace-outline"),i="mod-notes-rail",l=`/svc/shreddit/${i}/r/:subredditName/u/:userName/:subredditId/:userId/:thingId/:triggerSource/:postId/:conversationId`;var N,m;!function(a){a.USERNAME="username",a.USER_HOVER_CARD="user-hover-card",a.MODMAIL_USERNAME="modmail-username"}(N||(N={})),function(a){a.Overview="overview",a.Log="log",a.Posts="posts",a.Comments="comments"}(m||(m={}));const u=[{getButtonText:()=>"Overview",slot:m.Overview},{getButtonText:()=>"Log",slot:m.Log},{getButtonText:()=>"Posts",slot:m.Posts},{getButtonText:()=>"Comments",slot:m.Comments}],I={[a.cG.HelpfulUser]:()=>"Helpful",[a.cG.SolidContributor]:()=>"Good Contributor",[a.cG.SpamWatch]:()=>"Spam Watch",[a.cG.SpamWarning]:()=>"Spam Warning",[a.cG.AbuseWarning]:()=>"Abuse Warning",[a.cG.Ban]:()=>"Ban",[a.cG.BotBan]:()=>"Bot ban",[a.cG.PermaBan]:()=>"Perma ban",[a.cG.UserSummary]:()=>"Summary"},R=[{label:()=>"None",icon:()=>""},{label:I[a.cG.HelpfulUser],icon:(a=e.I.Medium,n)=>o({size:a,attributes:{className:n}}),gqlLabel:a.cG.HelpfulUser},{label:I[a.cG.SolidContributor],icon:(a=e.I.Medium,t)=>n.n({size:a,attributes:{className:t}}),gqlLabel:a.cG.SolidContributor},{label:I[a.cG.SpamWatch],icon:(a=e.I.Medium,n)=>t.n({size:a,attributes:{className:n}}),gqlLabel:a.cG.SpamWatch},{label:I[a.cG.SpamWarning],icon:(a=e.I.Medium,n)=>r.c({size:a,attributes:{className:n}}),gqlLabel:a.cG.SpamWarning},{label:I[a.cG.AbuseWarning],icon:(a=e.I.Medium,n)=>r.c({size:a,attributes:{className:n}}),gqlLabel:a.cG.AbuseWarning}];return{get M(){return m},N:R,get a(){return N},b:u,c:"mod-notes-rail-loading",d:i,e:l,f:20}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DMFEgBklTz.js",import.meta.url,"DMFEgBklTz"); SML.dm("RDJ1iNIxln",["C42E8rVVpA","CsxDAjmHZE","DMFEgBklTz"],(async(t,e)=>{let r=class extends e.s{constructor(){super(...arguments),this.postId="",this.impressionId="0",this.clickLocation=t.w.UNKNOWN,this.anchorStyleClass="",this.renderAsButton=!1,this.buttonProps={},this._currGalleryIndex=0,this._currGalleryItemText="",this.handleGalleryNavEvent=t=>{t!==this._currGalleryIndex&&(this._currGalleryIndex=t,this.galleryContent&&(this._currGalleryItemText=this.galleryContent[this._currGalleryIndex]))}}connectedCallback(){super.connectedCallback(),this._currGalleryItemText=this.galleryContent?.[this._currGalleryIndex]}createRenderRoot(){return this}render(){return this.galleryContent&&!this._currGalleryItemText?e.A:e.x` ${this._currGalleryItemText}`}};r.styles=[t.t],t._([t.n({type:String,attribute:"post-id"})],r.prototype,"postId",void 0),t._([t.n({type:String,attribute:"impression-id"})],r.prototype,"impressionId",void 0),t._([t.n({type:String,attribute:"click-location"})],r.prototype,"clickLocation",void 0),t._([t.n({type:String})],r.prototype,"target",void 0),t._([t.n({type:String,attribute:"anchor-style-class"})],r.prototype,"anchorStyleClass",void 0),t._([t.n({type:Boolean,attribute:"render-as-button"})],r.prototype,"renderAsButton",void 0),t._([t.n({type:Object,attribute:"button-props"})],r.prototype,"buttonProps",void 0),t._([t.n({type:Array,attribute:"gallery-content"})],r.prototype,"galleryContent",void 0),t._([t.v()],r.prototype,"_currGalleryIndex",void 0),t._([t.v()],r.prototype,"_currGalleryItemText",void 0),r=t._([t.e("call-to-action-gallery-links")],r)})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("UD2pUVjMzE",["CsxDAjmHZE"],(async e=>{const{svg:t}=e.g();return{E:"scroll-to-comments-complete",a:e=>{let t=!1;const o=()=>{t||(t=!0,e(),window.removeEventListener("scroll",r),window.removeEventListener("scrollend",o),clearTimeout(s),clearTimeout(n))};let n;const r=()=>{clearTimeout(n),n=setTimeout(o,100)};"onscrollend"in window?window.addEventListener("scrollend",o,{once:!0}):window.addEventListener("scroll",r);const s=setTimeout(o,1e3)},e:e.m(t``,"0 0 20 20","expand-left"),s:async function(e){const t=document.querySelector("shreddit-comments-page-tools, comment-body-header"),o=document.querySelector("nav")?.offsetHeight??0,n=document.getElementById("pdp-seeker-mweb-return-to-results")?.offsetHeight??0,r=document.querySelector("shreddit-comment-tree");if(!t||!r)return;await r.updateComplete;const s=t.offsetTop;await requestAnimationFrame((()=>{window.scrollTo({top:s-(o+n),behavior:e})}))}}})); SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE"); SML.dm("clzw02fdiy",["CsxDAjmHZE"],(async l=>{const{svg:h}=l.g();return{r:l.m(h``,"0 0 20 20","report")}})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./7ymiBBk8xO.js",import.meta.url,"7ymiBBk8xO");SML.di("./DRDo-q4GrF.js",import.meta.url,"DRDo-q4GrF");SML.di("./C-4AJ2Y78L.js",import.meta.url,"C-4AJ2Y78L");SML.di("./hqZhqS6qH4.js",import.meta.url,"hqZhqS6qH4");SML.di("./C-IW_ZM7he.js",import.meta.url,"C-IW_ZM7he"); SML.dm("emUZFej5Bs",["C42E8rVVpA","CsxDAjmHZE","DUzIBJc2in","7ymiBBk8xO","DRDo-q4GrF","C-4AJ2Y78L","hqZhqS6qH4","C-IW_ZM7he"],(async(e,t,i,a)=>{var n,r;!function(e){e.Scheduled="scheduled",e.Live="live",e.Ended="ended",e.Unavailable="unavailable"}(n||(n={}));let s=r=class extends t.s{constructor(){super(...arguments),this.isReminderSet=!1,this.eventState=n.Scheduled,this.postId="",this.permalink="",this.pdpTarget="_self",this.isPdp=!1,this.isLoggedIn=!1,this.isDesktopViewport=!1,this.shouldFireEngagedClick=!1,this.enableUserActionTriggeredModal=!1,this.requestInProgress=!1,this.handleClickCancelReminder=()=>{this.dispatchEvent(new Event(a.E,{bubbles:!0})),this.cancelReminder()},this.cancelReminder=async()=>{this.isReminderSet=!1;if(await this.updatePostReminderState(e.dU.NoReminder)){const t=e.c("faceplate-alert",{level:e.X.notice,message:"Reminder cancelled"});this.dispatchEvent(t),this.pubsub?.publish(e.T.AdReminderRsvpUnsubscribe,{postId:this.postId})}else{this.isReminderSet=!0;const e="Failed to cancel reminder";this.dispatchErrorAlert(e)}},this.handleClickSetReminder=async()=>{this.shouldFireEngagedClick&&this.dispatchEvent(e.c(e.dV)),this.isLoggedIn?(this.dispatchEvent(new Event(a.b,{bubbles:!0})),await this.setReminder()):this.dispatchEvent(e.c(e.dW.follow))},this.setReminder=async()=>{this.isReminderSet=!0;if(await this.updatePostReminderState(e.dU.Reminder)){const t=e.c("faceplate-alert",{level:e.X.success,message:"Reminder set"});this.dispatchEvent(t),this.pubsub?.publish(e.T.AdReminderRsvpSubscribe,{postId:this.postId})}else{this.isReminderSet=!1;const e="Failed to set reminder";this.dispatchErrorAlert(e)}},this.showUserActionTriggeredModal=()=>{this.userActionTriggeredModal?.showModal(),this.userActionTriggeredBottomSheet?.showModal(),this.userActionTriggeredModal?.addEventListener("rpl-dialog:hide",this.handleModalClose),this.userActionTriggeredBottomSheet?.addEventListener("rpl-bottom-sheet:hide",this.handleBottomSheetClose)},this.closeUserActionTriggeredModal=()=>{this.userActionTriggeredModal?.hide(),this.userActionTriggeredBottomSheet?.hide(),r.triggeredPostIds.delete(this.postId),this.userActionTriggeredModal?.removeEventListener("rpl-dialog:hide",this.handleModalClose),this.userActionTriggeredBottomSheet?.removeEventListener("rpl-bottom-sheet:hide",this.handleBottomSheetClose)},this.handleModalClose=()=>{r.triggeredPostIds.delete(this.postId),this.userActionTriggeredModal?.removeEventListener("rpl-dialog:hide",this.handleModalClose)},this.handleBottomSheetClose=()=>{r.triggeredPostIds.delete(this.postId),this.userActionTriggeredBottomSheet?.removeEventListener("rpl-bottom-sheet:hide",this.handleBottomSheetClose)},this.handleTriggerModal=e=>{e.postId!==this.postId||r.triggeredPostIds.has(this.postId)||this.isReminderSet||this.eventState!==n.Scheduled||(r.triggeredPostIds.add(this.postId),this.showUserActionTriggeredModal())},this.closeUserActionTriggeredModalAndGetNotifications=async()=>{this.closeUserActionTriggeredModal(),await this.handleClickSetReminder()},this.updatePostReminderState=async t=>{this.requestInProgress=!0;const i=await e.C({operation:e.H.UpdatePostReminderState,variables:{input:{postId:this.postId,reminderState:t}}});return this.requestInProgress=!1,!!i.data.updatePostReminderState?.ok}}connectedCallback(){super.connectedCallback(),this.pubsub=new e.m(this),this.pubsub.subscribe(e.T.AdReminderRsvpSubscribe,(e=>{e.postId===this.postId&&(this.isReminderSet=!0)})),this.pubsub.subscribe(e.T.AdReminderRsvpUnsubscribe,(e=>{e.postId===this.postId&&(this.isReminderSet=!1)})),this.enableUserActionTriggeredModal&&this.pubsub.subscribe(e.T.TriggerAdReminderModal,this.handleTriggerModal,!1)}disconnectedCallback(){super.disconnectedCallback(),this.pubsub=void 0}get shouldShowUserActionTriggeredModal(){const e=this.eventState===n.Live;return this.enableUserActionTriggeredModal&&this.isLoggedIn&&!e}dispatchErrorAlert(t){const i=e.c("faceplate-alert",{level:e.X.error,cause:"uncategorized",message:t});this.dispatchEvent(i)}getButtonAttributes(){const e=this.eventState===n.Live;return e&&this.isPdp?null:e&&!this.isPdp?{text:"Join Now",appearance:"primary",href:this.permalink,target:this.pdpTarget}:this.isReminderSet&&!e?{action:this.handleClickCancelReminder,text:"Reminder set",appearance:i.aq()?"secondary":"bordered"}:this.isReminderSet||e?null:{action:this.handleClickSetReminder,text:"Remind me",appearance:i.aq()?"bordered":"secondary"};}get userActionTriggerModalHeaderString(){return "Get reminded when this event starts?";}get userActionTriggerModalContentString(){return "Get notified before it starts so you don't miss out.";}renderUserActionTriggeredBottomSheet(){const i=t.x`
    ${this.userActionTriggerModalHeaderString}
    ${e.Z({appearance:"secondary",attributes:{onclick:this.closeUserActionTriggeredModal,"aria-label":"Close",className:"close-btn"},leadingIcon:t.c({size:t.I.Small}),size:e.ac.Small})}
    ${this.userActionTriggerModalContentString}
    ${e.Z({appearance:"secondary",size:e.ac.Small,children:"No thanks",attributes:{className:"w-100 mt-sm",onclick:this.closeUserActionTriggeredModal}})}
    ${e.Z({appearance:"primary",size:e.ac.Small,children:"Yes, remind me",attributes:{onclick:this.closeUserActionTriggeredModalAndGetNotifications,className:"w-100 my-sm"}})}
    `;return t.x``}renderUserActionTriggeredModal(){const i=t.x`
    ${this.userActionTriggerModalHeaderString}
    ${e.Z({appearance:"secondary",shape:"pill",leadingIcon:t.c({size:t.I.Small}),size:e.ac.Small,attributes:{"aria-label":"Close",onclick:this.closeUserActionTriggeredModal}})}
    ${this.userActionTriggerModalContentString}
    ${e.Z({appearance:"secondary",size:e.ac.Small,children:"No thanks",attributes:{className:"w-100 xs:w-auto",onclick:this.closeUserActionTriggeredModal}})}
    ${e.Z({appearance:"primary",size:e.ac.Small,children:"Yes, remind me",attributes:{onclick:this.closeUserActionTriggeredModalAndGetNotifications,className:"w-100 xs:w-auto"}})}
    `;return t.x``}render(){if(this.eventState===n.Ended)return t.x``;const i=this.getButtonAttributes();if(!i)return t.x``;const{appearance:a,action:r,text:s,href:o,target:l}=i,d=e.Z({appearance:a,attributes:{className:"relative",onclick:r,id:"",href:o,target:l,disabled:this.requestInProgress},size:e.ac.Small,children:s});return t.x`
    ${d} ${this.shouldShowUserActionTriggeredModal?this.isDesktopViewport?this.renderUserActionTriggeredModal():this.renderUserActionTriggeredBottomSheet():""}
    `}};s.styles=[e.t],s.triggeredPostIds=new Set,e._([e.n({type:Boolean,attribute:"is-reminder-set",reflect:!0})],s.prototype,"isReminderSet",void 0),e._([e.n({type:String,attribute:"event-state"})],s.prototype,"eventState",void 0),e._([e.n({type:String,attribute:"post-id"})],s.prototype,"postId",void 0),e._([e.n({type:String})],s.prototype,"permalink",void 0),e._([e.n({type:String,attribute:"pdp-target"})],s.prototype,"pdpTarget",void 0),e._([e.n({type:Boolean,attribute:"is-pdp"})],s.prototype,"isPdp",void 0),e._([e.n({type:Boolean,attribute:"is-logged-in"})],s.prototype,"isLoggedIn",void 0),e._([e.n({type:Boolean,attribute:"is-desktop-viewport"})],s.prototype,"isDesktopViewport",void 0),e._([e.n({type:Boolean,attribute:"should-fire-engaged-click"})],s.prototype,"shouldFireEngagedClick",void 0),e._([e.n({type:Boolean,attribute:"enable-user-action-triggered-modal"})],s.prototype,"enableUserActionTriggeredModal",void 0),e._([e.v()],s.prototype,"requestInProgress",void 0),e._([e.Q("rpl-dialog.triggered-modal")],s.prototype,"userActionTriggeredModal",void 0),e._([e.Q("rpl-bottom-sheet.triggered-modal")],s.prototype,"userActionTriggeredBottomSheet",void 0),s=r=e._([e.e("ad-reminder-button")],s);let o=class extends t.s{constructor(){super(...arguments),this.postId="",this.eventState=n.Scheduled,this.startsAt="",this.endsAt="",this.locale="en",this.isReminderSet=!1,this.isLoggedIn=!1,this.shouldFireEngagedClick=!1,this.requestInProgress=!1,this.handleClickCancelReminder=()=>{this.dispatchEvent(new Event(a.E,{bubbles:!0})),this.cancelReminder()},this.cancelReminder=async()=>{this.isReminderSet=!1;if(await this.updatePostReminderState(e.dU.NoReminder)){const t=e.c("faceplate-alert",{level:e.X.notice,message:"Reminder cancelled"});this.dispatchEvent(t),this.pubsub?.publish(e.T.AdReminderRsvpUnsubscribe,{postId:this.postId})}else{this.isReminderSet=!0;const e="Failed to cancel reminder";this.dispatchErrorAlert(e)}},this.handleClickSetReminder=async()=>{this.shouldFireEngagedClick&&this.dispatchEvent(e.c(e.dV)),this.isLoggedIn?(this.dispatchEvent(new Event(a.b,{bubbles:!0})),await this.setReminder()):this.dispatchEvent(e.c(e.dW.follow))},this.setReminder=async()=>{this.isReminderSet=!0;if(await this.updatePostReminderState(e.dU.Reminder)){const t=e.c("faceplate-alert",{level:e.X.success,message:"Reminder set"});this.dispatchEvent(t),this.pubsub?.publish(e.T.AdReminderRsvpSubscribe,{postId:this.postId})}else{this.isReminderSet=!1;const e="Failed to set reminder";this.dispatchErrorAlert(e)}},this.updatePostReminderState=async t=>{this.requestInProgress=!0;const i=await e.C({operation:e.H.UpdatePostReminderState,variables:{input:{postId:this.postId,reminderState:t}}});return this.requestInProgress=!1,!!i.data.updatePostReminderState?.ok},this.handleStatusClick=()=>{this.eventState===n.Ended||this.requestInProgress||(this.isReminderSet?this.handleClickCancelReminder():this.handleClickSetReminder())}}connectedCallback(){super.connectedCallback(),this.pubsub=new e.m(this),this.pubsub.subscribe(e.T.AdReminderRsvpSubscribe,(e=>{e.postId===this.postId&&(this.isReminderSet=!0)})),this.pubsub.subscribe(e.T.AdReminderRsvpUnsubscribe,(e=>{e.postId===this.postId&&(this.isReminderSet=!1)}))}getStatusMessage(){let e,t="text-neutral-content-weak";return this.eventState===n.Scheduled?e="Coming Up":this.eventState===n.Live?(t="text-global-orangered",e="Live"):e="Just Finished",{message:e,color:t};}getRelativeTime(){const e=new Date(this.startsAt),t=new Date(this.endsAt),i=new Date(Date.now()-6e4);return this.eventState===n.Scheduled?e:this.eventState===n.Live?e ${e} ยท ${a?t.x``:t.x``} `}};o.styles=[e.t],e._([e.n({type:String,attribute:"post-id"})],o.prototype,"postId",void 0),e._([e.n({type:String,attribute:"event-state"})],o.prototype,"eventState",void 0),e._([e.n({type:String,attribute:"starts-at"})],o.prototype,"startsAt",void 0),e._([e.n({type:String,attribute:"ends-at"})],o.prototype,"endsAt",void 0),e._([e.n({type:String})],o.prototype,"locale",void 0),e._([e.n({type:Boolean,attribute:"is-reminder-set",reflect:!0})],o.prototype,"isReminderSet",void 0),e._([e.n({type:Boolean,attribute:"is-logged-in"})],o.prototype,"isLoggedIn",void 0),e._([e.n({type:Boolean,attribute:"should-fire-engaged-click"})],o.prototype,"shouldFireEngagedClick",void 0),e._([e.v()],o.prototype,"requestInProgress",void 0),o=e._([e.e("ad-event-status")],o)})); SML.di("./C42E8rVVpA.js",import.meta.url,"C42E8rVVpA");SML.di("./CsxDAjmHZE.js",import.meta.url,"CsxDAjmHZE");SML.di("./BtqmVQuPYp.js",import.meta.url,"BtqmVQuPYp");SML.di("./DUzIBJc2in.js",import.meta.url,"DUzIBJc2in");SML.di("./B-LM1r1oJd.js",import.meta.url,"B-LM1r1oJd");SML.di("./DrM-WGXCsZ.js",import.meta.url,"DrM-WGXCsZ"); SML.dm("tmkhvHLxT3",["C42E8rVVpA","CsxDAjmHZE","BtqmVQuPYp","DUzIBJc2in","B-LM1r1oJd","DrM-WGXCsZ"],(async(t,i,e,s,n,a)=>{let o=class extends i.s{constructor(){super(...arguments),this.appearance=a.P.PLAIN,this.autoplay=0,this.pages=0,this.pageIndex=0,this.isAnimationFinished=!1,this._currentAnimation=null,this.handleAutoplayInterruption=async t=>{this.cancelAnimation(t)},this.cancelAnimation=async t=>{const i=await this._autoplayPillContainer;if(i){const{children:e}=i;if(e[t]?.firstElementChild){const i=e[t]?.firstElementChild?.getAnimations().map((t=>(t.cancel(),t.ready)));i&&await Promise.all(i)}}},this.resetAnimations=async()=>{const t=await this._autoplayPillContainer;if(t){const{children:i}=t;for(let t=0;t{this.isAnimationFinished=!1;try{await this.updateComplete,this._currentAnimation?.cancel();const t=[{backgroundColor:"var(--color-neutral-border-medium)",width:0,height:"var(--rem4)"},{backgroundColor:"var(--color-neutral-border-medium)",width:"100%",height:"var(--rem4)"}],i={duration:this.autoplay,fill:"forwards",iterations:1},{children:e}=await this._autoplayPillContainer,s=e?.[this.pageIndex]?.firstElementChild;this._currentAnimation=s?.animate(t,i),await(this._currentAnimation?.finished),this.isAnimationFinished=!0}catch(t){t instanceof DOMException&&"AbortError"===t.name||console.error(t)}},this.pauseAnimation=()=>{this._currentAnimation?.pause()},this.resumeAnimation=()=>{this._currentAnimation?.play()},this.render=()=>{if(0!==this.pages)return i.x`
    ${[...Array(this.pages).keys()].map(((e,s)=>i.x` `))}
    `}}static get styles(){return i.i`:host{display:block;box-sizing:border-box}.pagination-container{display:flex;justify-content:center}.track.in-view{height:var(--rem4,.25rem);border-radius:var(--rem2,.125rem)}.autoplayPill,.track{height:var(--rem2,.125rem);display:inline-block;border-radius:var(--rem2,.0625);width:100%}.autoplayPill{position:absolute}.track{background-color:var(--color-neutral-border);flex:1;margin:0 var(--rem2,.125rem);display:inline-block;position:relative}#autoplay-pill-container{display:flex;width:100%;align-items:center}.autoplayPill.viewed{background-color:var(--color-neutral-border-medium)}.pagination-controls.autoplay{width:90%}.pagination-controls.media.autoplay{position:absolute;bottom:var(--rem12,.75rem);z-index:2}.pagination-controls{display:flex;align-items:center;justify-content:center}.pagination-controls.plain .current-page-indicator{color:var(--color-media-onbackground)}.pagination-controls.media .current-page-indicator{color:var(--color-neutral-content)}`}updated(t){t.has("pageIndex")&&!this.isAnimationFinished&&this.handleAutoplayInterruption(t.get("pageIndex"))}};var r,l,h,d,c;t._([t.n({type:String,attribute:"appearance"})],o.prototype,"appearance",void 0),t._([t.n({type:Number})],o.prototype,"autoplay",void 0),t._([t.n({type:Number})],o.prototype,"pages",void 0),t._([t.n({type:Number,attribute:"page-index"})],o.prototype,"pageIndex",void 0),t._([t.v()],o.prototype,"isAnimationFinished",void 0),t._([t.dX("#autoplay-pill-container")],o.prototype,"_autoplayPillContainer",void 0),o=t._([t.e("faceplate-carousel-pagination")],o),function(t){t.OUTSIDE="outside",t.INSIDE="inside",t.OFF="off"}(r||(r={})),function(t){t.NEXT="next",t.BOTH="both",t.OFF="off"}(l||(l={})),function(t){t.INSIDE="inside",t.OUTSIDE="outside",t.OFF="off"}(h||(h={})),function(t){t.FORWARDS="forwards",t.BACKWARDS="backwards"}(d||(d={})),function(t){t.LEFT="left",t.CENTER="center",t.OFF="off"}(c||(c={}));let u=class extends i.s{constructor(){super(...arguments),this.navPlacement=h.OUTSIDE,this.paginationPlacement=r.OUTSIDE,this.autoplay="default",this.advanceAnimation=!1,this.numVisible=1,this.infinite=!1,this.inset=l.OFF,this.startIndex=0,this._pageIndex=0,this.pageCount=0,this.isCarouselInitialized=!1,this.hasBeenInteractedWith=!1,this._childCount=0,this._autoplayTimeoutId=null,this._isInsetBothAllowed=!1,this._lowerBoundOffset=0,this._upperBoundOffset=0,this._prevButtonHidden=!1,this._isNextButtonHidden=!1,this._gap=0,this._gapTotal=0,this._autoplayPaginationRef=t.U(),this._carouselListRef=t.U(),this._gesture=null,this.firstRender=!0,this.autoplayInProgress=!1,this.hidePrevButton=!1,this.hideNextButton=!1,this.emitter=s.l(this),this._animationStartTime=0,this._animationRemainingTime=0,this.generateAriaLiveMsg=({pageIndex:t,numVisible:i,pageCount:e})=>{const s=t*i+1;return i>1?`Items ${s} through ${s+i-1} of ${e}`:`Item ${s} of ${e}`},this.updated=async t=>{(t.has("numVisible")||t.has("infinite")||t.has("inset")||t.has("autoplay")||t.has("navPlacement")||t.has("paginationPlacement")||t.has("pageWidth"))&&((t.has("inset")||t.has("navPlacement"))&&(this.cachedDimensions=null),this.firstRender||this.resetAndInitialize()),(t.has("_pageIndex")||t.has("infinite"))&&this.toggleDisabledProgressButtons()},this.resetAndInitialize=()=>{this.resetCarousel(),this.initializeCarousel()},this.initializeResize=()=>{this.resizeObserver&&this.resizeObserver.disconnect(),this.resizeObserver=new ResizeObserver((async()=>{if(!this.firstRender){this.cachedDimensions=null,await new Promise((t=>requestAnimationFrame(t)));const t=this.getCarouselDimensions();t&&await this.showFirstChild(t.width)}})),this.resizeObserver.observe(this)},this.intersectionCallback=t=>{t.forEach((t=>{t.target.style.visibility=t.isIntersecting?"visible":"hidden"}));const i=new CustomEvent("__TEST-ONLY_carousel-intersection");this.dispatchEvent(i)},this.initializeIntersectionObserver=()=>{if(this._intersectionObserver=new IntersectionObserver(this.intersectionCallback,{root:this._carouselListRef?.value}),this.carouselSlot.children)for(const t of Array.from(this.carouselSlot.children))this._intersectionObserver.observe(t)},this.onPaginationClick=t=>{this.goToPage(t.detail.pageIndex,!0)},this.initializeCarousel=()=>{if(this.isCarouselInitialized)return;const{children:t}=this.carouselSlot;this.setChildAndPageCount(t),this.handleAutoPlay(),this._isInsetBothAllowed=this._childCount>=3&&(this.inset===l.BOTH||this.alignment===c.CENTER),this.infinite&&this.cloneBoundElements({children:t});if(this.navPlacement===h.INSIDE&&this.paginationPlacement===r.INSIDE||!this.firstRender){const t=this.getCarouselDimensions();t&&this.showFirstChild(t.width)}this.firstRender=!1,this.isCarouselInitialized=!0,this.initListMutationObserver(),this.initializeVisibility(),this.initializeIntersectionObserver(),this.toggleDisabledProgressButtons(),this._paginationCounter?.[0]&&(this._paginationCounter[0].style.visibility=this.pageCount<=5?"hidden":"visible");const i=new CustomEvent("__TEST-ONLY_carousel-initialized");this.dispatchEvent(i)},this.showFirstChild=async t=>{!this.hasBeenInteractedWith&&this.startIndex&&(this._pageIndex=this.startIndex),await this.setChildDimensions(t),this.goToPage(this.pageIndex,!1);const i=new CustomEvent("__TEST-ONLY_carousel-children-ready",{bubbles:!0});this.dispatchEvent(i)},this.handleAutoPlay=async()=>{"off"===this.autoplay||isNaN(this._autoplaySpeed)||(this.autoplayInProgress&&this.clearAnimationTimeout(),this.autoplayInProgress=!0,(this.infinite||this._pageIndex{await this.slideForwards(),this.handleAutoPlay()}),this._autoplaySpeed)))},this.cachedDimensions=null,this.getCarouselDimensions=()=>{if(this.cachedDimensions)return this.cachedDimensions;const t=this._carouselListRef.value?.getBoundingClientRect();if(t){const{width:i}=t;return this.cachedDimensions={width:i,height:t.height},this.cachedDimensions}},this.calcChildWidth=t=>{if(this.pageWidth)return"string"==typeof this.pageWidth&&this.pageWidth.endsWith("%")?t*(parseInt(this.pageWidth)/100):this.pageWidth;let i=0;this._gapTotal=this._gap*(this.numVisible-1)||0,this.inset!==l.OFF&&(i=48*(this.inset===l.NEXT?1:2),this._gapTotal=this._gap*(this.inset===l.NEXT?this.numVisible:this.numVisible+1));return(t-this._gapTotal-i)/this.numVisible},this.setChildDimensions=async t=>{this._gap=parseInt(getComputedStyle(this.carouselSlot).getPropertyValue("gap"))||0;for(const i of Array.from(this.carouselSlot.children)){const{width:e}=i.getBoundingClientRect(),s=i;if(s.style.boxSizing="border-box",t){const i=this.calcChildWidth(t);i!==e&&(s.style.width="number"==typeof i?`${i}px`:i)}"100%"!==s.style.height&&(s.style.height="100%"),"hidden"!==s.style.overflow&&(s.style.overflow="hidden")}},this.prepareNextSlideVisibility=t=>{const i=this.carouselSlot.children.length;for(let e=t;e{this.prepareNextSlideVisibility(i);let e="";const s=this.insetWidth(t);if(this._isInsetBothAllowed)switch(i){case 0:e="0px";break;case this.pageCount-1:e=this.isRTL?`calc(-1 * ${t.offsetLeft}px)`:`calc(-1 * (${t.offsetLeft}px - ${2*s}px - ${this._gap*this.numGaps}px))`;break;default:e=`calc(-1 * (${t.offsetLeft}px - ${s}px - ${this._gap}px))`}else{const i=getComputedStyle(this.carouselSlot),s=parseInt(i.paddingLeft||"0"),n=parseInt(i.paddingRight||"0"),a=this.carouselSlot.scrollWidth-(this.carouselSlot.clientWidth-n),o=t.offsetLeft===s?0:t.offsetLeft;e=-Math.min(o,a)+"px"}return this.carouselSlot.style.transform=`translateX(${e})`,await Promise.all(this.carouselSlot.getAnimations().map((t=>t.finished))).catch((t=>{t instanceof DOMException&&"AbortError"===t.name||console.error(t)}))},this.slideCarousel=async({isWithinBounds:t,direction:i,requestedIndex:e,allowAnimations:s,onSuccessfulSlide:n})=>{const{children:a}=this.carouselSlot,o=a.length,r=Math.max(1,Math.min(this.numVisible,o));let l=!1;if(this.firstRender||(this.carouselSlot.style.transitionDuration=`${s?this.animationDuration:0}ms`),t){let t=e*r+this._lowerBoundOffset;if(t+r>o){const i=e-1,s=t+r-o;t=Math.max(0,i*r+(r-s))}await this.handleTranslateXWithOffset({element:a[t],startIndex:t}),l=!0}else this.infinite&&(await this.handleInfiniteSlide({children:a,direction:i}),l=!0);l&&(this.hasBeenInteractedWith||(this.hasBeenInteractedWith=!0),n?.());const h=new CustomEvent("faceplate-carousel:slide",{detail:{prevPositionIndex:this._pageIndex,currPositionIndex:e,direction:i,num_items:this._childCount},bubbles:!0});this.dispatchEvent(h)},this.cloneBoundElements=({children:t})=>{let i=0;const e=this._childCount-1,s=this._isInsetBothAllowed?1:0;for(let i=0;i{this.carouselSlot.style.transitionDuration="0s";let e=this._isInsetBothAllowed?1:0;i===d.BACKWARDS&&(e=t.length-this._upperBoundOffset),await this.handleTranslateXWithOffset({element:t[e],startIndex:e}),this.carouselSlot.style.transitionDuration=`${this.animationDuration}ms`;const s=i===d.BACKWARDS?e-this.numVisible:e+this.numVisible;await this.handleTranslateXWithOffset({element:t[s],startIndex:s})},this.setNavButtonVisibility=({type:t,hidden:i})=>{this.navPlacement!==h.OFF&&("next"===t?(this.hideNextButton=i,this._isNextButtonHidden=i):(this.hidePrevButton=i,this._prevButtonHidden=i))},this.toggleDisabledProgressButtons=()=>{if(!this.infinite){const t=0===this.pageIndex,i=this.pageIndex===Math.ceil(this._childCount/this.numVisible)-1,e=0===this._childCount;this.setNavButtonVisibility({type:"previous",hidden:e||t}),this.setNavButtonVisibility({type:"next",hidden:e||i})}},this.resetCarousel=()=>{this.resetChildren(),this.cancelAutoPlay(),this.resetDisabledProgressButtons(),this._pageIndex=0,this.pageCount=0,this.isCarouselInitialized=!1,this._isInsetBothAllowed=!1,this._lowerBoundOffset=0,this._upperBoundOffset=0;const t=new CustomEvent("__TEST-ONLY_carousel-reset");this.dispatchEvent(t)},this.resetChildren=()=>{const{children:t}=this.carouselSlot;let i=0;const e=t.length;for(let s=0;s{"number"==typeof this._autoplayTimeoutId&&(window.clearTimeout(this._autoplayTimeoutId),this.autoplayInProgress=!1,t&&t())},this.cancelAutoPlay=()=>{this.clearAnimationTimeout(this._autoplayPaginationRef?.value?.resetAnimations)},this.onListItemKeydown=t=>{"ArrowLeft"===t.key?this.slideBackwards(t):"ArrowRight"===t.key&&this.slideForwards(t)},this.goToPage=(t,i)=>{if(t<0||t>=this.pageCount)return;let e=d.BACKWARDS;t>this._pageIndex&&(e=d.FORWARDS),this._pageIndex=t,this.slideCarousel({isWithinBounds:!0,direction:e,requestedIndex:t,allowAnimations:i})},this.swipeForwards=t=>{this.slideForwards(t),this.dispatchSwipeEvent(d.FORWARDS)},this.swipeBackwards=t=>{this.slideBackwards(t),this.dispatchSwipeEvent(d.BACKWARDS)},this.onInterruptedAutoplay=async t=>{await t(),this.handleAutoPlay()},this.slideHelper=async({navButtonDisabled:t,slide:i,e})=>{t||(this._autoplayTimeoutId&&e?this.onInterruptedAutoplay(i):await i())},this.slideForwards=async t=>{const i=this._pageIndex+1,e=i{this._pageIndex=e?i:0,this.slideCarousel({isWithinBounds:e,direction:d.FORWARDS,requestedIndex:i,allowAnimations:!0})},e:t})},this.onKeyDown=(t,i)=>{"Enter"!==t.key&&"Space"!==t.key||(t.preventDefault(),i(t))},this.slideBackwards=async t=>{const i=this._pageIndex-1,e=i>=0;await this.slideHelper({navButtonDisabled:this._prevButtonHidden,slide:async()=>{this._pageIndex=e?i:this.pageCount-1,this.slideCarousel({isWithinBounds:e,direction:d.BACKWARDS,requestedIndex:i,allowAnimations:!0})},e:t})},this.onListItemFocusIn=()=>{this.autoplay&&"off"!==this.autoplay&&(this._animationRemainingTime=this._autoplaySpeed-(Date.now()-this._animationStartTime),this.clearAnimationTimeout(),this.autoplayInProgress=!1,this._autoplayPaginationRef?.value?.pauseAnimation())},this.onListItemBlur=()=>{this.autoplay&&"off"!==this.autoplay&&(this._autoplayPaginationRef?.value?.resumeAnimation(),setTimeout((async()=>{await this.slideForwards(),this.handleAutoPlay()}),this._animationRemainingTime))}}static get styles(){return i.i`:host{display:flex;position:relative;width:inherit;isolation:isolate;--carousel-gap:var(--spacer-xs, 0.5rem);--carousel-padding:0;--carousel-margin:0}.carousel-container{display:flex;height:auto;align-items:center;position:relative;width:100%}::slotted(:not([slot])){height:100%;display:grid;grid-auto-flow:column;transition:transform;transition-timing-function:ease-out;margin:var(--carousel-margin)!important;padding:var(--carousel-padding)!important;list-style:none;position:relative;gap:var(--carousel-gap)}::slotted([slot=nextButton]),::slotted([slot=prevButton]){display:inline-block}.content-nav-buttons{display:inline-block;position:relative;z-index:2}.content-nav-buttons.hide{visibility:hidden}.content-nav-buttons.start{position:absolute;inset-inline-start:var(--spacer-sm,.75rem)}.content-nav-buttons.outside.end{padding:0 var(--spacer-sm,.75rem)}.content-nav-buttons.inside{position:absolute;top:50%;transform:translateY(-50%)}.content-nav-buttons.inside.start{inset-inline-start:var(--spacer-xs,.5rem)}.content-nav-buttons.inside.end{inset-inline-end:var(--spacer-xs,.5rem)}#carousel-window{position:relative;overflow:hidden;contain:content;display:flex;flex-direction:column;height:100%;flex:1}#carousel-list{height:100%;overflow:hidden;position:relative}:host([pagination-placement=outside]) #pagination-container{padding-top:var(--spacer-xs,.5rem)}:host(:not([nav-placement])) #carousel-window,:host([nav-placement=outside]) #carousel-window{margin-inline-start:var(--rem56,3.5rem)}:host([pagination-placement=inside]) #pagination-container{position:absolute;bottom:var(--rem16,1rem);inset-inline:0;margin:0 auto;width:fit-content}.carousel-actions{position:absolute;inset-inline-end:var(--rem12,.5rem);display:inline-flex;align-items:center;gap:var(--rem12,.75rem)}.carousel-actions.top{top:var(--rem12,.5rem)}.carousel-actions.bottom{bottom:var(--rem16,.1rem)}.hidden{visibility:hidden}.visible{visibility:visible;transition:visibility ease-in}`}get pageIndex(){return this._pageIndex}get isRTL(){try{return this.matches(":dir(rtl)")}catch{return"rtl"===getComputedStyle(this).direction}}get carouselSlot(){return this._children.reduce(((t,i)=>i.assignedSlot&&"UL"===i.nodeName?i:t),document.createElement("ul"))}connectedCallback(){if(super.connectedCallback(),this._gesture=new e.T(this,{mouseSupport:!1}),this._gesture.on("swipeleft",this.isRTL?this.swipeBackwards:this.swipeForwards),this._gesture.on("swiperight",this.isRTL?this.swipeForwards:this.swipeBackwards),this.initializeResize(),this.isCarouselInitialized){const t=this._pageIndex;this.resetAndInitialize(),this._pageIndex!==t&&this.goToPage(t,!1)}}disconnectedCallback(){super.disconnectedCallback(),this._gesture?.destroy(),this.resizeObserver?.disconnect(),this._listMutationObserver?.disconnect(),this._intersectionObserver?.disconnect()}firstUpdated(){this.initializeCarousel()}async handleChildRemoval(){const{children:t}=this.carouselSlot;this.setChildAndPageCount(t),this._firstViewableIndex>this._childCount-1&&this.slideBackwards(),this._childCount||this.toggleDisabledProgressButtons();const i=new CustomEvent("__TEST-ONLY_carousel-children-reset");this.dispatchEvent(i)}get _firstViewableIndex(){return this.infinite?this.pageIndex*this.numVisible+this._lowerBoundOffset:this.pageIndex*this.numVisible}initListMutationObserver(){this._listMutationObserver&&this._listMutationObserver.disconnect(),this._listMutationObserver=new MutationObserver((t=>{for(const i of t)"childList"===i.type&&this.isCarouselInitialized&&(i.removedNodes.length>0?this.handleChildRemoval():i.addedNodes.length>0&&this.handleChildrenAddition())})),this.carouselSlot&&this._listMutationObserver.observe(this.carouselSlot,{childList:!0})}setChildAndPageCount(t){this._childCount=t.length,this.pageCount=Math.ceil(this._childCount/this.numVisible)}async handleChildrenAddition(){const t=this._childCount,{children:i}=this.carouselSlot;this.setChildAndPageCount(i);const e=this.getCarouselDimensions();e&&await this.setChildDimensions(e.width),this._childCount>t&&this.toggleDisabledProgressButtons()}get _autoplaySpeed(){switch(this.autoplay){case"off":return 0;case"default":return 5e3;default:return parseInt(this.autoplay)}}get animationDuration(){return this.advanceAnimation&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches?250:0}get numInsets(){return this.inset===l.BOTH||this.alignment===c.CENTER?2:this.inset===l.NEXT||this.alignment===c.LEFT?1:0}get numGaps(){return this.numVisible+this.numInsets-1}insetWidth(t){const i=this.getCarouselDimensions();if(i){return(i.width-t.getBoundingClientRect().width*this.numVisible-this._gap*this.numGaps)/this.numInsets}return 0}resetDisabledProgressButtons(){this.setNavButtonVisibility({type:"next",hidden:!1}),this.setNavButtonVisibility({type:"previous",hidden:!1})}initializeVisibility(){for(const t of Array.from(this.carouselSlot.children))t.dataset.fpUiCarouselMarker||(t.style.visibility="hidden")}dispatchSwipeEvent(t){const i=new CustomEvent("faceplate-carousel:swipe",{detail:{currPositionIndex:this._pageIndex,direction:t},bubbles:!0});this.dispatchEvent(i)}render(){return i.x` ${this.currentAriaLiveMsg??this.generateAriaLiveMsg({pageIndex:this.pageIndex,pageCount:this.pageCount,numVisible:this.numVisible})} `}};return u.navButton=({placement:e,progress:s,ariaLabel:n})=>{const a=s===d.FORWARDS?"Next Page":"Previous Page";return t.Z({appearance:e===h.INSIDE?"media":"secondary",size:t.ac.Small,leadingIcon:s===d.FORWARDS?i.aa({size:i.h.Small}):i.ab({size:i.h.Small}),attributes:{"aria-label":n??a}})},u.closeButton=({attributes:e})=>t.Z({appearance:"media",size:t.ac.Small,leadingIcon:i.ac({size:i.h.Small}),attributes:e}),u.addButton=({children:e,attributes:s})=>t.Z({appearance:"media",size:t.ac.Small,leadingIcon:i.ad({size:i.h.Small}),attributes:s,children:e}),u.paginationCounter=({attributes:t,pageIndex:i,pageCount:e})=>n.b({appearance:n.B.MEDIA,content:`${i+1} / ${e}`,attributes:t}),t._([t.n({type:String,attribute:"nav-placement",reflect:!0})],u.prototype,"navPlacement",void 0),t._([t.n({type:String,attribute:"pagination-placement",reflect:!0})],u.prototype,"paginationPlacement",void 0),t._([t.n({type:String})],u.prototype,"autoplay",void 0),t._([t.n({type:Boolean,attribute:"advance-animation"})],u.prototype,"advanceAnimation",void 0),t._([t.n({type:Number,attribute:"num-visible"})],u.prototype,"numVisible",void 0),t._([t.n({type:Boolean})],u.prototype,"infinite",void 0),t._([t.n({type:String})],u.prototype,"inset",void 0),t._([t.n({type:String,attribute:"pagination-counter-label"})],u.prototype,"paginationCounterLabel",void 0),t._([t.n({type:Number,attribute:"start-index"})],u.prototype,"startIndex",void 0),t._([t.n()],u.prototype,"getPageLabels",void 0),t._([t.n({type:String,attribute:"current-page-label"})],u.prototype,"currentPageLabel",void 0),t._([t.n({type:String,attribute:"current-aria-live-msg"})],u.prototype,"currentAriaLiveMsg",void 0),t._([t.n({type:String,attribute:"pagination-container-label"})],u.prototype,"paginationContainerLabel",void 0),t._([t.n({type:String,attribute:"page-width"})],u.prototype,"pageWidth",void 0),t._([t.n({type:String})],u.prototype,"alignment",void 0),t._([t.v()],u.prototype,"_pageIndex",void 0),t._([t.v()],u.prototype,"pageCount",void 0),t._([t.v()],u.prototype,"isCarouselInitialized",void 0),t._([t.v()],u.prototype,"hasBeenInteractedWith",void 0),t._([t.av({flatten:!0})],u.prototype,"_children",void 0),t._([t.av({slot:"paginationCounter",flatten:!0})],u.prototype,"_paginationCounter",void 0),t._([t.v()],u.prototype,"firstRender",void 0),t._([t.v()],u.prototype,"autoplayInProgress",void 0),t._([t.v()],u.prototype,"hidePrevButton",void 0),t._([t.v()],u.prototype,"hideNextButton",void 0),u=t._([t.e("faceplate-carousel")],u),{get C(){return d},get F(){return u},get I(){return l},get N(){return h},get P(){return r}}})); SML.dm("uOlAvv4IVq",[],(async()=>{var e;return function(e){e.Feed="FEED",e.Pdp="PDP"}(e||(e={})),{get T(){return e}}}));