Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.
// ==UserScript==
// @name StreamGrabber
// @namespace https://github.com/streamgrabber-lite
// @version 2.0.0
// @author StreamGrabber
// @description Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.
// @license MIT
// @match *://*/*
// @exclude *://*.youtube.com/*
// @exclude *://*.youtu.be/*
// @exclude *://*.x.com/*
// @exclude *://*.twitch.tv/*
// @exclude *://*.reddit.com/*
// @exclude *://*.redd.it/*
// @exclude *://*.facebook.com/*
// @exclude *://*.instagram.com/*
// @exclude *://*.tiktok.com/*
// @exclude *://*.netflix.com/*
// @exclude *://*.hulu.com/*
// @exclude *://*.disneyplus.com/*
// @exclude *://*.primevideo.com/*
// @exclude *://*.spotify.com/*
// @exclude *://music.youtube.com/*
// @exclude *://*.soundcloud.com/*
// @exclude *://*.deezer.com/*
// @exclude *://*.lastpass.com/*
// @exclude *://*.1password.com/*
// @exclude *://*.bitwarden.com/*
// @exclude *://*.dashlane.com/*
// @exclude *://*.irctc.co.in/*
// @connect *
// @grant GM_addStyle
// @grant GM_download
// @grant GM_getValue
// @grant GM_notification
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
const tt={RETRIES:3,CONCURRENCY:6,REQUEST_TIMEOUT:6e4,MANIFEST_TIMEOUT:3e4,SMALL_BYTES:1048576,UI_IDLE_MS:5e3,ENRICH_DELAY:150,DETECT_DEBOUNCE:50,ENRICH_TIMEOUT:1e4,IS_TOP:window.self===window.top},re={TEXT_MAX:256,DB_MAX:120,CLEAR_MS:12e4},Pe={EXCLUDE_SMALL:"sg_exclude_small"},St={http:/^https?:/i,blob:/^blob:/i,m3u8:/\.m3u8(\b|[?#]|$)/i,video:/\.(mp4|mkv|webm|avi|mov|m4v|flv|ogv|ogg)([?#]|$)/i,segment:/\.(m4s|init|seg|fmp4|ts|m2ts)([?#]|$)/i,m3u8Type:/mpegurl|vnd\.apple\.mpegurl|application\/x-mpegurl/i,videoType:/^video\//i,videoTypeAlt:/(matroska|mp4|webm|quicktime)/i,resolutionCombined:/(?:^|[_\-\/])(\d{3,4})([px])(\d{3,4})?(?:[_\-\/\.]|$)|resolution[=_]?(\d{3,4})|quality[=_]?(\d{3,4})|[_\-]hd(\d{3,4})|(\d{3,4})\.m3u8/i},In=t=>typeof t=="string"&&St.http.test(t),Ft=t=>typeof t=="string"&&St.blob.test(t),Sn=t=>St.m3u8.test(t||""),An=t=>St.video.test(t||""),wn=t=>St.segment.test(t||""),Nn=t=>St.m3u8Type.test(t||""),Rn=t=>St.videoType.test(t||"")||St.videoTypeAlt.test(t||"");function Wt(t,e){try{return new URL(t,e).href}catch{return t}}function ze(t){if(!t)return null;const e=St.resolutionCombined.exec(t);if(e){if(e[1]){const u=parseInt(e[1],10),g=e[2],b=e[3];if(g==="x"&&b)return `${u}x${b}`;if(u>=144&&u<=4320)return `${u}p`}const i=e[4]||e[5]||e[6]||e[7];if(i){const u=parseInt(i,10);if(u>=144&&u<=4320)return `${u}p`}}return null}const Xe=["B","KB","MB","GB","TB"];function jt(t){if(t==null)return "";let e=0,i=t;for(;i>=1024&&e<Xe.length-1;)i/=1024,e++;const u=i<10&&e>0?1:0;return `${i.toFixed(u)} ${Xe[e]}`}function On(t){if(!t||t<=0)return null;const e=Math.floor(t/3600),i=Math.floor(t%3600/60),u=Math.floor(t%60),g=b=>String(b).padStart(2,"0");return e>0?`${e}:${g(i)}:${g(u)}`:`${i}:${g(u)}`}function Ke(t){return (t||"video").replace(/[\\/:*?"<>|]/g,"_").slice(0,120).trim()||"video"}const Ln={webm:"webm",matroska:"mkv",mkv:"mkv",quicktime:"mov",mov:"mov",mp2t:"ts",mpegts:"ts",ogg:"ogg",mp4:"mp4"};function Pn(t){const e=t.toLowerCase();for(const[i,u]of Object.entries(Ln))if(e.includes(i))return u;return "mp4"}function qe(t,e){const i=/(?:\.([a-z0-9]+))([?#]|$)/i.exec(t||"");return i?i[1].toLowerCase():e?Pn(e):"mp4"}function pe(t){if(!t)return null;const e=/bytes=(\d+)-(\d+)?/i.exec(t);return e?{start:+e[1],end:e[2]!=null?+e[2]:null}:null}function Xn(t,e){if(!t.has(e))return;const i=t.get(e);return t.delete(e),t.set(e,i),i}function Dn(t,e,i,u){if(t.has(e)&&t.delete(e),t.set(e,i),typeof u=="number"&&isFinite(u))for(;t.size>u;){const g=t.keys().next().value;g!==void 0&&t.delete(g);}}function fe(t,e,i,u,g){const b=Xn(t,i);if(b!==void 0)return Promise.resolve(b);if(e.has(i))return e.get(i);const p=(async()=>{try{const T=await u();return Dn(t,i,T,g),T}finally{e.delete(i);}})();return e.set(i,p),p}document.createElement("div");function $e(t){return [...t].sort((e,i)=>(i.h||0)-(e.h||0)||(i.avg||i.peak||0)-(e.avg||e.peak||0))}function We(t){const e=[];if(t.resolution&&e.push(t.resolution),t.bitrate&&e.push(`${Math.round(t.bitrate/1e3)}k`),t.duration&&t.duration>0){const i=On(t.duration);i&&e.push(i);}return t.size!=null&&e.push(`~${jt(t.size)}`),t.extra&&e.push(...t.extra),e.length>0?e.join(" • "):"Video Stream"}function Cn(t,e){return `${t} segments • ${e?"fMP4":"TS"}`}function xn(t,e={}){GM_notification({text:t,title:e.title??"StreamGrabber",timeout:e.timeout??3e3,onclick:e.onclick});}function be(t){xn(`Download complete: ${t}`);}function Mn(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t)}function Qe(t,e){const i=Mn(t);alert(i);}function me(){return Math.random().toString(36).slice(2)}const Un=["url","kind","label","sublabel","size","type","origin","enriched","enriching","hlsType","isLive","encrypted","duration","segCount","resolution","isVod","isFmp4","variantCount","variants","bestVariant","variant"];function kn(t){const e={};for(const i of Un)t[i]!==void 0&&(e[i]=t[i]);return e}function Ze(t,e){if(!Ft(t))return null;const i=e.get(t);return i?(i.ts=Date.now(),i):null}function _n(t,e){if(!e)return t;const i=pe(e);return i?t.slice(i.start,i.end==null?t.size:i.end+1):t}const Yn=new Map,Vn=new Map,ct=new Map;function Je(t){let e=null;const i=new Promise((u,g)=>{e=GM_xmlhttpRequest({method:"GET",url:t.url,responseType:t.responseType,headers:t.headers||{},timeout:t.timeout??tt.REQUEST_TIMEOUT,onprogress:b=>t.onprogress?.({loaded:b.loaded,total:b.total}),onload:b=>{b.status>=200&&b.status<300?u(b.response):g(new Error(`HTTP ${b.status}`));},onerror:()=>g(new Error("Network error")),ontimeout:()=>g(new Error("Timeout"))});});return i.abort=()=>{try{e?.abort();}catch{}},i}async function Gn(t){const e=Ze(t,ct);if(e){if(!e.blob)throw new Error("Blob not found");return e.blob.text()}return Je({url:t,responseType:"text",timeout:tt.MANIFEST_TIMEOUT})}function Qt(t){return fe(Yn,Vn,t,()=>Gn(t),re.TEXT_MAX)}function oe(t,e={},i=tt.REQUEST_TIMEOUT,u){const g=Ze(t,ct);if(g){if(!g.blob){const A=Promise.reject(new Error("Blob not found"));return A.abort=()=>{},A}const b=_n(g.blob,e.Range);u&&setTimeout(()=>u({loaded:b.size,total:b.size}),0);let p=false;const T=b.arrayBuffer().then(A=>{if(p)throw new Error("Aborted");return A});return T.abort=()=>{p=true;},T}return Je({url:t,responseType:"arraybuffer",headers:e,timeout:i,onprogress:u})}function De(t){const e=[];for(const[i,u]of ct)t(i,u)&&(ct.delete(i),e.push(i));return e}class Ce{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}dispatch(e){for(const i of this.listeners)try{i(e);}catch(u){console.error("[SG] Event dispatch error:",u);}}}class Bn{items=new Map;m3u8Urls=new Set;videoUrls=new Set;watchedVideos=new WeakSet;excludeSmall;_validCount=0;_validCountDirty=true;events={itemAdded:new Ce,updated:new Ce};constructor(){this.excludeSmall=GM_getValue(Pe.EXCLUDE_SMALL,true);}hasItem(e){return this.items.has(e)}getItem(e){return this.items.get(e)}addItem(e){return this.items.has(e.url)?false:(this.items.set(e.url,e),e.kind==="hls"?this.m3u8Urls.add(e.url):this.videoUrls.add(e.url),this.invalidateCount(),this.enforceLimit(),this.events.itemAdded.dispatch(e),this.events.updated.dispatch(),true)}enforceLimit(){for(;this.items.size>re.DB_MAX;){const e=this.items.keys().next().value;if(e===void 0)break;const i=this.items.get(e);this.items.delete(e),i&&(this.m3u8Urls.delete(i.url),this.videoUrls.delete(i.url));}this.invalidateCount();}get validCount(){if(this._validCountDirty){let e=0;for(const i of this.items.values())i.hlsType!=="invalid"&&i.hlsType!=="error"&&e++;this._validCount=e,this._validCountDirty=false;}return this._validCount}invalidateCount(){this._validCountDirty=true;}getAllItems(){return Array.from(this.items.values()).reverse()}getFilteredItems(){const e=this.getAllItems();return this.excludeSmall?e.filter(i=>i.size==null||i.size>=tt.SMALL_BYTES):e}setExcludeSmall(e){this.excludeSmall=e,GM_setValue(Pe.EXCLUDE_SMALL,e);}clear(){this.items.clear(),this.m3u8Urls.clear(),this.videoUrls.clear(),De(()=>true),this.invalidateCount();}trim(){this.enforceLimit();const e=Date.now(),i=De((u,g)=>{const b=e-(g.ts||0);return !!(g.revoked&&b>re.CLEAR_MS)});for(const u of i)this.items.has(u)&&(this.items.delete(u),this.m3u8Urls.delete(u),this.videoUrls.delete(u),this.invalidateCount());}}const it=new Bn;tt.IS_TOP&&(setInterval(()=>it.trim(),re.CLEAR_MS),window.addEventListener("pagehide",()=>it.trim()),window.addEventListener("beforeunload",()=>it.trim()));let he=null;const Zt=[];function Fn(t){if(he=t,Zt.length>0){const e=[...Zt];Zt.length=0,e.forEach(({url:i,metadata:u})=>t(i,u));}}function Yt(t,e){he?he(t,e):Zt.push({url:t,metadata:e});}function jn(){const t=URL.createObjectURL;URL.createObjectURL=function(e){const i=t.call(this,e);try{const u=Date.now();if(e instanceof Blob){const g=e.type||"",b={blob:e,type:g,size:e.size,kind:"other",ts:u};Nn(g)?(b.kind="m3u8",ct.set(i,b),Yt(i)):Rn(g)?(b.kind="video",ct.set(i,b),Yt(i)):/octet-stream|text\/plain|^$/.test(g)&&e.size>0?e.slice(0,Math.min(2048,e.size)).text().then(T=>{/^#EXTM3U/i.test(T)&&(b.kind="m3u8"),ct.set(i,b),b.kind==="m3u8"&&Yt(i);}).catch(()=>{ct.set(i,b);}):ct.set(i,b);}else ct.set(i,{blob:null,type:"mediasource",size:0,kind:"other",ts:u});}catch(u){console.error("[SG] createObjectURL hook error:",u);}return i};}function Hn(){const t=URL.revokeObjectURL;URL.revokeObjectURL=function(e){try{const i=ct.get(e);i&&(i.revoked=!0,i.ts=Date.now());}catch{}return t.call(this,e)};}function zn(){const t=window.fetch;typeof t=="function"&&(window.fetch=function(...e){try{const i=e[0],u=typeof i=="string"?i:i instanceof Request?i.url:i.href;u&&Yt(u);}catch{}return t.apply(this,e)});}function Kn(){const t=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(e,i,...u){try{const g=typeof i=="string"?i:i?.href;g&&Yt(g);}catch{}return t.call(this,e,i,...u)};}function qn(){try{new PerformanceObserver(e=>{for(const i of e.getEntries())"name"in i&&typeof i.name=="string"&&Yt(i.name);}).observe({entryTypes:["resource"]});}catch{}}let xe=false;function $n(){xe||(xe=true,jn(),Hn(),zn(),Kn(),qn());}let tn=()=>{};function Wn(t){tn=t;}function ge(t){if(it.watchedVideos.has(t))return;it.watchedVideos.add(t);const e=()=>{[t.currentSrc||t.src,...Array.from(t.querySelectorAll("source")).map(g=>g.src)].filter(Boolean).forEach(tn);};["loadstart","loadedmetadata","canplay"].forEach(u=>t.addEventListener(u,e)),e();}function Me(){document.querySelectorAll("video").forEach(t=>ge(t));}let se=null;function Ue(){se||(se=new MutationObserver(t=>{for(const e of t)for(const i of e.addedNodes)i instanceof Element&&(i.tagName==="VIDEO"?ge(i):i.querySelectorAll?.("video")?.forEach(u=>{ge(u);}));}),se.observe(document.documentElement,{childList:true,subtree:true}));}const le=new Set;function ke(t,e){le.has(t)||(le.add(t),setTimeout(()=>{le.delete(t),e(t);},tt.DETECT_DEBOUNCE));}function Qn(t,e,i={}){const{size:u=null,type:g=null}=i;let b;if(e==="hls"){const p=ze(t);b=p?`${p} • Analyzing...`:"Analyzing...";}else b=qe(t,g).toUpperCase();return {url:t,kind:e,label:b,sublabel:null,size:u,type:g,origin:document.location.origin,enriched:false,enriching:false,hlsType:null,isLive:false,encrypted:false,_enrichPromise:null}}let en=()=>{};function Zn(t){en=t;}function _e(t){try{if(!t||!In(t)&&!Ft(t)||wn(t))return;const e=t.toLowerCase();if(e.includes("ping.gif")||e.includes("jwpltx.com")||e.includes("doubleclick")||e.includes("analytics")||e.includes("/stats/")||it.hasItem(t))return;let i=null,u=null;if(Ft(t)){const A=ct.get(t);if(A&&(i=A.size,u=A.type),i!=null&&i<512*1024&&A?.kind!=="m3u8")return}const g=Sn(t)||Ft(t)&&ct.get(t)?.kind==="m3u8",b=An(t)||Ft(t)&&ct.get(t)?.kind==="video",p=g?"hls":b?"video":null;if(!p)return;const T=Qn(t,p,{size:i,type:u});it.addItem(T)&&en(T);}catch(e){console.error("[SG] processUrl error:",e);}}let Ye=false;function Jn(){Ye||(Ye=true,Fn(t=>ke(t,_e)),Wn(t=>ke(t,_e)),$n(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Me(),Ue();}):(Me(),Ue()));}var ce={exports:{}};var Ve;function tr(){return Ve||(Ve=1,(function(t,e){(function(i,u){t.exports=u();})(self,(()=>(()=>{var i={31:function(b,p,T){function A(l){return A=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},A(l)}function x(l,n){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(l);n&&(r=r.filter((function(f){return Object.getOwnPropertyDescriptor(l,f).enumerable}))),o.push.apply(o,r);}return o}function Y(l){for(var n=1;n<arguments.length;n++){var o=arguments[n]!=null?arguments[n]:{};n%2?x(Object(o),true).forEach((function(r){d(l,r,o[r]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(o)):x(Object(o)).forEach((function(r){Object.defineProperty(l,r,Object.getOwnPropertyDescriptor(o,r));}));}return l}function G(l,n,o){return n=v(n),(function(r,f){if(f&&(A(f)=="object"||typeof f=="function"))return f;if(f!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return (function(h){if(h===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return h})(r)})(l,B()?Reflect.construct(n,o||[],v(l).constructor):n.apply(l,o))}function B(){try{var l=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (B=function(){return !!l})()}function v(l){return v=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},v(l)}function N(l,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");l.prototype=Object.create(n&&n.prototype,{constructor:{value:l,writable:true,configurable:true}}),Object.defineProperty(l,"prototype",{writable:false}),n&&w(l,n);}function w(l,n){return w=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o,r){return o.__proto__=r,o},w(l,n)}function m(l,n,o){return Object.defineProperty(l,"prototype",{writable:false}),l}function y(l,n){if(!(l instanceof n))throw new TypeError("Cannot call a class as a function")}function d(l,n,o){return (n=C(n))in l?Object.defineProperty(l,n,{value:o,enumerable:true,configurable:true,writable:true}):l[n]=o,l}function C(l){var n=(function(o,r){if(A(o)!="object"||!o)return o;var f=o[Symbol.toPrimitive];if(f!==void 0){var h=f.call(o,r);if(A(h)!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return (r==="string"?String:Number)(o)})(l,"string");return A(n)=="symbol"?n:n+""}var _,j=this&&this.__createBinding||(Object.create?function(l,n,o,r){r===void 0&&(r=o);var f=Object.getOwnPropertyDescriptor(n,o);f&&!("get"in f?!n.__esModule:f.writable||f.configurable)||(f={enumerable:true,get:function(){return n[o]}}),Object.defineProperty(l,r,f);}:function(l,n,o,r){r===void 0&&(r=o),l[r]=n[o];}),rt=this&&this.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:true,value:n});}:function(l,n){l.default=n;}),at=this&&this.__importStar||(_=function(l){return _=Object.getOwnPropertyNames||function(n){var o=[];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(o[o.length]=r);return o},_(l)},function(l){if(l&&l.__esModule)return l;var n={};if(l!=null)for(var o=_(l),r=0;r<o.length;r++)o[r]!=="default"&&j(n,l,o[r]);return rt(n,l),n});Object.defineProperty(p,"__esModule",{value:true}),p.ContentSteering=p.RenditionReport=p.PrefetchSegment=p.PartialSegment=p.Segment=p.MediaPlaylist=p.MasterPlaylist=p.Playlist=p.SpliceInfo=p.DateRange=p.MediaInitializationSection=p.Key=p.SessionData=p.Variant=p.Rendition=void 0;var F=at(T(203)),pt=m((function l(n){var o=n.type,r=n.uri,f=n.groupId,h=n.language,O=n.assocLanguage,R=n.name,D=n.isDefault,S=n.autoselect,X=n.forced,M=n.instreamId,U=n.characteristics,V=n.channels,L=n.pathwayId;y(this,l),d(this,"type",void 0),d(this,"uri",void 0),d(this,"groupId",void 0),d(this,"language",void 0),d(this,"assocLanguage",void 0),d(this,"name",void 0),d(this,"isDefault",void 0),d(this,"autoselect",void 0),d(this,"forced",void 0),d(this,"instreamId",void 0),d(this,"characteristics",void 0),d(this,"channels",void 0),d(this,"pathwayId",void 0),F.PARAMCHECK(o,f,R),F.CONDITIONALASSERT([o==="SUBTITLES",r],[o==="CLOSED-CAPTIONS",M],[o==="CLOSED-CAPTIONS",!r],[X,o==="SUBTITLES"]),this.type=o,this.uri=r,this.groupId=f,this.language=h,this.assocLanguage=O,this.name=R,this.isDefault=D,this.autoselect=S,this.forced=X,this.instreamId=M,this.characteristics=U,this.channels=V,this.pathwayId=L;}));p.Rendition=pt;var ot=m((function l(n){var o=n.uri,r=n.isIFrameOnly,f=r!==void 0&&r,h=n.bandwidth,O=n.averageBandwidth,R=n.score,D=n.codecs,S=n.resolution,X=n.frameRate,M=n.hdcpLevel,U=n.allowedCpc,V=n.videoRange,L=n.stableVariantId,k=n.pathwayId,z=n.programId,Q=n.audio,et=Q===void 0?[]:Q,K=n.video,Z=K===void 0?[]:K,$=n.subtitles,nt=$===void 0?[]:$,J=n.closedCaptions,st=J===void 0?[]:J,dt=n.currentRenditions,ft=dt===void 0?{audio:0,video:0,subtitles:0,closedCaptions:0}:dt;y(this,l),d(this,"uri",void 0),d(this,"isIFrameOnly",void 0),d(this,"bandwidth",void 0),d(this,"averageBandwidth",void 0),d(this,"score",void 0),d(this,"codecs",void 0),d(this,"resolution",void 0),d(this,"frameRate",void 0),d(this,"hdcpLevel",void 0),d(this,"allowedCpc",void 0),d(this,"videoRange",void 0),d(this,"stableVariantId",void 0),d(this,"pathwayId",void 0),d(this,"programId",void 0),d(this,"audio",void 0),d(this,"video",void 0),d(this,"subtitles",void 0),d(this,"closedCaptions",void 0),d(this,"currentRenditions",void 0),F.PARAMCHECK(o,h),this.uri=o,this.isIFrameOnly=f,this.bandwidth=h,this.averageBandwidth=O,this.score=R,this.codecs=D,this.resolution=S,this.frameRate=X,this.hdcpLevel=M,this.allowedCpc=U,this.videoRange=V,this.stableVariantId=L,this.pathwayId=k,this.programId=z,this.audio=et,this.video=Z,this.subtitles=nt,this.closedCaptions=st,this.currentRenditions=ft;}));p.Variant=ot;var Xt=m((function l(n){var o=n.id,r=n.value,f=n.uri,h=n.language;y(this,l),d(this,"id",void 0),d(this,"value",void 0),d(this,"uri",void 0),d(this,"language",void 0),F.PARAMCHECK(o,r||f),F.ASSERT("SessionData cannot have both value and uri, shoud be either.",!(r&&f)),this.id=o,this.value=r,this.uri=f,this.language=h;}));p.SessionData=Xt;var At=m((function l(n){var o=n.method,r=n.uri,f=n.iv,h=n.format,O=n.formatVersion;y(this,l),d(this,"method",void 0),d(this,"uri",void 0),d(this,"iv",void 0),d(this,"format",void 0),d(this,"formatVersion",void 0),F.PARAMCHECK(o),F.CONDITIONALPARAMCHECK([o!=="NONE",r]),F.CONDITIONALASSERT([o==="NONE",!(r||f||h||O)]),this.method=o,this.uri=r,this.iv=f,this.format=h,this.formatVersion=O;}));p.Key=At;var Et=m((function l(n){var o=n.serverUri,r=n.pathwayId;y(this,l),d(this,"serverUri",void 0),d(this,"pathwayId",void 0),this.serverUri=o,this.pathwayId=r;}));p.ContentSteering=Et;var yt=m((function l(n){var o=n.hint,r=o!==void 0&&o,f=n.uri,h=n.mimeType,O=n.byterange;y(this,l),d(this,"hint",void 0),d(this,"uri",void 0),d(this,"mimeType",void 0),d(this,"byterange",void 0),F.PARAMCHECK(f),this.hint=r,this.uri=f,this.mimeType=h,this.byterange=O;}));p.MediaInitializationSection=yt;var bt=m((function l(n){var o=n.id,r=n.classId,f=n.start,h=n.cue,O=n.end,R=n.duration,D=n.plannedDuration,S=n.endOnNext,X=n.attributes,M=X===void 0?{}:X;y(this,l),d(this,"id",void 0),d(this,"classId",void 0),d(this,"start",void 0),d(this,"cue",void 0),d(this,"end",void 0),d(this,"duration",void 0),d(this,"plannedDuration",void 0),d(this,"endOnNext",void 0),d(this,"attributes",void 0),F.PARAMCHECK(o),F.CONDITIONALPARAMCHECK([S===true,r]),F.CONDITIONALASSERT([O,f],[O,f<=O],[R,R>=0],[D,D>=0]),this.id=o,this.classId=r,this.start=f,this.cue=h,this.end=O,this.duration=R,this.plannedDuration=D,this.endOnNext=S,this.attributes=M;}));p.DateRange=bt;var vt=m((function l(n){var o=n.type,r=n.duration,f=n.tagName,h=n.value;y(this,l),d(this,"type",void 0),d(this,"duration",void 0),d(this,"tagName",void 0),d(this,"value",void 0),F.PARAMCHECK(o),F.CONDITIONALPARAMCHECK([o==="OUT",r]),F.CONDITIONALPARAMCHECK([o==="RAW",f]),this.type=o,this.duration=r,this.tagName=f,this.value=h;}));p.SpliceInfo=vt;var ut=m((function l(n){y(this,l),d(this,"type",void 0),F.PARAMCHECK(n),this.type=n;})),P=(function(l){function n(o){var r,f=o.isMasterPlaylist,h=o.uri,O=o.version,R=o.independentSegments,D=R!==void 0&&R,S=o.start,X=o.source,M=o.defines;return y(this,n),d(r=G(this,n,["playlist"]),"isMasterPlaylist",void 0),d(r,"uri",void 0),d(r,"version",void 0),d(r,"independentSegments",void 0),d(r,"start",void 0),d(r,"source",void 0),d(r,"defines",void 0),F.PARAMCHECK(f),r.isMasterPlaylist=f,r.uri=h,r.version=O,r.independentSegments=D,r.start=S,r.source=X,r.defines=M,r}return N(n,l),m(n)})(ut);p.Playlist=P;var q=(function(l){function n(){var o,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};y(this,n),d(o=G(this,n,[Y(Y({},r),{},{isMasterPlaylist:true})]),"variants",void 0),d(o,"currentVariant",void 0),d(o,"sessionDataList",void 0),d(o,"sessionKeyList",void 0),d(o,"contentSteering",void 0);var f=r.variants,h=f===void 0?[]:f,O=r.currentVariant,R=r.sessionDataList,D=R===void 0?[]:R,S=r.sessionKeyList,X=S===void 0?[]:S,M=r.contentSteering,U=M===void 0?void 0:M;return o.variants=h,o.currentVariant=O,o.sessionDataList=D,o.sessionKeyList=X,o.contentSteering=U,o}return N(n,l),m(n)})(P);p.MasterPlaylist=q;var I=(function(l){function n(){var o,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};y(this,n),d(o=G(this,n,[Y(Y({},r),{},{isMasterPlaylist:false})]),"targetDuration",void 0),d(o,"mediaSequenceBase",void 0),d(o,"discontinuitySequenceBase",void 0),d(o,"endlist",void 0),d(o,"playlistType",void 0),d(o,"isIFrame",void 0),d(o,"segments",void 0),d(o,"prefetchSegments",void 0),d(o,"lowLatencyCompatibility",void 0),d(o,"partTargetDuration",void 0),d(o,"renditionReports",void 0),d(o,"skip",void 0),d(o,"hash",void 0);var f=r.targetDuration,h=r.mediaSequenceBase,O=h===void 0?0:h,R=r.discontinuitySequenceBase,D=R===void 0?0:R,S=r.endlist,X=S!==void 0&&S,M=r.playlistType,U=r.isIFrame,V=r.segments,L=V===void 0?[]:V,k=r.prefetchSegments,z=k===void 0?[]:k,Q=r.lowLatencyCompatibility,et=r.partTargetDuration,K=r.renditionReports,Z=K===void 0?[]:K,$=r.skip,nt=$===void 0?0:$,J=r.hash;return o.targetDuration=f,o.mediaSequenceBase=O,o.discontinuitySequenceBase=D,o.endlist=X,o.playlistType=M,o.isIFrame=U,o.segments=L,o.prefetchSegments=z,o.lowLatencyCompatibility=Q,o.partTargetDuration=et,o.renditionReports=Z,o.skip=nt,o.hash=J,o}return N(n,l),m(n)})(P);p.MediaPlaylist=I;var E=(function(l){function n(o){var r,f=o.uri,h=o.mimeType,O=o.data,R=o.duration,D=o.title,S=o.byterange,X=o.discontinuity,M=o.mediaSequenceNumber,U=M===void 0?0:M,V=o.discontinuitySequence,L=V===void 0?0:V,k=o.key,z=o.map,Q=o.programDateTime,et=o.dateRange,K=o.markers,Z=K===void 0?[]:K,$=o.parts,nt=$===void 0?[]:$,J=o.gap;return y(this,n),d(r=G(this,n,["segment"]),"uri",void 0),d(r,"mimeType",void 0),d(r,"data",void 0),d(r,"duration",void 0),d(r,"title",void 0),d(r,"byterange",void 0),d(r,"discontinuity",void 0),d(r,"mediaSequenceNumber",void 0),d(r,"discontinuitySequence",void 0),d(r,"key",void 0),d(r,"map",void 0),d(r,"programDateTime",void 0),d(r,"dateRange",void 0),d(r,"markers",void 0),d(r,"parts",void 0),d(r,"gap",void 0),r.uri=f,r.mimeType=h,r.data=O,r.duration=R,r.title=D,r.byterange=S,r.discontinuity=X,r.mediaSequenceNumber=U,r.discontinuitySequence=L,r.key=k,r.map=z,r.programDateTime=Q,r.dateRange=et,r.markers=Z,r.parts=nt,r.gap=J,r}return N(n,l),m(n)})(ut);p.Segment=E;var s=(function(l){function n(o){var r,f=o.hint,h=f!==void 0&&f,O=o.uri,R=o.duration,D=o.independent,S=o.byterange,X=o.gap;return y(this,n),d(r=G(this,n,["part"]),"hint",void 0),d(r,"uri",void 0),d(r,"duration",void 0),d(r,"independent",void 0),d(r,"byterange",void 0),d(r,"gap",void 0),F.PARAMCHECK(O),r.hint=h,r.uri=O,r.duration=R,r.independent=D,r.duration=R,r.byterange=S,r.gap=X,r}return N(n,l),m(n)})(ut);p.PartialSegment=s;var a=(function(l){function n(o){var r,f=o.uri,h=o.discontinuity,O=o.mediaSequenceNumber,R=O===void 0?0:O,D=o.discontinuitySequence,S=D===void 0?0:D,X=o.key;return y(this,n),d(r=G(this,n,["prefetch"]),"uri",void 0),d(r,"discontinuity",void 0),d(r,"mediaSequenceNumber",void 0),d(r,"discontinuitySequence",void 0),d(r,"key",void 0),F.PARAMCHECK(f),r.uri=f,r.discontinuity=h,r.mediaSequenceNumber=R,r.discontinuitySequence=S,r.key=X,r}return N(n,l),m(n)})(ut);p.PrefetchSegment=a;var c=m((function l(n){var o=n.uri,r=n.lastMSN,f=n.lastPart;y(this,l),d(this,"uri",void 0),d(this,"lastMSN",void 0),d(this,"lastPart",void 0),F.PARAMCHECK(o),this.uri=o,this.lastMSN=r,this.lastPart=f;}));p.RenditionReport=c;},73:function(b,p,T){var A,x=this&&this.__createBinding||(Object.create?function(y,d,C,_){_===void 0&&(_=C);var j=Object.getOwnPropertyDescriptor(d,C);j&&!("get"in j?!d.__esModule:j.writable||j.configurable)||(j={enumerable:true,get:function(){return d[C]}}),Object.defineProperty(y,_,j);}:function(y,d,C,_){_===void 0&&(_=C),y[_]=d[C];}),Y=this&&this.__setModuleDefault||(Object.create?function(y,d){Object.defineProperty(y,"default",{enumerable:true,value:d});}:function(y,d){y.default=d;}),G=this&&this.__importStar||(A=function(y){return A=Object.getOwnPropertyNames||function(d){var C=[];for(var _ in d)Object.prototype.hasOwnProperty.call(d,_)&&(C[C.length]=_);return C},A(y)},function(y){if(y&&y.__esModule)return y;var d={};if(y!=null)for(var C=A(y),_=0;_<C.length;_++)C[_]!=="default"&&x(d,y,C[_]);return Y(d,y),d}),B=this&&this.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(p,"__esModule",{value:true}),p.setOptions=p.getOptions=p.types=p.stringify=p.parse=void 0;const v=T(203);Object.defineProperty(p,"getOptions",{enumerable:true,get:function(){return v.getOptions}}),Object.defineProperty(p,"setOptions",{enumerable:true,get:function(){return v.setOptions}});const N=B(T(377));p.parse=N.default;const w=B(T(887));p.stringify=w.default;const m=G(T(31));p.types=m;},203:(b,p)=>{function T(v,N){return (function(w){if(Array.isArray(w))return w})(v)||(function(w,m){var y=w==null?null:typeof Symbol<"u"&&w[Symbol.iterator]||w["@@iterator"];if(y!=null){var d,C,_,j,rt=[],at=true,F=false;try{if(_=(y=y.call(w)).next,m!==0)for(;!(at=(d=_.call(y)).done)&&(rt.push(d.value),rt.length!==m);at=!0);}catch(pt){F=true,C=pt;}finally{try{if(!at&&y.return!=null&&(j=y.return(),Object(j)!==j))return}finally{if(F)throw C}}return rt}})(v,N)||x(v,N)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function A(v,N){var w=typeof Symbol<"u"&&v[Symbol.iterator]||v["@@iterator"];if(!w){if(Array.isArray(v)||(w=x(v))||N){w&&(v=w);var m=0,y=function(){};return {s:y,n:function(){return m>=v.length?{done:true}:{done:false,value:v[m++]}},e:function(j){throw j},f:y}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var d,C=true,_=false;return {s:function(){w=w.call(v);},n:function(){var j=w.next();return C=j.done,j},e:function(j){_=true,d=j;},f:function(){try{C||w.return==null||w.return();}finally{if(_)throw d}}}}function x(v,N){if(v){if(typeof v=="string")return Y(v,N);var w={}.toString.call(v).slice(8,-1);return w==="Object"&&v.constructor&&(w=v.constructor.name),w==="Map"||w==="Set"?Array.from(v):w==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(w)?Y(v,N):void 0}}function Y(v,N){(N==null||N>v.length)&&(N=v.length);for(var w=0,m=Array(N);w<N;w++)m[w]=v[w];return m}Object.defineProperty(p,"__esModule",{value:true}),p.THROW=B,p.ASSERT=function(v){for(var N=arguments.length,w=new Array(N>1?N-1:0),m=1;m<N;m++)w[m-1]=arguments[m];var y,d=A(w.entries());try{for(d.s();!(y=d.n()).done;){var C=T(y.value,2),_=C[0];C[1]||B(new Error("".concat(v," : Failed at [").concat(_,"]")));}}catch(j){d.e(j);}finally{d.f();}},p.CONDITIONALASSERT=function(){for(var v=arguments.length,N=new Array(v),w=0;w<v;w++)N[w]=arguments[w];var m,y=A(N.entries());try{for(y.s();!(m=y.n()).done;){var d=T(m.value,2),C=d[0],_=T(d[1],2),j=_[0],rt=_[1];j&&(rt||B(new Error("Conditional Assert : Failed at [".concat(C,"]"))));}}catch(at){y.e(at);}finally{y.f();}},p.PARAMCHECK=function(){for(var v=arguments.length,N=new Array(v),w=0;w<v;w++)N[w]=arguments[w];var m,y=A(N.entries());try{for(y.s();!(m=y.n()).done;){var d=T(m.value,2),C=d[0];d[1]===void 0&&B(new Error("Param Check : Failed at [".concat(C,"]")));}}catch(_){y.e(_);}finally{y.f();}},p.CONDITIONALPARAMCHECK=function(){for(var v=arguments.length,N=new Array(v),w=0;w<v;w++)N[w]=arguments[w];var m,y=A(N.entries());try{for(y.s();!(m=y.n()).done;){var d=T(m.value,2),C=d[0],_=T(d[1],2),j=_[0],rt=_[1];j&&rt===void 0&&B(new Error("Conditional Param Check : Failed at [".concat(C,"]")));}}catch(at){y.e(at);}finally{y.f();}},p.INVALIDPLAYLIST=function(v){B(new Error("Invalid Playlist : ".concat(v)));},p.toNumber=function(v){var N=arguments.length>1&&arguments[1]!==void 0?arguments[1]:10;if(typeof v=="number")return v;var w=N===10?Number.parseFloat(v):Number.parseInt(v,N);return Number.isNaN(w)?0:w},p.hexToByteSequence=function(v){(v.startsWith("0x")||v.startsWith("0X"))&&(v=v.slice(2));for(var N=new Uint8Array(v.length/2),w=0;w<v.length;w+=2)N[w/2]=Number.parseInt(v.slice(w,w+2),16);return N},p.byteSequenceToHex=function(v){var N=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v.byteLength;w<=N&&B(new Error("end must be larger than start : start=".concat(N,", end=").concat(w)));for(var m=[],y=N;y<w;y++)m.push("0".concat((255&v[y]).toString(16).toUpperCase()).slice(-2));return "0x".concat(m.join(""))},p.tryCatch=function(v,N){try{return v()}catch(w){return N(w)}},p.splitAt=function(v,N){for(var w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,m=-1,y=0,d=0;y<v.length;y++)if(v[y]===N){if(d++===w)return [v.slice(0,y),v.slice(y+1)];m=y;}return m!==-1?[v.slice(0,m),v.slice(m+1)]:[v]},p.trim=function(v){var N=arguments.length>1&&arguments[1]!==void 0?arguments[1]:" ";return !v||(v=v.trim(),N===" ")||(v.startsWith(N)&&(v=v.slice(1)),v.endsWith(N)&&(v=v.slice(0,-1))),v},p.splitByCommaWithPreservingQuotes=function(v){for(var N=[],w=true,m=0,y=[],d=0;d<v.length;d++){var C=v[d];w&&C===","?(N.push(v.slice(m,d).trim()),m=d+1):C!=='"'&&C!=="'"||(w?(y.push(C),w=false):C===y.at(-1)?(y.pop(),w=true):y.push(C));}return N.push(v.slice(m).trim()),N},p.camelify=function(v){var N,w=[],m=false,y=A(v);try{for(y.s();!(N=y.n()).done;){var d=N.value;d!=="-"&&d!=="_"?m?(w.push(d.toUpperCase()),m=!1):w.push(d.toLowerCase()):m=!0;}}catch(C){y.e(C);}finally{y.f();}return w.join("")},p.formatDate=function(v){var N=v.getUTCFullYear(),w=("0"+(v.getUTCMonth()+1)).slice(-2),m=("0"+v.getUTCDate()).slice(-2),y=("0"+v.getUTCHours()).slice(-2),d=("0"+v.getUTCMinutes()).slice(-2),C=("0"+v.getUTCSeconds()).slice(-2),_=("00"+v.getUTCMilliseconds()).slice(-3);return "".concat(N,"-").concat(w,"-").concat(m,"T").concat(y,":").concat(d,":").concat(C,".").concat(_,"Z")},p.hasOwnProp=function(v,N){return Object.hasOwn(v,N)},p.setOptions=function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};G=Object.assign(G,v);},p.getOptions=function(){return Object.assign({},G)};var G={};function B(v){if(G.strictMode)throw v;G.silent||console.error(v.message);}},377:function(b,p,T){function A(I,E){return (function(s){if(Array.isArray(s))return s})(I)||(function(s,a){var c=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(c!=null){var l,n,o,r,f=[],h=true,O=false;try{if(o=(c=c.call(s)).next,a===0){if(Object(c)!==c)return;h=!1;}else for(;!(h=(l=o.call(c)).done)&&(f.push(l.value),f.length!==a);h=!0);}catch(R){O=true,n=R;}finally{try{if(!h&&c.return!=null&&(r=c.return(),Object(r)!==r))return}finally{if(O)throw n}}return f}})(I,E)||Y(I,E)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function x(I,E){var s=typeof Symbol<"u"&&I[Symbol.iterator]||I["@@iterator"];if(!s){if(Array.isArray(I)||(s=Y(I))||E){s&&(I=s);var a=0,c=function(){};return {s:c,n:function(){return a>=I.length?{done:true}:{done:false,value:I[a++]}},e:function(r){throw r},f:c}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var l,n=true,o=false;return {s:function(){s=s.call(I);},n:function(){var r=s.next();return n=r.done,r},e:function(r){o=true,l=r;},f:function(){try{n||s.return==null||s.return();}finally{if(o)throw l}}}}function Y(I,E){if(I){if(typeof I=="string")return G(I,E);var s={}.toString.call(I).slice(8,-1);return s==="Object"&&I.constructor&&(s=I.constructor.name),s==="Map"||s==="Set"?Array.from(I):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?G(I,E):void 0}}function G(I,E){(E==null||E>I.length)&&(E=I.length);for(var s=0,a=Array(E);s<E;s++)a[s]=I[s];return a}var B,v=this&&this.__createBinding||(Object.create?function(I,E,s,a){a===void 0&&(a=s);var c=Object.getOwnPropertyDescriptor(E,s);c&&!("get"in c?!E.__esModule:c.writable||c.configurable)||(c={enumerable:true,get:function(){return E[s]}}),Object.defineProperty(I,a,c);}:function(I,E,s,a){a===void 0&&(a=s),I[a]=E[s];}),N=this&&this.__setModuleDefault||(Object.create?function(I,E){Object.defineProperty(I,"default",{enumerable:true,value:E});}:function(I,E){I.default=E;}),w=this&&this.__importStar||(B=function(I){return B=Object.getOwnPropertyNames||function(E){var s=[];for(var a in E)Object.prototype.hasOwnProperty.call(E,a)&&(s[s.length]=a);return s},B(I)},function(I){if(I&&I.__esModule)return I;var E={};if(I!=null)for(var s=B(I),a=0;a<s.length;a++)s[a]!=="default"&&v(E,I,s[a]);return N(E,I),E});Object.defineProperty(p,"__esModule",{value:true});var m=w(T(203)),y=T(31);function d(I){return m.trim(I,'"')}function C(I){var E=m.splitAt(I,",");return {duration:m.toNumber(E[0]),title:decodeURIComponent(escape(E[1]))}}function _(I){var E=m.splitAt(I,"@");return {length:m.toNumber(E[0]),offset:E[1]?m.toNumber(E[1]):-1}}function j(I){var E=m.splitAt(I,"x");return {width:m.toNumber(E[0]),height:m.toNumber(E[1])}}function rt(I){var E="ALLOWED-CPC: Each entry must consit of KEYFORMAT and Content Protection Configuration",s=I.split(",");s.length===0&&m.INVALIDPLAYLIST(E);var a,c=[],l=x(s);try{for(l.s();!(a=l.n()).done;){var n=a.value,o=A(m.splitAt(n,":"),2),r=o[0],f=o[1];r&&f?c.push({format:r,cpcList:f.split("/")}):m.INVALIDPLAYLIST(E);}}catch(h){l.e(h);}finally{l.f();}return c}function at(I){return I.startsWith('"')?d(I):I.startsWith("0x")||I.startsWith("0X")?m.hexToByteSequence(I):m.toNumber(I)}function F(I,E){E.IV&&I.compatibleVersion<2&&(I.compatibleVersion=2),(E.KEYFORMAT||E.KEYFORMATVERSIONS)&&I.compatibleVersion<5&&(I.compatibleVersion=5);}function pt(I){var E,s,a,c={},l=x(m.splitByCommaWithPreservingQuotes(I));try{for(l.s();!(E=l.n()).done;){var n=E.value,o=A(m.splitAt(n,"="),2),r=o[0],f=o[1],h=d(f);switch(r){case "URI":c[r]=h;break;case "START-DATE":case "END-DATE":c[r]=new Date(h);break;case "IV":c[r]=(s=h,a=void 0,(a=m.hexToByteSequence(s)).length!==16&&m.INVALIDPLAYLIST("IV must be a 128-bit unsigned integer"),a);break;case "BYTERANGE":c[r]=_(h);break;case "RESOLUTION":c[r]=j(h);break;case "ALLOWED-CPC":c[r]=rt(h);break;case "END-ON-NEXT":case "DEFAULT":case "AUTOSELECT":case "FORCED":case "PRECISE":case "CAN-BLOCK-RELOAD":case "INDEPENDENT":case "GAP":c[r]=h==="YES";break;case "DURATION":case "PLANNED-DURATION":case "BANDWIDTH":case "AVERAGE-BANDWIDTH":case "FRAME-RATE":case "TIME-OFFSET":case "CAN-SKIP-UNTIL":case "HOLD-BACK":case "PART-HOLD-BACK":case "PART-TARGET":case "BYTERANGE-START":case "BYTERANGE-LENGTH":case "LAST-MSN":case "LAST-PART":case "SKIPPED-SEGMENTS":case "SCORE":case "PROGRAM-ID":c[r]=m.toNumber(h);break;default:r.startsWith("SCTE35-")?c[r]=m.hexToByteSequence(h):r.startsWith("X-")?c[r]=at(f):(r==="VIDEO-RANGE"&&h!=="SDR"&&h!=="HLG"&&h!=="PQ"&&m.INVALIDPLAYLIST('VIDEO-RANGE: unknown value "'.concat(h,'"')),c[r]=h);}}}catch(O){l.e(O);}finally{l.f();}return c}function ot(){m.INVALIDPLAYLIST("The file contains both media and master playlist tags.");}function Xt(I,E,s){var a,c=(a=E.attributes,new y.Rendition({type:a.TYPE,uri:a.URI,groupId:a["GROUP-ID"],language:a.LANGUAGE,assocLanguage:a["ASSOC-LANGUAGE"],name:a.NAME,isDefault:a.DEFAULT,autoselect:a.AUTOSELECT,forced:a.FORCED,instreamId:a["INSTREAM-ID"],characteristics:a.CHARACTERISTICS,channels:a.CHANNELS,pathwayId:a["PATHWAY-ID"]})),l=I[m.camelify(s)],n=(function(o,r){var f,h=false,O=x(o);try{for(O.s();!(f=O.n()).done;){var R=f.value;if(R.name===r.name)return "All EXT-X-MEDIA tags in the same Group MUST have different NAME attributes.";R.isDefault&&(h=!0);}}catch(D){O.e(D);}finally{O.f();}return h&&r.isDefault?"EXT-X-MEDIA A Group MUST NOT have more than one member with a DEFAULT attribute of YES.":""})(l,c);n&&m.INVALIDPLAYLIST(n),l.push(c),c.isDefault&&(I.currentRenditions[m.camelify(s)]=l.length-1);}function At(I,E,s,a,c){var l,n=new y.Variant({uri:s,bandwidth:E.BANDWIDTH,averageBandwidth:E["AVERAGE-BANDWIDTH"],score:E.SCORE,codecs:E.CODECS,resolution:E.RESOLUTION,frameRate:E["FRAME-RATE"],hdcpLevel:E["HDCP-LEVEL"],allowedCpc:E["ALLOWED-CPC"],videoRange:E["VIDEO-RANGE"],stableVariantId:E["STABLE-VARIANT-ID"],pathwayId:E["STABLE-PATHWAY-ID"],programId:E["PROGRAM-ID"]}),o=x(I);try{for(o.s();!(l=o.n()).done;){var r=l.value;if(r.name==="EXT-X-MEDIA"){var f=r.attributes,h=f.TYPE;if(h&&f["GROUP-ID"]||m.INVALIDPLAYLIST("EXT-X-MEDIA TYPE attribute is REQUIRED."),E[h]===f["GROUP-ID"]&&(Xt(n,r,h),h==="CLOSED-CAPTIONS")){var O,R=x(n.closedCaptions);try{for(R.s();!(O=R.n()).done;){var D=O.value.instreamId;if(D&&D.startsWith("SERVICE")&&c.compatibleVersion<7){c.compatibleVersion=7;break}}}catch(S){R.e(S);}finally{R.f();}}}}}catch(S){o.e(S);}finally{o.f();}return (function(S,X,M){for(var U=function(){var k=L[V];k==="CLOSED-CAPTIONS"&&S[k]==="NONE"?(M.isClosedCaptionsNone=true,X.closedCaptions=[]):S[k]&&!X[m.camelify(k)].some((function(z){return z.groupId===S[k]}))&&m.INVALIDPLAYLIST("".concat(k," attribute MUST match the value of the GROUP-ID attribute of an EXT-X-MEDIA tag whose TYPE attribute is ").concat(k,"."));},V=0,L=["AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS"];V<L.length;V++)U();})(E,n,c),n.isIFrameOnly=a,n}function Et(I,E,s,a,c,l,n){for(var o=new y.Segment({uri:E,mediaSequenceNumber:c,discontinuitySequence:l}),r=false,f=false,h=s;h<=a;h++){var O=q(I[h]),R=O.name,D=O.value,S=O.attributes;if(R==="EXTINF")!Number.isInteger(D.duration)&&n.compatibleVersion<3&&(n.compatibleVersion=3),Math.round(D.duration)>n.targetDuration&&m.INVALIDPLAYLIST("EXTINF duration, when rounded to the nearest integer, MUST be less than or equal to the target duration"),o.duration=D.duration,o.title=D.title;else if(R==="EXT-X-BYTERANGE")n.compatibleVersion<4&&(n.compatibleVersion=4),o.byterange=D;else if(R==="EXT-X-DISCONTINUITY")o.parts.length>0&&m.INVALIDPLAYLIST("EXT-X-DISCONTINUITY must appear before the first EXT-X-PART tag of the Parent Segment."),o.discontinuity=true;else if(R==="EXT-X-GAP")n.compatibleVersion<8&&(n.compatibleVersion=8),o.gap=true;else if(R==="EXT-X-KEY")o.parts.length>0&&m.INVALIDPLAYLIST("EXT-X-KEY must appear before the first EXT-X-PART tag of the Parent Segment."),F(n,S),o.key=new y.Key({method:S.METHOD,uri:S.URI,iv:S.IV,format:S.KEYFORMAT,formatVersion:S.KEYFORMATVERSIONS});else if(R==="EXT-X-MAP")o.parts.length>0&&m.INVALIDPLAYLIST("EXT-X-MAP must appear before the first EXT-X-PART tag of the Parent Segment."),n.compatibleVersion<5&&(n.compatibleVersion=5),n.hasMap=true,o.map=new y.MediaInitializationSection({uri:S.URI,byterange:S.BYTERANGE});else if(R==="EXT-X-PROGRAM-DATE-TIME")o.programDateTime=D;else if(R==="EXT-X-DATERANGE"){for(var X={},M=0,U=Object.keys(S);M<U.length;M++){var V=U[M];(V.startsWith("SCTE35-")||V.startsWith("X-"))&&(X[V]=S[V]);}o.dateRange=new y.DateRange({id:S.ID,classId:S.CLASS,start:S["START-DATE"],cue:S.CUE,end:S["END-DATE"],duration:S.DURATION,plannedDuration:S["PLANNED-DURATION"],endOnNext:S["END-ON-NEXT"],attributes:X});}else if(R==="EXT-X-CUE-OUT")o.markers.push(new y.SpliceInfo({type:"OUT",duration:S&&S.DURATION||D}));else if(R==="EXT-X-CUE-IN")o.markers.push(new y.SpliceInfo({type:"IN"}));else if(R==="EXT-X-CUE-OUT-CONT"||R==="EXT-X-CUE"||R==="EXT-OATCLS-SCTE35"||R==="EXT-X-ASSET"||R==="EXT-X-SCTE35")o.markers.push(new y.SpliceInfo({type:"RAW",tagName:R,value:D}));else if(R!=="EXT-X-PRELOAD-HINT"||S.TYPE)if(R==="EXT-X-PRELOAD-HINT"&&S.TYPE==="PART"&&f)m.INVALIDPLAYLIST("Servers should not add more than one EXT-X-PRELOAD-HINT tag with the same TYPE attribute to a Playlist.");else if(R!=="EXT-X-PART"&&R!=="EXT-X-PRELOAD-HINT"||S.URI){if(R==="EXT-X-PRELOAD-HINT"&&S.TYPE==="MAP")r&&m.INVALIDPLAYLIST("Servers should not add more than one EXT-X-PRELOAD-HINT tag with the same TYPE attribute to a Playlist."),r=true,n.hasMap=true,o.map=new y.MediaInitializationSection({hint:true,uri:S.URI,byterange:{length:S["BYTERANGE-LENGTH"],offset:S["BYTERANGE-START"]||0}});else if(R==="EXT-X-PART"||R==="EXT-X-PRELOAD-HINT"&&S.TYPE==="PART"){R!=="EXT-X-PART"||S.DURATION||m.INVALIDPLAYLIST("EXT-X-PART: DURATION attribute is mandatory"),R==="EXT-X-PRELOAD-HINT"&&(f=true);var L=new y.PartialSegment({hint:R==="EXT-X-PRELOAD-HINT",uri:S.URI,byterange:R==="EXT-X-PART"?S.BYTERANGE:{length:S["BYTERANGE-LENGTH"],offset:S["BYTERANGE-START"]||0},duration:S.DURATION,independent:S.INDEPENDENT,gap:S.GAP});o.gap&&!L.gap&&m.INVALIDPLAYLIST("Partial segments must have GAP=YES if they are in a gap (EXT-X-GAP)"),o.parts.push(L);}}else m.INVALIDPLAYLIST("EXT-X-PART / EXT-X-PRELOAD-HINT: URI attribute is mandatory");else m.INVALIDPLAYLIST("EXT-X-PRELOAD-HINT: TYPE attribute is mandatory");}return o}function yt(I,E,s,a,c,l,n){for(var o=new y.PrefetchSegment({uri:E,mediaSequenceNumber:c,discontinuitySequence:l}),r=s;r<=a;r++){var f=I[r],h=f.name,O=f.attributes;h==="EXTINF"?m.INVALIDPLAYLIST("A prefetch segment must not be advertised with an EXTINF tag."):h==="EXT-X-DISCONTINUITY"?m.INVALIDPLAYLIST("A prefetch segment must not be advertised with an EXT-X-DISCONTINUITY tag."):h==="EXT-X-PREFETCH-DISCONTINUITY"?o.discontinuity=true:h==="EXT-X-KEY"?(F(n,O),o.key=new y.Key({method:O.METHOD,uri:O.URI,iv:O.IV,format:O.KEYFORMAT,formatVersion:O.KEYFORMATVERSIONS})):h==="EXT-X-MAP"&&m.INVALIDPLAYLIST("Prefetch segments must not be advertised with an EXT-X-MAP tag.");}return o}function bt(I,E){var s,a=new y.MediaPlaylist,c=-1,l=0,n=false,o=false,r=0,f=null,h=null,O=false,R=x(I.entries());try{for(R.s();!(s=R.n()).done;){var D=A(s.value,2),S=D[0],X=D[1],M=q(X),U=M.name,V=M.value,L=M.attributes;if(M.category!=="Segment"){if(U==="EXT-X-VERSION")a.version===void 0?a.version=V:m.INVALIDPLAYLIST("A Playlist file MUST NOT contain more than one EXT-X-VERSION tag.");else if(U==="EXT-X-TARGETDURATION")a.targetDuration=E.targetDuration=V;else if(U==="EXT-X-MEDIA-SEQUENCE")a.segments.length>0&&m.INVALIDPLAYLIST("The EXT-X-MEDIA-SEQUENCE tag MUST appear before the first Media Segment in the Playlist."),a.mediaSequenceBase=l=V;else if(U==="EXT-X-DISCONTINUITY-SEQUENCE")a.segments.length>0&&m.INVALIDPLAYLIST("The EXT-X-DISCONTINUITY-SEQUENCE tag MUST appear before the first Media Segment in the Playlist."),n&&m.INVALIDPLAYLIST("The EXT-X-DISCONTINUITY-SEQUENCE tag MUST appear before any EXT-X-DISCONTINUITY tag."),a.discontinuitySequenceBase=r=V;else if(U==="EXT-X-ENDLIST")a.endlist=!0;else if(U==="EXT-X-PLAYLIST-TYPE")a.playlistType=V;else if(U==="EXT-X-I-FRAMES-ONLY")E.compatibleVersion<4&&(E.compatibleVersion=4),a.isIFrame=!0;else if(U==="EXT-X-INDEPENDENT-SEGMENTS")a.independentSegments&&m.INVALIDPLAYLIST("EXT-X-INDEPENDENT-SEGMENTS tag MUST NOT appear more than once in a Playlist"),a.independentSegments=!0;else if(U==="EXT-X-START")a.start&&m.INVALIDPLAYLIST("EXT-X-START tag MUST NOT appear more than once in a Playlist"),typeof L["TIME-OFFSET"]!="number"&&m.INVALIDPLAYLIST("EXT-X-START: TIME-OFFSET attribute is REQUIRED"),a.start={offset:L["TIME-OFFSET"],precise:L.PRECISE||!1};else if(U==="EXT-X-SERVER-CONTROL")L["CAN-BLOCK-RELOAD"]||m.INVALIDPLAYLIST("EXT-X-SERVER-CONTROL: CAN-BLOCK-RELOAD=YES is mandatory for Low-Latency HLS"),a.lowLatencyCompatibility={canBlockReload:L["CAN-BLOCK-RELOAD"],canSkipUntil:L["CAN-SKIP-UNTIL"],holdBack:L["HOLD-BACK"],partHoldBack:L["PART-HOLD-BACK"]};else if(U==="EXT-X-PART-INF")L["PART-TARGET"]||m.INVALIDPLAYLIST("EXT-X-PART-INF: PART-TARGET attribute is mandatory"),a.partTargetDuration=L["PART-TARGET"];else if(U==="EXT-X-RENDITION-REPORT")L.URI||m.INVALIDPLAYLIST("EXT-X-RENDITION-REPORT: URI attribute is mandatory"),L.URI.search(/^[a-z]+:/)===0&&m.INVALIDPLAYLIST("EXT-X-RENDITION-REPORT: URI must be relative to the playlist uri"),a.renditionReports.push(new y.RenditionReport({uri:L.URI,lastMSN:L["LAST-MSN"],lastPart:L["LAST-PART"]}));else if(U==="EXT-X-SKIP")L["SKIPPED-SEGMENTS"]||m.INVALIDPLAYLIST("EXT-X-SKIP: SKIPPED-SEGMENTS attribute is mandatory"),E.compatibleVersion<9&&(E.compatibleVersion=9),a.skip=L["SKIPPED-SEGMENTS"],l+=a.skip;else if(U==="EXT-X-PREFETCH"){var k=yt(I,V,c===-1?S:c,S-1,l++,r,E);k&&(k.discontinuity&&(k.discontinuitySequence++,r=k.discontinuitySequence),k.key?f=k.key:k.key=f,a.prefetchSegments.push(k)),o=!0,c=-1;}else if(U==="EXT-X-DEFINE")a.defines||(a.defines=[]),a.defines.push(L);else if(typeof X=="string"){c===-1&&m.INVALIDPLAYLIST("A URI line is not preceded by any segment tags"),a.targetDuration||m.INVALIDPLAYLIST("The EXT-X-TARGETDURATION tag is REQUIRED"),o&&m.INVALIDPLAYLIST("These segments must appear after all complete segments.");var z=Et(I,X,c,S-1,l++,r,E);if(z){var Q=A(vt(a,z,r,f,h),3);r=Q[0],f=Q[1],h=Q[2],!O&&z.parts.length>0&&(O=!0);}c=-1;}}else c===-1&&(c=S),U==="EXT-X-DISCONTINUITY"&&(n=!0);}}catch($){R.e($);}finally{R.f();}if(c!==-1){var et=Et(I,"",c,I.length-1,l++,r,E);if(et){var K,Z=et.parts;!(Z.length>0)||a.endlist||(K=Z.at(-1))!==null&&K!==void 0&&K.hint||m.INVALIDPLAYLIST("If the Playlist contains EXT-X-PART tags and does not contain an EXT-X-ENDLIST tag, the Playlist must contain an EXT-X-PRELOAD-HINT tag with a TYPE=PART attribute"),vt(a,et,f,h),!O&&et.parts.length>0&&(O=true);}}return (function($){for(var nt=new Map,J=new Map,st=false,dt=false,ft=$.length-1;ft>=0;ft--){var It=$[ft],wt=It.programDateTime,W=It.dateRange;if(wt&&(dt=true),W&&W.start){st=true,W.endOnNext&&(W.end||W.duration)&&m.INVALIDPLAYLIST("An EXT-X-DATERANGE tag with an END-ON-NEXT=YES attribute MUST NOT contain DURATION or END-DATE attributes.");var lt=W.start.getTime(),Kt=W.duration||0;W.end&&W.duration&<+1e3*Kt!==W.end.getTime()&&m.INVALIDPLAYLIST("END-DATE MUST be equal to the value of the START-DATE attribute plus the value of the DURATION"),W.endOnNext&&(W.end=nt.get(W.classId)),nt.set(W.classId,W.start);var Nt=W.end?W.end.getTime():W.start.getTime()+1e3*(W.duration||0),xt=J.get(W.classId);if(xt){var qt,Rt=x(xt);try{for(Rt.s();!(qt=Rt.n()).done;){var Dt=qt.value;(Dt.start<=lt&&Dt.end>lt||Dt.start>=lt&&Dt.start<Nt)&&m.INVALIDPLAYLIST("DATERANGE tags with the same CLASS should not overlap");}}catch(Mt){Rt.e(Mt);}finally{Rt.f();}xt.push({start:lt,end:Nt});}else W.classId&&J.set(W.classId,[{start:lt,end:Nt}]);}}st&&!dt&&m.INVALIDPLAYLIST("If a Playlist contains an EXT-X-DATERANGE tag, it MUST also contain at least one EXT-X-PROGRAM-DATE-TIME tag.");})(a.segments),a.lowLatencyCompatibility&&(function($,nt){var J=$.lowLatencyCompatibility,st=$.targetDuration,dt=$.partTargetDuration,ft=$.segments,It=$.renditionReports,wt=J.canSkipUntil,W=J.holdBack,lt=J.partHoldBack;if(wt<6*st&&m.INVALIDPLAYLIST("The Skip Boundary must be at least six times the EXT-X-TARGETDURATION."),W<3*st&&m.INVALIDPLAYLIST("HOLD-BACK must be at least three times the EXT-X-TARGETDURATION."),nt){dt===void 0&&m.INVALIDPLAYLIST("EXT-X-PART-INF is required if a Playlist contains one or more EXT-X-PART tags"),lt===void 0&&m.INVALIDPLAYLIST("EXT-X-PART: PART-HOLD-BACK attribute is mandatory"),lt<dt&&m.INVALIDPLAYLIST("PART-HOLD-BACK must be at least PART-TARGET");var Kt,Nt=x(ft.entries());try{for(Nt.s();!(Kt=Nt.n()).done;){var xt=A(Kt.value,2),qt=xt[0],Rt=xt[1].parts;Rt.length>0&&qt<ft.length-3&&m.INVALIDPLAYLIST("Remove EXT-X-PART tags from the Playlist after they are greater than three target durations from the end of the Playlist.");var Dt,Mt=x(Rt.entries());try{for(Mt.s();!(Dt=Mt.n()).done;){var Re=A(Dt.value,2),bn=Re[0],ie=Re[1].duration;ie!==void 0&&(ie>dt&&m.INVALIDPLAYLIST("PART-TARGET is the maximum duration of any Partial Segment"),bn<Rt.length-1&&ie<.85*dt&&m.INVALIDPLAYLIST("All Partial Segments except the last part of a segment must have a duration of at least 85% of PART-TARGET"));}}catch(Gt){Mt.e(Gt);}finally{Mt.f();}}}catch(Gt){Nt.e(Gt);}finally{Nt.f();}}var Oe,$t=x(It);try{for($t.s();!(Oe=$t.n()).done;){var Le,Vt=Oe.value,ae=ft.at(-1);(Le=Vt.lastMSN)!==null&&Le!==void 0||(Vt.lastMSN=ae.mediaSequenceNumber),(Vt.lastPart===null||Vt.lastPart===void 0)&&ae.parts.length>0&&(Vt.lastPart=ae.parts.length-1);}}catch(Gt){$t.e(Gt);}finally{$t.f();}})(a,O),a}function vt(I,E,s,a,c){var l=E.discontinuity,n=E.key,o=E.map,r=E.byterange,f=E.uri;if(l&&(E.discontinuitySequence=s+1),n||(E.key=a),o||(E.map=c),r&&r.offset===-1){var h=I.segments;if(h.length>0){var O=h.at(-1);O.byterange&&O.uri===f?r.offset=O.byterange.offset+O.byterange.length:m.INVALIDPLAYLIST("If offset of EXT-X-BYTERANGE is not present, a previous Media Segment MUST be a sub-range of the same media resource");}else m.INVALIDPLAYLIST("If offset of EXT-X-BYTERANGE is not present, a previous Media Segment MUST appear in the Playlist file");}return I.segments.push(E),[E.discontinuitySequence,E.key,E.map]}function ut(I,E){var s=(function(f){var h=f.indexOf(":");return h===-1?[f.slice(1).trim(),null]:[f.slice(1,h).trim(),f.slice(h+1).trim()]})(I),a=A(s,2),c=a[0],l=a[1],n=(function(f){switch(f){case "EXTM3U":case "EXT-X-VERSION":case "EXT-X-CONTENT-STEERING":return "Basic";case "EXTINF":case "EXT-X-BYTERANGE":case "EXT-X-DISCONTINUITY":case "EXT-X-PREFETCH-DISCONTINUITY":case "EXT-X-KEY":case "EXT-X-MAP":case "EXT-X-PROGRAM-DATE-TIME":case "EXT-X-DATERANGE":case "EXT-X-CUE-OUT":case "EXT-X-CUE-IN":case "EXT-X-CUE-OUT-CONT":case "EXT-X-CUE":case "EXT-OATCLS-SCTE35":case "EXT-X-ASSET":case "EXT-X-SCTE35":case "EXT-X-PART":case "EXT-X-PRELOAD-HINT":case "EXT-X-GAP":return "Segment";case "EXT-X-TARGETDURATION":case "EXT-X-MEDIA-SEQUENCE":case "EXT-X-DISCONTINUITY-SEQUENCE":case "EXT-X-ENDLIST":case "EXT-X-PLAYLIST-TYPE":case "EXT-X-I-FRAMES-ONLY":case "EXT-X-SERVER-CONTROL":case "EXT-X-PART-INF":case "EXT-X-PREFETCH":case "EXT-X-RENDITION-REPORT":case "EXT-X-SKIP":return "MediaPlaylist";case "EXT-X-MEDIA":case "EXT-X-STREAM-INF":case "EXT-X-I-FRAME-STREAM-INF":case "EXT-X-SESSION-DATA":case "EXT-X-SESSION-KEY":return "MasterPlaylist";case "EXT-X-INDEPENDENT-SEGMENTS":case "EXT-X-START":case "EXT-X-DEFINE":return "MediaorMasterPlaylist";default:return "Unknown"}})(c);if((function(f,h){if(f==="Segment"||f==="MediaPlaylist")return h.isMasterPlaylist===void 0?void(h.isMasterPlaylist=false):void(h.isMasterPlaylist&&ot());if(f==="MasterPlaylist"){if(h.isMasterPlaylist===void 0)return void(h.isMasterPlaylist=true);h.isMasterPlaylist===false&&ot();}})(n,E),n==="Unknown")return null;n==="MediaPlaylist"&&c!=="EXT-X-RENDITION-REPORT"&&c!=="EXT-X-PREFETCH"&&(E.hash[c]&&m.INVALIDPLAYLIST("There MUST NOT be more than one Media Playlist tag of each type in any Media Playlist"),E.hash[c]=true);var o=(function(f,h){switch(f){case "EXTM3U":case "EXT-X-DISCONTINUITY":case "EXT-X-ENDLIST":case "EXT-X-I-FRAMES-ONLY":case "EXT-X-INDEPENDENT-SEGMENTS":case "EXT-X-CUE-IN":case "EXT-X-GAP":return [null,null];case "EXT-X-VERSION":case "EXT-X-TARGETDURATION":case "EXT-X-MEDIA-SEQUENCE":case "EXT-X-DISCONTINUITY-SEQUENCE":return [m.toNumber(h),null];case "EXT-X-CUE-OUT":return Number.isNaN(Number(h))?[null,pt(h)]:[m.toNumber(h),null];case "EXT-X-KEY":case "EXT-X-MAP":case "EXT-X-DATERANGE":case "EXT-X-MEDIA":case "EXT-X-STREAM-INF":case "EXT-X-I-FRAME-STREAM-INF":case "EXT-X-SESSION-DATA":case "EXT-X-SESSION-KEY":case "EXT-X-START":case "EXT-X-SERVER-CONTROL":case "EXT-X-PART-INF":case "EXT-X-PART":case "EXT-X-PRELOAD-HINT":case "EXT-X-RENDITION-REPORT":case "EXT-X-SKIP":case "EXT-X-DEFINE":return [null,pt(h)];case "EXTINF":return [C(h),null];case "EXT-X-BYTERANGE":return [_(h),null];case "EXT-X-PROGRAM-DATE-TIME":return [new Date(h),null];default:return [h,null]}})(c,l),r=A(o,2);return {name:c,category:n,value:r[0],attributes:r[1]}}function P(I,E){var s;return E.isMasterPlaylist?s=(function(a,c){var l,n=new y.MasterPlaylist,o=false,r=x(a.entries());try{var f=function(){var S=A(l.value,2),X=S[0],M=q(S[1]),U=M.name,V=M.value,L=M.attributes;if(U==="EXT-X-VERSION")n.version=V;else if(U==="EXT-X-CONTENT-STEERING-SERVER"){var k=new y.ContentSteering({serverUri:L["SERVER-URI"],pathwayId:L["PATHWAY-ID"]});n.contentSteering=k;}else if(U==="EXT-X-STREAM-INF"){var z=a[X+1];(typeof z!="string"||z.startsWith("#EXT"))&&m.INVALIDPLAYLIST("EXT-X-STREAM-INF must be followed by a URI line");var Q=At(a,L,z,!1,c);Q&&(typeof Q.score=="number"&&(o=!0,Q.score<0&&m.INVALIDPLAYLIST("SCORE attribute on EXT-X-STREAM-INF must be positive decimal-floating-point number.")),n.variants.push(Q));}else if(U==="EXT-X-I-FRAME-STREAM-INF"){var et=At(a,L,L.URI,!0,c);et&&n.variants.push(et);}else if(U==="EXT-X-SESSION-DATA"){var K=new y.SessionData({id:L["DATA-ID"],value:L.VALUE,uri:L.URI,language:L.LANGUAGE});n.sessionDataList.some((function($){return $.id===K.id&&$.language===K.language}))&&m.INVALIDPLAYLIST("A Playlist MUST NOT contain more than one EXT-X-SESSION-DATA tag with the same DATA-ID attribute and the same LANGUAGE attribute."),n.sessionDataList.push(K);}else if(U==="EXT-X-SESSION-KEY"){L.METHOD==="NONE"&&m.INVALIDPLAYLIST("EXT-X-SESSION-KEY: The value of the METHOD attribute MUST NOT be NONE");var Z=new y.Key({method:L.METHOD,uri:L.URI,iv:L.IV,format:L.KEYFORMAT,formatVersion:L.KEYFORMATVERSIONS});n.sessionKeyList.some((function($){return (function(nt,J){if(nt.method!==J.method||nt.uri!==J.uri)return !1;if(nt.iv){if(!J.iv||nt.iv.byteLength!==J.iv.byteLength)return !1;for(var st=0;st<nt.iv.byteLength;st++)if(nt.iv[st]!==J.iv[st])return !1}else if(J.iv)return !1;return nt.format===J.format&&nt.formatVersion===J.formatVersion})($,Z)}))&&m.INVALIDPLAYLIST("A Master Playlist MUST NOT contain more than one EXT-X-SESSION-KEY tag with the same METHOD, URI, IV, KEYFORMAT, and KEYFORMATVERSIONS attribute values."),F(c,L),n.sessionKeyList.push(Z);}else U==="EXT-X-INDEPENDENT-SEGMENTS"?(n.independentSegments&&m.INVALIDPLAYLIST("EXT-X-INDEPENDENT-SEGMENTS tag MUST NOT appear more than once in a Playlist"),n.independentSegments=!0):U==="EXT-X-START"?(n.start&&m.INVALIDPLAYLIST("EXT-X-START tag MUST NOT appear more than once in a Playlist"),typeof L["TIME-OFFSET"]!="number"&&m.INVALIDPLAYLIST("EXT-X-START: TIME-OFFSET attribute is REQUIRED"),n.start={offset:L["TIME-OFFSET"],precise:L.PRECISE||!1}):U==="EXT-X-DEFINE"&&(n.defines||(n.defines=[]),n.defines.push(L));};for(r.s();!(l=r.n()).done;)f();}catch(S){r.e(S);}finally{r.f();}if(o){var h,O=x(n.variants);try{for(O.s();!(h=O.n()).done;)typeof h.value.score!="number"&&m.INVALIDPLAYLIST("If any Variant Stream contains the SCORE attribute, then all Variant Streams in the Master Playlist SHOULD have a SCORE attribute");}catch(S){O.e(S);}finally{O.f();}}if(c.isClosedCaptionsNone){var R,D=x(n.variants);try{for(D.s();!(R=D.n()).done;)R.value.closedCaptions.length>0&&m.INVALIDPLAYLIST("If there is a variant with CLOSED-CAPTIONS attribute of NONE, all EXT-X-STREAM-INF tags MUST have this attribute with a value of NONE");}catch(S){D.e(S);}finally{D.f();}}return n})(I,E):!(s=bt(I,E)).isIFrame&&E.hasMap&&E.compatibleVersion<6&&(E.compatibleVersion=6),E.compatibleVersion>1&&(!s.version||s.version<E.compatibleVersion)&&m.INVALIDPLAYLIST("EXT-X-VERSION needs to be ".concat(E.compatibleVersion," or higher.")),s}function q(I){return typeof I=="string"?{}:I}p.default=function(I){var E={version:void 0,isMasterPlaylist:void 0,hasMap:false,targetDuration:0,compatibleVersion:1,isClosedCaptionsNone:false,hash:{}},s=P((function(a,c){var l,n=[],o=x(a.split(`
`));try{for(o.s();!(l=o.n()).done;){var r=l.value.trim();if(r)if(r.startsWith("#")){if(r.startsWith("#EXT")){var f=ut(r,c);f&&n.push(f);}}else n.push(r);}}catch(h){o.e(h);}finally{o.f();}return n.length!==0&&n[0].name==="EXTM3U"||m.INVALIDPLAYLIST("The EXTM3U tag MUST be the first line."),n})(I,E),E);return s.source=I,s};},887:function(b,p,T){function A(s){return A=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},A(s)}function x(s,a){return (function(c){if(Array.isArray(c))return c})(s)||(function(c,l){var n=c==null?null:typeof Symbol<"u"&&c[Symbol.iterator]||c["@@iterator"];if(n!=null){var o,r,f,h,O=[],R=true,D=false;try{if(f=(n=n.call(c)).next,l===0){if(Object(n)!==n)return;R=!1;}else for(;!(R=(o=f.call(n)).done)&&(O.push(o.value),O.length!==l);R=!0);}catch(S){D=true,r=S;}finally{try{if(!R&&n.return!=null&&(h=n.return(),Object(h)!==h))return}finally{if(D)throw r}}return O}})(s,a)||G(s,a)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function Y(s,a){var c=typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(!c){if(Array.isArray(s)||(c=G(s))||a){c&&(s=c);var l=0,n=function(){};return {s:n,n:function(){return l>=s.length?{done:true}:{done:false,value:s[l++]}},e:function(h){throw h},f:n}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o,r=true,f=false;return {s:function(){c=c.call(s);},n:function(){var h=c.next();return r=h.done,h},e:function(h){f=true,o=h;},f:function(){try{r||c.return==null||c.return();}finally{if(f)throw o}}}}function G(s,a){if(s){if(typeof s=="string")return B(s,a);var c={}.toString.call(s).slice(8,-1);return c==="Object"&&s.constructor&&(c=s.constructor.name),c==="Map"||c==="Set"?Array.from(s):c==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)?B(s,a):void 0}}function B(s,a){(a==null||a>s.length)&&(a=s.length);for(var c=0,l=Array(a);c<a;c++)l[c]=s[c];return l}function v(s,a){for(var c=0;c<a.length;c++){var l=a[c];l.enumerable=l.enumerable||false,l.configurable=true,"value"in l&&(l.writable=true),Object.defineProperty(s,j(l.key),l);}}function N(s,a,c){return a=_(a),(function(l,n){if(n&&(A(n)=="object"||typeof n=="function"))return n;if(n!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return (function(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o})(l)})(s,d()?Reflect.construct(a,[],_(s).constructor):a.apply(s,c))}function w(s,a,c,l){var n=m(_(s.prototype),a,c);return 2&l&&typeof n=="function"?function(o){return n.apply(c,o)}:n}function m(){return m=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(s,a,c){var l=(function(o,r){for(;!{}.hasOwnProperty.call(o,r)&&(o=_(o))!==null;);return o})(s,a);if(l){var n=Object.getOwnPropertyDescriptor(l,a);return n.get?n.get.call(arguments.length<3?s:c):n.value}},m.apply(null,arguments)}function y(s){var a=typeof Map=="function"?new Map:void 0;return y=function(c){if(c===null||!(function(n){try{return Function.toString.call(n).indexOf("[native code]")!==-1}catch{return typeof n=="function"}})(c))return c;if(typeof c!="function")throw new TypeError("Super expression must either be null or a function");if(a!==void 0){if(a.has(c))return a.get(c);a.set(c,l);}function l(){return (function(n,o,r){if(d())return Reflect.construct.apply(null,arguments);var f=[null];f.push.apply(f,o);var h=new(n.bind.apply(n,f));return r&&C(h,r.prototype),h})(c,arguments,_(this).constructor)}return l.prototype=Object.create(c.prototype,{constructor:{value:l,enumerable:false,writable:true,configurable:true}}),C(l,c)},y(s)}function d(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (d=function(){return !!s})()}function C(s,a){return C=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(c,l){return c.__proto__=l,c},C(s,a)}function _(s){return _=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},_(s)}function j(s){var a=(function(c,l){if(A(c)!="object"||!c)return c;var n=c[Symbol.toPrimitive];if(n!==void 0){var o=n.call(c,l);if(A(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(c)})(s,"string");return A(a)=="symbol"?a:a+""}var rt,at=this&&this.__createBinding||(Object.create?function(s,a,c,l){l===void 0&&(l=c);var n=Object.getOwnPropertyDescriptor(a,c);n&&!("get"in n?!a.__esModule:n.writable||n.configurable)||(n={enumerable:true,get:function(){return a[c]}}),Object.defineProperty(s,l,n);}:function(s,a,c,l){l===void 0&&(l=c),s[l]=a[c];}),F=this&&this.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:true,value:a});}:function(s,a){s.default=a;}),pt=this&&this.__importStar||(rt=function(s){return rt=Object.getOwnPropertyNames||function(a){var c=[];for(var l in a)Object.prototype.hasOwnProperty.call(a,l)&&(c[c.length]=l);return c},rt(s)},function(s){if(s&&s.__esModule)return s;var a={};if(s!=null)for(var c=rt(s),l=0;l<c.length;l++)c[l]!=="default"&&at(a,s,c[l]);return F(a,s),a});Object.defineProperty(p,"__esModule",{value:true});var ot=pt(T(203)),Xt=["#EXTINF","#EXT-X-BYTERANGE","#EXT-X-DISCONTINUITY","#EXT-X-STREAM-INF","#EXT-X-CUE-OUT","#EXT-X-CUE-IN","#EXT-X-KEY","#EXT-X-MAP"],At=["#EXT-X-MEDIA"],Et=(function(s){function a(o){var r,f,h,O;return (function(R,D){if(!(R instanceof D))throw new TypeError("Cannot call a class as a function")})(this,a),r=N(this,a),f=r,O=void 0,(h=j(h="baseUri"))in f?Object.defineProperty(f,h,{value:O,enumerable:true,configurable:true,writable:true}):f[h]=O,r.baseUri=o,r}return (function(o,r){if(typeof r!="function"&&r!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(r&&r.prototype,{constructor:{value:o,writable:true,configurable:true}}),Object.defineProperty(o,"prototype",{writable:false}),r&&C(o,r);})(a,s),c=a,l=[{key:"push",value:function(){for(var o=this,r=arguments.length,f=new Array(r),h=0;h<r;h++)f[h]=arguments[h];for(var O=function(){var S=D[R];if(!S.startsWith("#"))return w(a,"push",o,3)([S]),0;if(Xt.some((function(X){return S.startsWith(X)})))return w(a,"push",o,3)([S]),0;if(o.includes(S)){if(At.some((function(X){return S.startsWith(X)})))return 0;ot.INVALIDPLAYLIST("Redundant item (".concat(S,")"));}w(a,"push",o,3)([S]);},R=0,D=f;R<D.length;R++)O();return this.length}},{key:"join",value:function(){for(var o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:",",r=this.length-1;r>=0;r--)this[r]||this.splice(r,1);return w(a,"join",this,3)([o])}}],l&&v(c.prototype,l),n&&v(c,n),Object.defineProperty(c,"prototype",{writable:false}),c;var c,l,n;})(y(Array));function yt(s,a){var c=1e3;a&&(c=Math.pow(10,a));var l=Math.round(s*c)/c;return a?l.toFixed(a):l}function bt(s){var a=['DATA-ID="'.concat(s.id,'"')];return s.language&&a.push('LANGUAGE="'.concat(s.language,'"')),s.value?a.push('VALUE="'.concat(s.value,'"')):s.uri&&a.push('URI="'.concat(s.uri,'"')),"#EXT-X-SESSION-DATA:".concat(a.join(","))}function vt(s,a){var c=a?"#EXT-X-SESSION-KEY":"#EXT-X-KEY",l=["METHOD=".concat(s.method)];return s.uri&&l.push('URI="'.concat(s.uri,'"')),s.iv&&(s.iv.byteLength!==16&&ot.INVALIDPLAYLIST("IV must be a 128-bit unsigned integer"),l.push("IV=".concat(ot.byteSequenceToHex(s.iv)))),s.format&&l.push('KEYFORMAT="'.concat(s.format,'"')),s.formatVersion&&l.push('KEYFORMATVERSIONS="'.concat(s.formatVersion,'"')),"".concat(c,":").concat(l.join(","))}function ut(s,a){var c=a.isIFrameOnly?"#EXT-X-I-FRAME-STREAM-INF":"#EXT-X-STREAM-INF",l=["BANDWIDTH=".concat(a.bandwidth)];if(a.averageBandwidth&&l.push("AVERAGE-BANDWIDTH=".concat(a.averageBandwidth)),a.isIFrameOnly&&l.push('URI="'.concat(a.uri,'"')),a.codecs&&l.push('CODECS="'.concat(a.codecs,'"')),a.resolution&&l.push("RESOLUTION=".concat(a.resolution.width,"x").concat(a.resolution.height)),a.frameRate&&l.push("FRAME-RATE=".concat(yt(a.frameRate,3))),a.hdcpLevel&&l.push("HDCP-LEVEL=".concat(a.hdcpLevel)),a.audio.length>0){l.push('AUDIO="'.concat(a.audio[0].groupId,'"'));var n,o=Y(a.audio);try{for(o.s();!(n=o.n()).done;){var r=n.value;s.push(P(r));}}catch(K){o.e(K);}finally{o.f();}}if(a.video.length>0){l.push('VIDEO="'.concat(a.video[0].groupId,'"'));var f,h=Y(a.video);try{for(h.s();!(f=h.n()).done;){var O=f.value;s.push(P(O));}}catch(K){h.e(K);}finally{h.f();}}if(a.subtitles.length>0){l.push('SUBTITLES="'.concat(a.subtitles[0].groupId,'"'));var R,D=Y(a.subtitles);try{for(D.s();!(R=D.n()).done;){var S=R.value;s.push(P(S));}}catch(K){D.e(K);}finally{D.f();}}if(ot.getOptions().allowClosedCaptionsNone&&a.closedCaptions.length===0)l.push("CLOSED-CAPTIONS=NONE");else if(a.closedCaptions.length>0){l.push('CLOSED-CAPTIONS="'.concat(a.closedCaptions[0].groupId,'"'));var X,M=Y(a.closedCaptions);try{for(M.s();!(X=M.n()).done;){var U=X.value;s.push(P(U));}}catch(K){M.e(K);}finally{M.f();}}if(a.score&&l.push("SCORE=".concat(a.score)),a.allowedCpc){var V,L=[],k=Y(a.allowedCpc);try{for(k.s();!(V=k.n()).done;){var z=V.value,Q=z.format,et=z.cpcList;L.push("".concat(Q,":").concat(et.join("/")));}}catch(K){k.e(K);}finally{k.f();}l.push('ALLOWED-CPC="'.concat(L.join(","),'"'));}a.videoRange&&l.push("VIDEO-RANGE=".concat(a.videoRange)),a.stableVariantId&&l.push('STABLE-VARIANT-ID="'.concat(a.stableVariantId,'"')),a.pathwayId&&l.push('PATHWAY-ID="'.concat(a.pathwayId,'"')),a.programId&&l.push("PROGRAM-ID=".concat(a.programId)),s.push("".concat(c,":").concat(l.join(","))),a.isIFrameOnly||s.push("".concat(a.uri));}function P(s){var a=["TYPE=".concat(s.type),'GROUP-ID="'.concat(s.groupId,'"'),'NAME="'.concat(s.name,'"')];return s.isDefault!==void 0&&a.push("DEFAULT=".concat(s.isDefault?"YES":"NO")),s.autoselect!==void 0&&a.push("AUTOSELECT=".concat(s.autoselect?"YES":"NO")),s.forced!==void 0&&a.push("FORCED=".concat(s.forced?"YES":"NO")),s.language&&a.push('LANGUAGE="'.concat(s.language,'"')),s.assocLanguage&&a.push('ASSOC-LANGUAGE="'.concat(s.assocLanguage,'"')),s.instreamId&&a.push('INSTREAM-ID="'.concat(s.instreamId,'"')),s.characteristics&&a.push('CHARACTERISTICS="'.concat(s.characteristics,'"')),s.channels&&a.push('CHANNELS="'.concat(s.channels,'"')),s.uri&&a.push('URI="'.concat(s.uri,'"')),"#EXT-X-MEDIA:".concat(a.join(","))}function q(s,a,c,l){var n,o,r,f=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1,h=false,O="";if(a.discontinuity&&s.push("#EXT-X-DISCONTINUITY"),a.gap&&s.push("#EXT-X-GAP"),a.key){var R=vt(a.key);R!==c&&(s.push(R),c=R);}if(a.map){var D=(function(X){var M=['URI="'.concat(X.uri,'"')];return X.byterange&&M.push('BYTERANGE="'.concat(I(X.byterange),'"')),"#EXT-X-MAP:".concat(M.join(","))})(a.map);D!==l&&(s.push(D),l=D);}if(a.programDateTime&&s.push("#EXT-X-PROGRAM-DATE-TIME:".concat(ot.formatDate(a.programDateTime))),a.dateRange&&s.push((function(X){var M=['ID="'.concat(X.id,'"')];X.start&&M.push('START-DATE="'.concat(ot.formatDate(X.start),'"')),X.cue&&M.push('CUE="'.concat(X.cue,'"')),X.end&&M.push('END-DATE="'.concat(ot.formatDate(X.end),'"')),X.duration&&M.push("DURATION=".concat(X.duration)),X.plannedDuration&&M.push("PLANNED-DURATION=".concat(X.plannedDuration)),X.classId&&M.push('CLASS="'.concat(X.classId,'"')),X.endOnNext&&M.push("END-ON-NEXT=YES");for(var U=0,V=Object.keys(X.attributes);U<V.length;U++){var L=V[U];L.startsWith("X-")?typeof X.attributes[L]=="number"?M.push("".concat(L,"=").concat(X.attributes[L])):M.push("".concat(L,'="').concat(X.attributes[L],'"')):L.startsWith("SCTE35-")&&M.push("".concat(L,"=").concat(ot.byteSequenceToHex(X.attributes[L])));}return "#EXT-X-DATERANGE:".concat(M.join(","))})(a.dateRange)),a.markers.length>0&&(O=(function(X,M){var U,V="",L=Y(M);try{for(L.s();!(U=L.n()).done;){var k=U.value;if(k.type==="OUT")V="OUT",X.push("#EXT-X-CUE-OUT:DURATION=".concat(k.duration));else if(k.type==="IN")V="IN",X.push("#EXT-X-CUE-IN");else if(k.type==="RAW"){var z=k.value?":".concat(k.value):"";X.push("#".concat(k.tagName).concat(z));}}}catch(Q){L.e(Q);}finally{L.f();}return V})(s,a.markers)),a.parts.length>0&&(h=(function(X,M){var U,V=false,L=Y(M);try{for(L.s();!(U=L.n()).done;){var k=U.value;if(k.hint){var z=[];if(z.push("TYPE=PART",'URI="'.concat(k.uri,'"')),k.byterange){var Q=k.byterange,et=Q.offset,K=Q.length;z.push("BYTERANGE-START=".concat(et)),K&&z.push("BYTERANGE-LENGTH=".concat(K));}X.push("#EXT-X-PRELOAD-HINT:".concat(z.join(","))),V=!0;}else {var Z=[];Z.push("DURATION=".concat(k.duration),'URI="'.concat(k.uri,'"')),k.byterange&&Z.push("BYTERANGE=".concat(I(k.byterange))),k.independent&&Z.push("INDEPENDENT=YES"),k.gap&&Z.push("GAP=YES"),X.push("#EXT-X-PART:".concat(Z.join(",")));}}}catch($){L.e($);}finally{L.f();}return V})(s,a.parts)),h)return [c,l];if(typeof a.duration=="number"&&!Number.isNaN(a.duration)){var S=f<3?Math.round(a.duration):yt(a.duration,(n=a.duration,o=n.toString(10),(r=o.indexOf("."))===-1?0:o.length-r-1));s.push("#EXTINF:".concat(S,",").concat(unescape(encodeURIComponent(a.title||""))));}return a.byterange&&s.push("#EXT-X-BYTERANGE:".concat(I(a.byterange))),Array.prototype.push.call(s,"".concat(a.uri)),[c,l,O]}function I(s){var a=s.offset,c=s.length;return "".concat(c,"@").concat(a)}function E(s){var a=[];for(var c in s)a.push("".concat(c,'="').concat(s[c],'"'));return "#EXT-X-DEFINE:".concat(a.join(","))}p.default=function(s,a){ot.PARAMCHECK(s),ot.ASSERT("Not a playlist",s.type==="playlist");var c=new Et(s.uri);if(c.push("#EXTM3U"),s.version&&c.push("#EXT-X-VERSION:".concat(s.version)),s.independentSegments&&c.push("#EXT-X-INDEPENDENT-SEGMENTS"),s.start&&c.push("#EXT-X-START:TIME-OFFSET=".concat(yt(s.start.offset)).concat(s.start.precise?",PRECISE=YES":"")),s.defines){var l,n=Y(s.defines);try{for(n.s();!(l=n.n()).done;){var o=l.value;c.push(E(o));}}catch(r){n.e(r);}finally{n.f();}}return s.isMasterPlaylist?(function(r,f,h){var O,R;f.contentSteering&&r.push((O=f.contentSteering,R=['SERVER-URI="'.concat(O.serverUri,'"'),'PATHWAY-ID="'.concat(O.pathwayId,'"')],"#EXT-X-CONTENT-STEERING:".concat(R.join(","))));var D,S=Y(f.sessionDataList);try{for(S.s();!(D=S.n()).done;){var X=D.value;r.push(bt(X));}}catch(Z){S.e(Z);}finally{S.f();}var M,U=Y(f.sessionKeyList);try{for(U.s();!(M=U.n()).done;){var V=M.value;r.push(vt(V,!0));}}catch(Z){U.e(Z);}finally{U.f();}var L,k=Y(f.variants.entries());try{for(k.s();!(L=k.n()).done;){var z=x(L.value,2),Q=z[0],et=z[1],K=r.length;ut(r,et),h!=null&&h.variantProcessor&&h.variantProcessor(r,K,r.length-1,et,Q);}}catch(Z){k.e(Z);}finally{k.f();}})(c,s,a):(function(r,f,h){var O="",R="",D=false;if(f.targetDuration&&r.push("#EXT-X-TARGETDURATION:".concat(f.targetDuration)),f.lowLatencyCompatibility){var S=f.lowLatencyCompatibility,X=S.canBlockReload,M=S.canSkipUntil,U=S.holdBack,V=S.partHoldBack,L=[];L.push("CAN-BLOCK-RELOAD=".concat(X?"YES":"NO")),M!==void 0&&L.push("CAN-SKIP-UNTIL=".concat(M)),U!==void 0&&L.push("HOLD-BACK=".concat(U)),V!==void 0&&L.push("PART-HOLD-BACK=".concat(V)),r.push("#EXT-X-SERVER-CONTROL:".concat(L.join(",")));}f.partTargetDuration&&r.push("#EXT-X-PART-INF:PART-TARGET=".concat(f.partTargetDuration)),f.mediaSequenceBase&&r.push("#EXT-X-MEDIA-SEQUENCE:".concat(f.mediaSequenceBase)),f.discontinuitySequenceBase&&r.push("#EXT-X-DISCONTINUITY-SEQUENCE:".concat(f.discontinuitySequenceBase)),f.playlistType&&r.push("#EXT-X-PLAYLIST-TYPE:".concat(f.playlistType)),f.isIFrame&&r.push("#EXT-X-I-FRAMES-ONLY"),f.skip>0&&r.push("#EXT-X-SKIP:SKIPPED-SEGMENTS=".concat(f.skip));var k,z=Y(f.segments.entries());try{for(z.s();!(k=z.n()).done;){var Q,et=x(k.value,2),K=et[0],Z=et[1],$=r.length,nt=x(q(r,Z,O,R,f.version),3);O=nt[0],R=nt[1],(Q=nt[2])==="OUT"?D=!0:Q==="IN"&&D&&(D=!1),h!=null&&h.segmentProcessor&&h.segmentProcessor(r,$,r.length-1,Z,K);}}catch(lt){z.e(lt);}finally{z.f();}f.playlistType==="VOD"&&D&&r.push("#EXT-X-CUE-IN"),f.prefetchSegments.length>2&&ot.INVALIDPLAYLIST("The server must deliver no more than two prefetch segments");var J,st=Y(f.prefetchSegments);try{for(st.s();!(J=st.n()).done;){var dt=J.value;dt.discontinuity&&r.push("#EXT-X-PREFETCH-DISCONTINUITY"),r.push("#EXT-X-PREFETCH:".concat(dt.uri));}}catch(lt){st.e(lt);}finally{st.f();}f.endlist&&r.push("#EXT-X-ENDLIST");var ft,It=Y(f.renditionReports);try{for(It.s();!(ft=It.n()).done;){var wt=ft.value,W=[];W.push('URI="'.concat(wt.uri,'"'),"LAST-MSN=".concat(wt.lastMSN)),wt.lastPart!==void 0&&W.push("LAST-PART=".concat(wt.lastPart)),r.push("#EXT-X-RENDITION-REPORT:".concat(W.join(",")));}}catch(lt){It.e(lt);}finally{It.f();}})(c,s,a),c.join(`
`)};}},u={},g=(function b(p){var T=u[p];if(T!==void 0)return T.exports;var A=u[p]={exports:{}};return i[p].call(A.exports,A,A.exports,b),A.exports})(73);return g})()));})(ce)),ce.exports}var er=tr();function Jt(t,e){const i=er.parse(t);if(i.isMasterPlaylist)return {isMaster:true,variants:nr(i,e)};const u=i,g=rr(u,e);return {isMaster:false,segments:g.segs,mediaSeq:g.mediaSeq,endList:g.endList,targetDuration:u.targetDuration}}function nr(t,e){const i=[];for(const u of t.variants){if(!u.uri)continue;const g=u.resolution,b=g?.width??null,p=g?.height??null;i.push({url:Wt(u.uri,e),res:b&&p?`${b}x${p}`:null,w:b,h:p,peak:u.bandwidth??null,avg:u.averageBandwidth??null,codecs:u.codecs??null});}return i}function Ge(t,e){if(!t||typeof t.length!="number")return {header:null,next:e};const i=typeof t.offset=="number"?t.offset:e,u=i+t.length-1;return {header:`bytes=${i}-${u}`,next:u+1}}function rr(t,e){const i=[];let u=0,g=null;for(let b=0;b<t.segments.length;b++){const p=t.segments[b];let T=null;if(p.byterange){const G=Ge(p.byterange,u);T=G.header,u=G.next;}else u=0;let A=null,x=false;if(p.map?.uri){const G=Wt(p.map.uri,e);let B=null;p.map.byterange&&(B=Ge(p.map.byterange,0).header),A={uri:G,rangeHeader:B};const v=`${G}|${B||""}`;x=v!==g,x&&(g=v);}let Y=null;p.key?.method&&p.key.method!=="NONE"&&(Y={method:String(p.key.method).toUpperCase(),uri:p.key.uri?Wt(p.key.uri,e):null,iv:p.key.iv?.toString()??null}),i.push({uri:Wt(p.uri,e),dur:p.duration||0,range:T,key:Y,map:A,needMap:x});}return {segs:i,mediaSeq:t.mediaSequenceBase||0,endList:t.endlist??false}}function nn(t){let e=true,i=0;const u=new Set;for(const g of t.segs){if(g.range){const b=pe(g.range);!b||b.end==null?e=false:i+=b.end-b.start+1;}else e=false;if(g.needMap&&g.map)if(g.map.rangeHeader){const b=`${g.map.uri}|${g.map.rangeHeader}`;if(!u.has(b)){u.add(b);const p=pe(g.map.rangeHeader);!p||p.end==null?e=false:i+=p.end-p.start+1;}}else e=false;}return e?i:null}function ir(t,e,i){const u=t.endList,g=nn(t);if(g!=null)return {bytes:g,seconds:e,vod:u,via:"byterange"};const b=i?.avg??i?.peak??null;return u&&b&&e>0?{bytes:Math.round(b/8*e),seconds:e,vod:u,via:"avg-bw"}:{bytes:null,seconds:e,vod:u,via:"unknown"}}function rn(t){return t.reduce((e,i)=>e+i.dur,0)}function an(t){return t.length===0?false:t.some(e=>e.map)||/\.m4s(\?|$)/i.test(t[0].uri)}function ar(t){return t.some(e=>e.key?.method==="AES-128")}const te=new Set;let ue=false,de=null,on=()=>{},sn=()=>{};function or(t){on=t;}function sr(t){sn=t;}async function lr(t){const e=await Qt(t.url),i=Jt(e,t.url);if(i.isMaster&&i.variants){const g=$e(i.variants)[0],b=i.variants.length,T=[`${b} ${b===1?"quality":"qualities"}`];g?.res?T.push(`up to ${g.res}`):g?.h&&T.push(`up to ${g.h}p`),t.label=T.join(" • "),t.hlsType="master",t.variantCount=b,t.variants=i.variants,t.bestVariant=g;}else if(i.segments&&i.segments.length>0){const u=i.segments,g=u.length,b=rn(u),p=i.endList??false,T=nn({segs:u,mediaSeq:i.mediaSeq??0}),A=ze(t.url),x=an(u),Y=ar(u);t.label=We({resolution:A,duration:b,size:T}),t.sublabel=Cn(g,x),t.hlsType="media",t.duration=b,t.segCount=g,t.resolution=A,t.isVod=p,t.isFmp4=x,t.encrypted=Y,t.isLive=!p,T!=null&&(t.size=T);}else t.label="Empty or Invalid",t.hlsType="invalid";t.enriched=true;}async function ln(t){if(!t||t.enriched||t.enriching)return false;t.enriching=true;const e=new Promise((i,u)=>setTimeout(()=>u(new Error("Timeout")),tt.ENRICH_TIMEOUT));try{return t._enrichPromise=Promise.race([lr(t),e]),await t._enrichPromise,!0}catch(i){const u=i;return console.error("[SG] enrichItem error:",u),t.label=u.message==="Timeout"?"Timeout":"Parse Error",t.hlsType="error",t.enriched=true,false}finally{t.enriching=false,t._enrichPromise=null;}}async function cr(){if(!ue){ue=true;try{for(;te.size>0;){const t=te.values().next().value;if(t===void 0)break;te.delete(t);const e=sn(t);e&&e.kind==="hls"&&!e.enriched&&(await ln(e),on());}}finally{ue=false;}}}function cn(t){te.add(t),de&&clearTimeout(de),de=setTimeout(cr,tt.ENRICH_DELAY);}async function ur(t){return t._enrichPromise?(await t._enrichPromise,t.enriched&&t.hlsType!=="error"&&t.hlsType!=="invalid"):ln(t)}const Be=new Map,dr=new Map;let un=()=>{},dn=()=>{},pn=()=>{},fn=()=>{},mn=()=>{},hn=()=>{};function pr(t){t.onRemoteItem&&(un=t.onRemoteItem),t.onProgressStart&&(dn=t.onProgressStart),t.onProgressUpdate&&(pn=t.onProgressUpdate),t.onProgressDone&&(fn=t.onProgressDone),t.onPick&&(mn=t.onPick),t.onDownloadCommand&&(hn=t.onDownloadCommand);}const fr={SG_DETECT:(t,e)=>{if(!t.item)return;const i=t.item;i.remoteWin=e,i.isRemote=true,console.log("[SG] Received detection from iframe:",i.kind,i.url.slice(0,60)),it.addItem(i)&&(un(i),i.kind==="hls"&&cn(i.url));},SG_PROGRESS_START:(t,e)=>{const{id:i,title:u,src:g}=t.payload;dn(i,u,g,e);},SG_PROGRESS_UPDATE:t=>{const{id:e,p:i,txt:u}=t.payload;pn(e,i,u);},SG_PROGRESS_DONE:t=>{const{id:e,ok:i,msg:u}=t.payload;fn(e,i,u);},SG_CMD_PICK:(t,e)=>{const{id:i,items:u,title:g}=t.payload;mn(i,u,g,e);}},mr={SG_CMD_DOWNLOAD:t=>{const{url:e,kind:i,variant:u}=t.payload;console.log("[SG] [iframe] Received download command:",{url:e,kind:i}),hn(e,i,u);},SG_CMD_PICK_RESULT:t=>{const{id:e,item:i}=t.payload,u=Be.get(e);u&&(Be.delete(e),u(i));},SG_CMD_CONTROL:t=>{const{id:e,action:i}=t.payload,u=dr.get(e+"_ctrl");u&&(i==="cancel"&&u.onCancel?.(),i==="stop"&&u.onStop?.());}};function hr(t){const e=t.data;if(!e||typeof e!="object"||!e.type||t.source===window)return;let i;tt.IS_TOP?i=fr[e.type]:i=mr[e.type],i&&i(e,t.source);}function gr(t){try{window.top?.postMessage(t,"*");}catch(e){console.error("[SG] Failed to post to top:",e);}}function vr(t){gr({type:"SG_DETECT",item:kn(t)});}let Fe=false;function Tr(){Fe||(Fe=true,window.addEventListener("message",hr),console.log("[SG] Messaging initialized",{isTop:tt.IS_TOP}));}function Er(t){const e=(t||"").replace(/^0x/i,"").replace(/[^0-9a-f]/gi,"");if(e.length===0)return new Uint8Array(0);const u=(e.length%2===0?e:"0"+e).match(/.{1,2}/g);return u?new Uint8Array(u.map(g=>parseInt(g,16))):new Uint8Array(0)}function yr(t){let e=BigInt(t>>>0);const i=new Uint8Array(16);for(let u=15;u>=0;u--)i[u]=Number(e&0xffn),e>>=8n;return i}async function br(t,e,i){const u=await crypto.subtle.importKey("raw",e,{name:"AES-CBC"},false,["decrypt"]);return crypto.subtle.decrypt({name:"AES-CBC",iv:i},u,t)}async function Ir(t,e){if(typeof window.showSaveFilePicker!="function")return null;try{const i=t.split(".").pop()||"mp4",g=await(await window.showSaveFilePicker({suggestedName:t,types:[{description:"Video file",accept:{[e]:[`.${i}`]}}]})).createWritable();let b=!1,p=!1;return {async write(T){if(!(b||p))try{await g.write(T);}catch(A){throw console.error("[SG] Native write error:",A),A}},async close(){if(!(b||p)){b=!0;try{await g.close(),be(t);}catch(T){throw console.error("[SG] Native close error:",T),new Error(`Failed to save file: ${T.message}`)}}},abort(){if(!(b||p)){p=!0;try{g.abort();}catch{}}}}}catch(i){const u=i;if(u.name==="AbortError")throw i;return console.warn("[SG] File System Access API failed, using fallback:",u.message),null}}function Sr(t,e){const i=[];let u=0,g=false,b=false;return {async write(p){g||b||(i.push(p),u+=p.length,u>500*1024*1024&&i.length%100===0&&console.warn(`[SG] Large download in memory: ${Math.round(u/1024/1024)}MB`));},async close(){if(g||b)return;if(g=true,i.length===0)throw new Error("No data to save");const p=new Blob(i,{type:e}),T=URL.createObjectURL(p);return console.log(`[SG] Saving blob: ${t}, size: ${p.size} bytes`),new Promise((A,x)=>{const Y=()=>{setTimeout(()=>URL.revokeObjectURL(T),1e3);};GM_download({url:T,name:t,saveAs:true,onload:()=>{Y(),be(t),A();},onerror:G=>{Y();const B=G?.error||"unknown",v=G?.details||"";console.error("[SG] GM_download error:",{error:B,details:v});let N;switch(B){case "not_enabled":N="Downloads are disabled in userscript settings";break;case "not_whitelisted":N="URL not whitelisted for download. Check userscript settings.";break;case "not_permitted":N="Download not permitted. Try allowing downloads in browser settings.";break;case "not_supported":N="Download not supported by your userscript manager";break;case "not_succeeded":N=v||"Download failed. Check if the file location is writable.";break;default:N=`Download failed: ${B}${v?` - ${v}`:""}`;}x(new Error(N));},ontimeout:()=>{Y(),x(new Error("Download timed out"));}});})},abort(){g||b||(b=true,i.length=0);}}}async function Ar(t,e){const i=await Ir(t,e);return i?(console.log("[SG] Using native File System Access API"),i):(console.log("[SG] Using blob fallback for download"),Sr(t,e))}async function wr(t,e,i,u,g){const b=t.segs,p=b.length;console.log("[SG] Starting segment download:",{filename:e,segments:p,srcUrl:u});const T={paused:false,canceled:false,ended:false,done:0,active:0,nextIdx:0,writePtr:0,byteDone:0,avgLen:0},A={attempts:new Uint8Array(p),status:new Int8Array(p)},x=new Map,Y=new Map,G=new Map,B=new Set,v=new Map,N=new Map,w=new Map,m=new Map,y=i?"video/mp4":"video/mp2t";let d;try{d=await Ar(e,y);}catch(P){if(P.name==="AbortError"){g.remove();return}throw P}g.setOnStop(()=>(T.paused=!T.paused,T.paused||bt(),T.paused?"paused":"resumed")),g.setOnCancel(()=>{T.canceled=true,C(),d.abort(),g.remove();});function C(){for(const[,P]of x)try{P.abort();}catch{}x.clear(),Y.clear();}function _(P){B.add(P);}function j(){const P=B.values().next();return P.done?-1:(B.delete(P.value),P.value)}let rt=0;function at(){rt||(rt=requestAnimationFrame(()=>{rt=0;let P=0;Y.forEach(({loaded:I,total:E})=>{E>0?P+=Math.min(1,I/E):T.avgLen>0&&(P+=Math.min(1,I/T.avgLen));});const q=(T.done+P)/p*100;g.update(q,`${T.done}/${p}`);}));}let F=Promise.resolve();function pt(){F=F.then(async()=>{for(;G.has(T.writePtr);){const P=G.get(T.writePtr);G.delete(T.writePtr),await d.write(P),T.writePtr++;}});}async function ot(P){return !P.key||P.key.method!=="AES-128"||!P.key.uri?null:fe(v,N,P.key.uri,async()=>{const q=await oe(P.key.uri);return new Uint8Array(q)},100)}async function Xt(P){if(!P.needMap||!P.map?.uri)return null;const q=`${P.map.uri}|${P.map.rangeHeader||""}`;return fe(w,m,q,async()=>{const I=P.map.rangeHeader?{Range:P.map.rangeHeader}:{},E=await oe(P.map.uri,I);return new Uint8Array(E)},100)}function At(P,q){A.attempts[P]++,A.attempts[P]>tt.RETRIES?(A.status[P]=-1,console.error(`[SG] Segment ${P} failed: ${q}`),Et(P)):(A.status[P]=0,_(P));}function Et(P){A.status[P]===-1&&P===T.writePtr&&!T.ended&&(C(),ut(false));}async function yt(P){const q=b[P];if(A.status[P]=1,T.active++,q.key&&q.key.method&&q.key.method!=="AES-128"){T.active--,A.status[P]=-1,console.error("[SG] Unsupported key method:",q.key.method),Et(P),vt();return}const I=q.range?{Range:q.range}:{},E=oe(q.uri,I,tt.REQUEST_TIMEOUT,s=>{Y.set(P,{loaded:s.loaded,total:s.total}),at();});x.set(P,{abort:()=>E.abort()});try{let s=await E;const a=await ot(q);if(a){const l=q.key.iv?Er(q.key.iv):yr(t.mediaSeq+P);s=await br(s,a,l);}let c=new Uint8Array(s);if(q.needMap){const l=await Xt(q);if(l?.length){const n=new Uint8Array(l.length+c.length);n.set(l,0),n.set(c,l.length),c=n;}}G.set(P,c),Y.delete(P),x.delete(P),A.status[P]=2,T.active--,T.done++,T.byteDone+=c.length,T.avgLen=T.byteDone/Math.max(1,T.done),at(),pt();}catch(s){Y.delete(P),x.delete(P),T.active--,At(P,s.message||"network/decrypt");}finally{bt(),vt();}}function bt(){if(!(T.paused||T.canceled||T.ended))for(;T.active<tt.CONCURRENCY;){let P=j();if(P===-1){for(;T.nextIdx<p&&A.status[T.nextIdx]!==0;)T.nextIdx++;T.nextIdx<p&&(P=T.nextIdx++);}if(P===-1)break;yt(P);}}function vt(){if(!T.ended){if(A.status[T.writePtr]===-1){C(),ut(false);return}if(T.done===p){ut(true);return}if(!T.active){for(let P=0;P<A.status.length;P++)if(A.status[P]===-1){ut(false);return}}}}async function ut(P){if(!T.ended){T.ended=true;try{pt(),await F,P?(await d.close(),g.update(100,""),g.done(!0)):(d.abort(),g.done(!1,"Failed"));}catch(q){console.error("[SG] finalize error:",q),g.done(false);}finally{C();}}}bt();}async function ve(t,e){console.log("[SG] Direct download:",t);const i=ct.get(t),u=qe(t,i?.type),g=`${Ke(document.title)}.${u}`;let b=t,p=()=>{};i?.blob&&(b=URL.createObjectURL(i.blob),p=()=>URL.revokeObjectURL(b));const T=e.createCard(g,t);T.setOnCancel(()=>{p(),T.remove();}),GM_download({url:b,name:g,saveAs:true,onprogress:A=>{A.lengthComputable?T.update(A.loaded/A.total*100,`${jt(A.loaded)}/${jt(A.total)}`):T.update(0,jt(A.loaded));},onload:()=>{T.update(100,""),T.done(true),p(),be(g);},onerror:A=>{const x=A?.error||"unknown";console.error("[SG] Download error:",{error:x,url:t}),T.done(false,x==="not_succeeded"?"Save failed":x),p();},ontimeout:()=>{T.done(false,"Timeout"),p();}});}async function ee(t,e,i){console.log("[SG] HLS download:",t);const u=await Qt(t),g=Jt(u,t);let b=t,p=e;if(g.isMaster&&g.variants&&g.variants.length>0){const m=$e(g.variants);if(m.length===0)throw new Error("No variants found");const y=[];for(const C of m){let _=null,j=0;try{const at=await Qt(C.url),F=Jt(at,C.url);F.segments&&(j=rn(F.segments),_=ir({segs:F.segments,mediaSeq:F.mediaSeq??0,endList:F.endList??!1},j,C).bytes);}catch{}const rt=We({resolution:C.res,bitrate:C.avg||C.peak,duration:j,size:_});y.push({url:C.url,kind:"variant",label:rt,sublabel:null,size:_,type:null,origin:document.location.origin,enriched:true,enriching:false,hlsType:"media",isLive:false,encrypted:false,variant:C});}const d=await i.pickVariant(y);if(!d)return;p=d.variant??null,b=d.url;}const T=await Qt(b),A=Jt(T,b);if(!A.segments||A.segments.length===0)throw new Error("Invalid playlist: no segments");const x={segs:A.segments,mediaSeq:A.mediaSeq??0,endList:A.endList??false},Y=an(x.segs),G=Y?"mp4":"ts",B=Ke(document.title),v=p?.res?`_${p.res}`:"",N=`${B}${v}.${G}`,w=i.createCard(N,t,x.segs.length);await wr(x,N,Y,t,w);}async function Nr(t,e){if(t.isRemote&&t.remoteWin){if(t.remoteWin.closed)throw new Error("Source frame is gone");if(!t.url.startsWith("blob:")){if(t.kind==="hls")return ee(t.url,null,e);if(t.kind==="video")return ve(t.url,e)}t.remoteWin.postMessage({type:"SG_CMD_DOWNLOAD",payload:{url:t.url,kind:t.kind,variant:t.variant}},"*");return}if(t.kind==="hls"&&!t.enriched){e.setBusy(true);try{t._enrichPromise?await t._enrichPromise:await ur(t);}catch(i){throw new Error(`Failed to analyze stream: ${i.message}`)}finally{e.setBusy(false);}if(t.hlsType==="error"||t.hlsType==="invalid")throw new Error("Cannot download: Stream analysis failed or invalid")}if(t.kind==="video")return ve(t.url,e);if(t.kind==="variant")return ee(t.url,t.variant??null,e);if(t.kind==="hls")return ee(t.url,null,e)}const Rr='@import"https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600;700&family=Urbanist:wght@300;400;500;600;700&display=swap";#sg-fab-container,#sg-modal-container,#sg-toast-container{font-family:Urbanist,system-ui,-apple-system,sans-serif!important;font-size:14px!important;line-height:1.5!important;box-sizing:border-box!important;letter-spacing:.02em!important}#sg-fab-container *,#sg-modal-container *,#sg-toast-container *{box-sizing:border-box!important;outline:none!important}:host{--sg-bg-deep: #050505;--sg-bg-surface: #0a0a0a;--sg-bg-glass: rgba(10, 10, 10, .7);--sg-gold-dim: #8a7e58;--sg-gold: #D4AF37;--sg-gold-bright: #f4d060;--sg-gold-glow: rgba(212, 175, 55, .3);--sg-border-subtle: rgba(255, 255, 255, .08);--sg-border-gold: rgba(212, 175, 55, .25);--sg-text-main: #f0f0f0;--sg-text-muted: #888888;--sg-text-gold: #e5c55d;--sg-success: #10b981;--sg-error: #ef4444;--sg-warn: #f59e0b;--sg-radius-lg: 16px;--sg-radius-md: 10px;--sg-radius-sm: 6px;--sg-shadow-glow: 0 0 20px var(--sg-gold-glow);--sg-glass-blur: blur(16px);--sg-font-display: "Cinzel", serif;--sg-font-body: "Urbanist", sans-serif;--sg-transition: all .3s cubic-bezier(.25, .8, .25, 1)}@keyframes sg-spin{to{transform:rotate(360deg)}}@keyframes sg-breathe{0%,to{box-shadow:0 0 10px var(--sg-gold-glow);border-color:var(--sg-gold)}50%{box-shadow:0 0 25px var(--sg-gold-glow);border-color:var(--sg-gold-bright)}}@keyframes sg-fade-up{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes sg-scale-in{0%{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}.sg-fab{all:initial!important;position:fixed!important;right:30px!important;bottom:30px!important;z-index:2147483647!important;width:60px!important;height:60px!important;border-radius:20px!important;padding:0!important;display:none!important;align-items:center!important;justify-content:center!important;background:linear-gradient(145deg,#151515,#000)!important;color:var(--sg-gold)!important;border:1px solid var(--sg-border-gold)!important;border-top:1px solid var(--sg-border-subtle)!important;cursor:pointer!important;font-family:var(--sg-font-body)!important;box-shadow:0 10px 30px #00000080,0 0 0 1px #00000080!important;transition:var(--sg-transition)!important}.sg-fab.show{display:flex!important;animation:sg-scale-in .4s ease-out backwards!important}.sg-fab:hover{transform:translateY(-2px) scale(1.05)!important;box-shadow:0 15px 40px #0009,var(--sg-shadow-glow)!important;border-color:var(--sg-gold-bright)!important;color:var(--sg-gold-bright)!important}.sg-fab:active{transform:translateY(0) scale(.95)!important}.sg-fab.busy{pointer-events:none!important;animation:sg-breathe 2s infinite!important}.sg-fab.busy>.sg-fab-icon{opacity:0!important}.sg-fab.busy:after{content:""!important;position:absolute!important;inset:0!important;margin:auto!important;width:24px!important;height:24px!important;border:2px solid transparent!important;border-top-color:var(--sg-gold)!important;border-right-color:var(--sg-gold)!important;border-radius:50%!important;animation:sg-spin .8s linear infinite!important}.sg-fab-icon{all:initial!important;display:flex!important;align-items:center!important;justify-content:center!important;color:inherit!important;font-size:0!important}.sg-fab svg{width:26px!important;height:26px!important;fill:none!important;stroke:currentColor!important;stroke-width:2!important;filter:drop-shadow(0 0 2px rgba(212,175,55,.5))!important}.sg-badge{all:initial!important;position:absolute!important;top:-6px!important;right:-6px!important;background:var(--sg-gold)!important;color:#000!important;font-weight:700!important;font-size:11px!important;font-family:var(--sg-font-body)!important;padding:2px 7px!important;border-radius:10px!important;display:none!important;border:2px solid #000!important;min-width:22px!important;text-align:center!important;box-shadow:0 4px 8px #00000080!important}.sg-badge.show{display:inline-block!important;animation:sg-scale-in .3s cubic-bezier(.18,.89,.32,1.28)!important}.sg-modal{all:initial!important;position:fixed!important;inset:0!important;z-index:2147483647!important;display:none!important;align-items:center!important;justify-content:center!important;background:#0009!important;backdrop-filter:blur(8px)!important;font-family:var(--sg-font-body)!important;opacity:0!important;transition:opacity .3s ease!important}.sg-modal.show{display:flex!important;opacity:1!important}.sg-card{all:initial!important;display:flex!important;flex-direction:column!important;background:#0a0a0ad9!important;backdrop-filter:var(--sg-glass-blur) saturate(180%)!important;-webkit-backdrop-filter:var(--sg-glass-blur) saturate(180%)!important;border:1px solid var(--sg-border-gold)!important;border-radius:var(--sg-radius-lg)!important;color:var(--sg-text-main)!important;width:min(580px,94vw)!important;max-height:85vh!important;overflow:hidden!important;box-shadow:0 20px 50px #000000b3,0 0 0 1px #ffffff0d!important;font-family:var(--sg-font-body)!important;transform:translateY(20px)!important;transition:transform .4s cubic-bezier(.19,1,.22,1)!important}.sg-modal.show .sg-card{transform:translateY(0)!important}.sg-card-head{all:initial!important;display:grid!important;grid-template-columns:1fr auto!important;align-items:center!important;padding:24px 28px 20px!important;border-bottom:1px solid var(--sg-border-subtle)!important;background:linear-gradient(to bottom,rgba(255,255,255,.03),transparent)!important;font-family:var(--sg-font-body)!important;position:relative!important}.sg-card-head:after{content:""!important;position:absolute!important;bottom:0!important;left:28px!important;width:40px!important;height:2px!important;background:var(--sg-gold)!important;box-shadow:0 0 8px var(--sg-gold)!important}.sg-card-title{all:initial!important;font-family:var(--sg-font-display)!important;font-size:20px!important;letter-spacing:.05em!important;font-weight:600!important;color:var(--sg-text-gold)!important;text-transform:uppercase!important;text-shadow:0 2px 10px rgba(0,0,0,.5)!important}.sg-card-body{all:initial!important;display:flex!important;flex-direction:column!important;gap:16px!important;padding:24px 28px 28px!important;overflow-y:auto!important;max-height:calc(85vh - 80px)!important;font-family:var(--sg-font-body)!important;background-image:radial-gradient(circle at 100% 0%,rgba(212,175,55,.03) 0%,transparent 25%),radial-gradient(circle at 0% 100%,rgba(212,175,55,.02) 0%,transparent 20%)!important}.sg-card-body::-webkit-scrollbar{width:6px!important}.sg-card-body::-webkit-scrollbar-thumb{background:#ffffff1a!important;border-radius:3px!important}.sg-card-body::-webkit-scrollbar-thumb:hover{background:var(--sg-gold-dim)!important}.sg-btn{all:initial!important;display:flex!important;align-items:center!important;justify-content:center!important;background:#ffffff08!important;border:1px solid var(--sg-border-subtle)!important;color:var(--sg-text-muted)!important;border-radius:var(--sg-radius-sm)!important;padding:8px!important;cursor:pointer!important;min-width:36px!important;min-height:36px!important;transition:var(--sg-transition)!important;font-family:var(--sg-font-body)!important}.sg-btn:hover{background:#ffffff14!important;color:var(--sg-text-main)!important;border-color:#fff3!important;transform:translateY(-1px)!important}.sg-btn svg{width:18px!important;height:18px!important;fill:none!important;stroke:currentColor!important}.sg-btn-small{padding:6px!important;min-width:28px!important;min-height:28px!important}.sg-btn-small svg{width:14px!important;height:14px!important}.sg-option{all:initial!important;display:flex!important;align-items:center!important;gap:12px!important;font-size:14px!important;color:var(--sg-text-muted)!important;padding:14px 18px!important;background:#0003!important;border:1px solid var(--sg-border-subtle)!important;border-radius:var(--sg-radius-md)!important;cursor:pointer!important;font-family:var(--sg-font-body)!important;transition:var(--sg-transition)!important}.sg-option:hover{background:#ffffff08!important;border-color:#ffffff26!important;color:var(--sg-text-main)!important}.sg-option input[type=checkbox]{width:18px!important;height:18px!important;cursor:pointer!important;accent-color:var(--sg-gold)!important;margin:0!important;filter:sepia(100%) hue-rotate(5deg) brightness(.9) saturate(1.5)!important}.sg-list{all:initial!important;display:flex!important;flex-direction:column!important;gap:12px!important;font-family:var(--sg-font-body)!important}.sg-item{all:initial!important;display:block!important;background:linear-gradient(90deg,#ffffff05,#fff0)!important;border:1px solid var(--sg-border-subtle)!important;border-left:2px solid transparent!important;border-radius:var(--sg-radius-md)!important;padding:16px 20px!important;cursor:pointer!important;transition:var(--sg-transition)!important;font-family:var(--sg-font-body)!important;animation:sg-fade-up .5s ease-out backwards!important}.sg-item:nth-child(1){animation-delay:.05s!important}.sg-item:nth-child(2){animation-delay:.1s!important}.sg-item:nth-child(3){animation-delay:.15s!important}.sg-item:nth-child(4){animation-delay:.2s!important}.sg-item:hover{background:#ffffff0a!important;border-color:#ffffff1a!important;border-left-color:var(--sg-gold)!important;transform:translate(4px)!important;box-shadow:0 4px 20px #0000004d!important}.sg-item:focus{outline:1px solid var(--sg-gold)!important}.sg-item-top{all:initial!important;display:flex!important;align-items:flex-start!important;justify-content:space-between!important;gap:14px!important;margin-bottom:8px!important;font-family:var(--sg-font-body)!important}.sg-item-title{all:initial!important;display:flex!important;align-items:center!important;flex-wrap:wrap!important;gap:10px!important;font-weight:600!important;font-size:15px!important;color:var(--sg-text-main)!important;line-height:1.4!important;flex:1!important;font-family:var(--sg-font-body)!important}.sg-item-url{all:initial!important;display:block!important;font-size:12px!important;color:#555!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important;font-family:Consolas,Monaco,monospace!important;opacity:.6!important}.sg-item-sub{all:initial!important;display:flex!important;align-items:center!important;gap:10px!important;font-size:12px!important;color:var(--sg-text-muted)!important;margin-bottom:6px!important;font-family:var(--sg-font-body)!important}.sg-item-size{color:var(--sg-gold-dim)!important}.sg-badge-type{all:initial!important;display:inline-flex!important;align-items:center!important;font-size:10px!important;padding:4px 8px!important;border-radius:4px!important;font-weight:700!important;text-transform:uppercase!important;letter-spacing:.5px!important;white-space:nowrap!important;font-family:var(--sg-font-body)!important;border:1px solid transparent!important;background:#ffffff0d!important;color:#fff!important}.sg-badge-type.master{border-color:#6366f166!important;color:#a5b4fc!important;background:#6366f11a!important}.sg-badge-type.video{border-color:#10b98166!important;color:#6ee7b7!important;background:#10b9811a!important}.sg-badge-type.direct{background:#f59e0b!important;color:#fff!important}.sg-badge-type.live{background:#ef4444!important;color:#fff!important}.sg-badge-type.encrypted{background:#8b5cf6!important;color:#fff!important}.sg-badge-type.analyzing{background:#6b7280!important;color:#fff!important;animation:sg-pulse 1s infinite!important}.sg-badge-type.remote{background:#06b6d4!important;color:#fff!important}.sg-badge-type.error{background:#e74c3c!important;color:#fff!important}.sg-copy-btn{all:initial!important;display:flex!important;align-items:center!important;justify-content:center!important;background:transparent!important;border:1px solid var(--sg-border-subtle)!important;color:var(--sg-gold)!important;border-radius:6px!important;padding:8px!important;cursor:pointer!important;flex-shrink:0!important;transition:var(--sg-transition)!important;font-family:var(--sg-font-body)!important}.sg-copy-btn:hover{border-color:var(--sg-gold-dim)!important;color:var(--sg-gold)!important;background:#d4af370d!important}.sg-copy-btn.copied{border-color:var(--sg-success)!important;color:var(--sg-success)!important}.sg-empty{all:initial!important;display:flex!important;flex-direction:column!important;align-items:center!important;padding:60px 40px!important;color:var(--sg-text-muted)!important;font-size:15px!important;text-align:center!important;line-height:1.6!important;font-family:var(--sg-font-body)!important;border:1px dashed var(--sg-border-subtle)!important;border-radius:var(--sg-radius-md)!important}.sg-empty small{display:block!important;margin-top:12px!important;font-size:13px!important;color:#555!important;font-style:italic!important}.sg-toast{all:initial!important;position:fixed!important;right:30px!important;bottom:110px!important;z-index:2147483648!important;display:flex!important;flex-direction:column!important;gap:16px!important;max-width:400px!important;max-height:70vh!important;overflow-y:auto!important;align-items:flex-end!important;font-family:var(--sg-font-body)!important;pointer-events:none!important}.sg-toast>*{pointer-events:auto!important}.sg-progress{all:initial!important;display:flex!important;flex-direction:column!important;background:#0f0f0ff2!important;backdrop-filter:blur(10px)!important;color:var(--sg-text-main)!important;border:1px solid var(--sg-border-gold)!important;border-left:3px solid var(--sg-gold)!important;border-radius:var(--sg-radius-md)!important;padding:16px 20px!important;min-width:340px!important;box-shadow:0 10px 40px #0009!important;font-family:var(--sg-font-body)!important;animation:sg-fade-up .4s cubic-bezier(.18,.89,.32,1.28)!important}.sg-progress-row{all:initial!important;display:flex!important;align-items:center!important;justify-content:space-between!important;gap:12px!important;margin-bottom:12px!important;font-family:var(--sg-font-body)!important}.sg-progress-name{all:initial!important;font-weight:600!important;font-size:14px!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important;max-width:220px!important;color:var(--sg-text-main)!important;font-family:var(--sg-font-body)!important;letter-spacing:.01em!important}.sg-progress-ctrls{all:initial!important;display:flex!important;gap:6px!important;margin-left:auto!important;font-family:system-ui,sans-serif!important}.sg-progress-bar{all:initial!important;display:block!important;height:6px!important;background:#ffffff1a!important;border-radius:3px!important;overflow:hidden!important;margin-bottom:12px!important}.sg-progress-fill{all:initial!important;display:block!important;height:100%!important;width:0!important;background-color:var(--sg-gold)!important;background:linear-gradient(90deg,var(--sg-gold),var(--sg-gold-bright))!important;box-shadow:0 0 10px var(--sg-gold-glow)!important;transition:width .2s linear!important}.sg-progress-status{all:initial!important;display:flex!important;justify-content:space-between!important;font-size:12px!important;font-family:var(--sg-font-body)!important}.sg-progress-status span:first-child{color:var(--sg-text-muted)!important;font-variant-numeric:tabular-nums!important}.sg-progress-status span:last-child{color:#e0e0e0!important}.sg-progress.paused .sg-progress-fill{background:#f59e0b!important}.sg-progress.minimized{padding:10px 14px!important;min-width:auto!important;background:#000!important;border-left-width:1px!important}.sg-progress.minimized .sg-progress-bar,.sg-progress.minimized .sg-progress-status,.sg-progress.minimized .sg-progress-name{display:none!important}.sg-progress.minimized .sg-progress-row{margin-bottom:0!important;justify-content:center!important}.sg-progress.minimized .sg-progress-ctrls{margin:0!important;gap:0!important}.sg-progress.minimized .sg-progress-ctrls>*:not(.btn-minimize){display:none!important}@media(max-width:640px){.sg-fab{right:20px!important;bottom:20px!important}.sg-toast{left:16px!important;right:16px!important;bottom:80px!important;max-width:none!important;align-items:stretch!important}.sg-progress{min-width:0!important;width:100%!important}.sg-card{max-height:90vh!important;width:100%!important;margin:8px!important;border-radius:10px!important}.sg-card-body{max-height:calc(90vh - 70px)!important}}',Or=Rr,gt={download:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
<path d="M7 10l5 5 5-5"/>
<path d="M12 15V3"/>
</svg>`,close:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>`,copy:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="9" width="13" height="13" rx="2"/>
<path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>
</svg>`,check:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M20 6L9 17l-5-5"/>
</svg>`,pause:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="6" y="4" width="4" height="16"/>
<rect x="14" y="4" width="4" height="16"/>
</svg>`,play:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polygon points="5 3 19 12 5 21 5 3"/>
</svg>`,cancel:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<path d="M15 9l-6 6M9 9l6 6"/>
</svg>`,minimize:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M19 9l-7 7-7-7"/>
</svg>`,maximize:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M5 15l7-7 7 7"/>
</svg>`},Te=(...t)=>t.filter(Boolean).join(" ");function H(t,e,i){const u=document.createElement(t);if(e)for(const[g,b]of Object.entries(e))b==null||b===false||u.setAttribute(g,b===true?"":String(b));if(i)if(typeof i=="string")u.innerHTML=i;else for(const g of i)u.append(typeof g=="string"?document.createTextNode(g):g);return u}async function Lr(t,e){try{await navigator.clipboard.writeText(t);}catch{const u=Object.assign(document.createElement("textarea"),{value:t,style:"position:fixed;opacity:0;pointer-events:none"}),g=e.getRootNode();(g instanceof ShadowRoot||g instanceof Document?g:document.body).appendChild(u),u.select();const p=document.execCommand("copy");if(u.remove(),!p)return false}const i=e.innerHTML;return e.innerHTML=gt.check,e.classList.add("copied"),setTimeout(()=>{e.innerHTML=i,e.classList.remove("copied");},1200),true}let Ot=null,je=null,Bt=null;function Pr(t,e,i){Ot||(Ot=H("button",{class:"sg-fab",type:"button"}),je=H("span",{class:"sg-fab-icon"},gt.download),Bt=H("span",{class:"sg-badge"}),Ot.append(je,Bt),Ot.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),i();}),t.appendChild(Ot)),Ot.className=Te("sg-fab",e.show&&"show",e.busy&&"busy",e.idle&&"idle"),Ot.disabled=e.busy,Ot.title=`Download media (${e.count})`,Bt&&(Bt.className=Te("sg-badge",e.count>0&&"show"),Bt.textContent=e.count>99?"99+":String(e.count));}function Xr(t,e,i,u,g,b,p,T,A){if(t.innerHTML="",!e)return;const x=H("div",{class:"sg-modal show"});x.addEventListener("click",N=>N.target===x&&p());const Y=H("div",{class:"sg-card",role:"dialog","aria-modal":"true"}),G=H("div",{class:"sg-card-head"});G.append(Object.assign(H("div",{class:"sg-card-title"}),{textContent:i}),Dr(gt.close,"Close (Esc)",p)),Y.appendChild(G);const B=H("div",{class:"sg-card-body"});if(g&&u.some(N=>N.size!=null)){const N=H("label",{class:"sg-option"}),w=H("input",{type:"checkbox",checked:b||null});w.addEventListener("change",()=>A(w.checked)),N.append(w," Exclude small (< 1MB)"),B.appendChild(N);}const v=H("div",{class:"sg-list"});if(u.length===0){const N=H("div",{class:"sg-empty"});N.innerHTML="No media detected.<br><small>Play a video to detect streams.</small>",v.appendChild(N);}else u.forEach(N=>v.appendChild(Cr(N,T)));B.appendChild(v),Y.appendChild(B),x.appendChild(Y),t.appendChild(x);}function Dr(t,e,i){const u=H("button",{class:"sg-btn",title:e,type:"button"},t);return u.addEventListener("click",g=>{g.preventDefault(),i();}),u}function Cr(t,e){const i=H("div",{class:"sg-item",role:"button",tabindex:"0"}),u=H("div",{class:"sg-item-top"}),g=H("div",{class:"sg-item-title"});g.appendChild(Object.assign(H("span"),{textContent:t.label})),xr(t).forEach(T=>g.appendChild(T)),u.appendChild(g),t.size&&u.appendChild(Object.assign(H("span",{class:"sg-item-size"}),{textContent:jt(t.size)}));const b=H("button",{class:"sg-copy-btn",title:"Copy URL",type:"button"},gt.copy);b.addEventListener("click",T=>{T.stopPropagation(),Lr(t.url,b);}),u.appendChild(b),i.appendChild(u),t.sublabel&&i.appendChild(Object.assign(H("div",{class:"sg-item-sub"}),{textContent:t.sublabel}));const p=H("div",{class:"sg-item-url",title:t.url});return p.textContent=t.url.length>60?t.url.slice(0,60)+"…":t.url,i.appendChild(p),i.addEventListener("click",T=>{T.target.closest(".sg-copy-btn")||e(t);}),i.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),e(t));}),i}function xr(t){const e=[],i=(u,g)=>{const b=H("span",{class:`sg-badge-type ${g}`});b.textContent=u,e.push(b);};return t.kind==="hls"?(t.hlsType==="error"||t.hlsType==="invalid"?i(t.hlsType==="error"?"Error":"Invalid","error"):t.hlsType==="master"?i("Master","master"):t.hlsType==="media"?i("Video","video"):t.enriching?i("...","analyzing"):i("HLS","video"),t.isLive&&i("Live","live"),t.encrypted&&i("🔒","encrypted")):t.kind==="video"?i("Direct","direct"):t.kind==="variant"&&i("Quality","video"),t.isRemote&&i("iFrame","remote"),e}class Mr{constructor(e,i,u,g=0){this.container=e,this.title=i,this.src=u,this.status=g?`${g} segments`:"Starting...",this.el=H("div",{class:"sg-progress",id:`sg-progress-${me()}`});const b=H("div",{class:"sg-progress-row"});b.appendChild(Object.assign(H("div",{class:"sg-progress-name",title:u}),{textContent:i}));const p=H("div",{class:"sg-progress-ctrls"});this.minBtn=H("button",{class:"sg-btn sg-btn-sm btn-minimize",title:"Minimize",type:"button"},gt.minimize),this.minBtn.addEventListener("click",()=>this.toggleMinimize()),p.appendChild(this.minBtn);const T=H("button",{class:"sg-btn sg-btn-sm",title:"Cancel",type:"button"},gt.cancel);T.addEventListener("click",()=>this.onCancelFn?.()),p.appendChild(T),b.appendChild(p),this.el.appendChild(b);const A=H("div",{class:"sg-progress-bar"});this.fillEl=H("div",{class:"sg-progress-fill"}),A.appendChild(this.fillEl),this.el.appendChild(A);const x=H("div",{class:"sg-progress-status"});this.statusEl=H("span"),this.statusEl.textContent=this.status,this.percentEl=H("span"),this.percentEl.textContent="0%",x.append(this.statusEl,this.percentEl),this.el.appendChild(x),e.appendChild(this.el);}el;fillEl;statusEl;percentEl;pauseBtn=null;minBtn;minimized=false;paused=false;percent=0;status;onStop;onCancelFn;toggleMinimize(){this.minimized=!this.minimized,this.minBtn.innerHTML=this.minimized?gt.maximize:gt.minimize,this.minBtn.title=this.minimized?"Expand":"Minimize",this.updateClass();}updateClass(){this.el.className=Te("sg-progress",this.minimized&&"minimized",this.paused&&"paused");}update(e,i=""){this.percent=Math.max(0,Math.min(100,e)),i&&(this.status=i),this.fillEl.style.setProperty("width",`${this.percent}%`,"important"),this.statusEl.textContent=this.status,this.percentEl.textContent=`${Math.floor(this.percent)}%`;}done(e=true,i){this.fillEl.style.width="100%",this.fillEl.classList.add(e?"success":"error"),this.statusEl.textContent=i||(e?"Complete ✓":"Failed ✗"),this.percentEl.textContent="100%",setTimeout(()=>this.remove(),2500);}remove(){this.el.remove();}setOnStop(e){this.onStop=e,!this.pauseBtn&&(this.pauseBtn=H("button",{class:"sg-btn sg-btn-sm",title:"Pause",type:"button"},gt.pause),this.pauseBtn.addEventListener("click",()=>{if(!this.onStop)return;const i=this.onStop();this.paused=i==="paused",this.pauseBtn.innerHTML=this.paused?gt.play:gt.pause,this.pauseBtn.title=this.paused?"Resume":"Pause",this.updateClass();}),this.minBtn.before(this.pauseBtn));}setOnCancel(e){this.onCancelFn=e;}}function Ur(t,e,i,u=0){return new Mr(t,e,i,u)}let ht=false,Lt=null,kt=null,_t=null;const Ct={show:false,busy:false,idle:false,count:0},mt={show:false,title:"Select Media",items:[]};let Ee=null,Pt=null,gn=null,vn=null;function Ie(){if(!tt.IS_TOP||ht)return;if(!document.body){const u=document.readyState==="loading"?"DOMContentLoaded":"load";window.addEventListener(u,()=>Ie(),{once:true});return}const t=document.createElement("div");t.id="sg-host",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"0",height:"0",zIndex:"2147483647",pointerEvents:"none"});const e=t.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Or,e.append(i),Lt=document.createElement("div"),Lt.id="sg-fab-container",Lt.style.pointerEvents="auto",kt=document.createElement("div"),kt.id="sg-modal-container",kt.style.pointerEvents="auto",_t=document.createElement("div"),_t.id="sg-toast-container",_t.className="sg-toast",e.append(Lt,kt,_t),document.documentElement.append(t),Lt.addEventListener("mouseenter",Ae),Lt.addEventListener("mouseleave",Se),document.addEventListener("keydown",u=>u.key==="Escape"&&mt.show&&we()),ht=true,Tt();}function zt(){return tt.IS_TOP?(ht||Ie(),ht):false}function Tt(){if(!ht||!Lt||!kt)return;Pr(Lt,Ct,Tn);const t=mt.show?kr():[];Xr(kt,mt.show,mt.title,t,Pt?.filterable??true,it.excludeSmall,we,Yr,Vr);}function ne(){tt.IS_TOP&&(Ct.show=true,Ct.count=it.validCount,zt()&&(Tt(),Se()));}function ye(t){Ct.busy=t,ht&&Tt();}function Ht(){Ct.count=it.validCount,ht&&Tt();}function Se(){Ae(),Ee=setTimeout(()=>{Ct.idle=true,ht&&Tt();},tt.UI_IDLE_MS);}function Ae(){Ct.idle=false,Ee&&clearTimeout(Ee),ht&&Tt();}function kr(){const t=mt.items.length>0?mt.items:it.getFilteredItems();return it.excludeSmall?t.filter(e=>e.size==null||e.size>=tt.SMALL_BYTES):t}function _r(t="Select Media",e){zt()&&(mt.show=true,mt.title=t,mt.items=e??[],Tt());}function we(){mt.show=false,mt.items=[],ht&&Tt(),Pt&&(Pt.resolve(null),Pt=null);}function Yr(t){we(),Pt?(Pt.resolve(t),Pt=null):vn?.(t);}function Vr(t){it.setExcludeSmall(t),Tt();}function Tn(){ht&&(Ae(),Se(),gn?.());}function Ne(t,{title:e="Select Media",filterable:i=true}={}){return zt()?new Promise(u=>{Pt={resolve:u,title:e,filterable:i},_r(e,t);}):Promise.resolve(null)}function En(t,e,i=0){return !zt()||!_t?{update(){},done(){},remove(){},setOnStop(){},setOnCancel(){}}:Ur(_t,t,e,i)}function Gr(){tt.IS_TOP&&(GM_registerMenuCommand("Show Download Panel",()=>{zt(),ne(),Tn();}),GM_registerMenuCommand("Clear Cache",()=>{it.clear(),Ht(),GM_notification({text:"Cache cleared",title:"StreamGrabber",timeout:2e3});}));}function Br(t){t.onFabClick&&(gn=t.onFabClick),t.onItemSelected&&(vn=t.onItemSelected);}function He(){tt.IS_TOP&&(Ht(),ht&&mt.show&&Tt());}const Ut=new Map;function Fr(){console.log("[SG] StreamGrabber v2.0.0 initializing...",{isTop:tt.IS_TOP,readyState:document.readyState,href:location.href.slice(0,100)}),sr(t=>it.getItem(t)),Br({onFabClick:jr,onItemSelected:yn}),tt.IS_TOP&&(Ie(),Gr()),Tr(),pr({onRemoteItem:()=>{ne(),Ht();},onProgressStart:(t,e,i,u)=>{if(!Ut.has(t))try{const g=En(e,i);g.setOnStop(()=>(u.postMessage({type:"SG_CMD_CONTROL",payload:{id:t,action:"stop"}},"*"),"paused")),g.setOnCancel(()=>{u.postMessage({type:"SG_CMD_CONTROL",payload:{id:t,action:"cancel"}},"*"),g.remove(),Ut.delete(t);}),Ut.set(t,g);}catch(g){console.error("[SG] Failed to create remote progress card:",g);}},onProgressUpdate:(t,e,i)=>{Ut.get(t)?.update(e,i);},onProgressDone:(t,e,i)=>{const u=Ut.get(t);u&&(u.done(e,i),setTimeout(()=>Ut.delete(t),2500));},onPick:(t,e,i,u)=>{Ne(e,{title:i,filterable:true}).then(g=>{u.postMessage({type:"SG_CMD_PICK_RESULT",payload:{id:t,item:g}},"*");});},onDownloadCommand:Hr}),Zn(t=>{tt.IS_TOP?(console.log("[SG] Detected:",t.kind,t.url.slice(0,60)),ne(),Ht(),t.kind==="hls"&&cn(t.url)):(console.log("[SG] [iframe] Forwarding detection:",t.kind,t.url.slice(0,60)),vr(t));}),or(()=>{He();}),it.events.itemAdded.subscribe(()=>{ne(),Ht();}),it.events.updated.subscribe(()=>{He();}),Jn(),console.log("[SG] Initialization complete",{isTop:tt.IS_TOP});}async function jr(){ye(true);try{const t=it.getFilteredItems();if(t.length===0){alert("No media detected yet. Try playing a video first.");return}const e=await Ne(t,{title:"Select Media",filterable:!0});if(!e)return;await yn(e);}catch(t){Qe(t);}finally{ye(false);}}async function yn(t){try{await Nr(t,{createCard:En,pickVariant:e=>Ne(e,{title:"Select Quality",filterable:!0}),setBusy:ye});}catch(e){Qe(e);}}async function Hr(t,e,i){console.log("[SG] [iframe] Received download command:",{url:t,kind:e});try{const u=(g,b)=>{const p=me();return window.top?.postMessage({type:"SG_PROGRESS_START",payload:{id:p,title:g,src:b}},"*"),{update(T,A){window.top?.postMessage({type:"SG_PROGRESS_UPDATE",payload:{id:p,p:T,txt:A||""}},"*");},done(T=!0,A){window.top?.postMessage({type:"SG_PROGRESS_DONE",payload:{id:p,ok:T,msg:A||""}},"*");},remove(){},setOnStop(){},setOnCancel(){}}};e==="hls"?await ee(t,i,{createCard:u,pickVariant:async g=>new Promise(b=>{const p=me(),T=A=>{const x=A.data;x?.type==="SG_CMD_PICK_RESULT"&&x?.payload?.id===p&&(window.removeEventListener("message",T),b(x.payload.item));};window.addEventListener("message",T),window.top?.postMessage({type:"SG_CMD_PICK",payload:{id:p,items:g,title:"Select Quality"}},"*");}),setBusy:()=>{}}):e==="video"&&await ve(t,{createCard:u,pickVariant:async()=>null,setBusy:()=>{}});}catch(u){console.error("[SG] [iframe] Download error:",u);}}Fr();
})();