@oddin-gg/havik-player 2.6.2 → 2.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("hls.js");c=s(c,1);var l=class extends Error{code;httpStatus;retryAfterMs;requestId;serverCode;liveStartsAtMs;constructor(e,t,n,r){super(n),this.name=`PlaybackError`,this.code=e,this.httpStatus=t,this.retryAfterMs=r?.retryAfterMs,this.requestId=r?.requestId,this.serverCode=r?.serverCode,this.liveStartsAtMs=r?.liveStartsAtMs,r?.cause!==void 0&&(this.cause=r.cause)}};function u(e){switch(e){case 400:return`INVALID_URN`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 410:return`GONE`;case 425:return`TOO_EARLY`;case 429:return`RATE_LIMITED`;case 503:return`UNAVAILABLE`;default:return`INTERNAL`}}function d(e){return e===401?`UNAUTHORIZED`:e===403?`FORBIDDEN`:`DRM_CLIENT`}var f=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function p(e){return f.has(e)}async function m(e){let t=typeof e==`function`?await e():e;if(!t||!t.apiKey)throw Error(`havik-player: credential is missing an apiKey`);return t}function h(e,t){let n=e.replace(/\/+$/,``),r;try{r=new URL(n+t)}catch{throw new l(`INTERNAL`,0,`invalid baseUrl: ${JSON.stringify(e)}`)}if(r.protocol!==`https:`&&r.protocol!==`http:`)throw new l(`INTERNAL`,0,`baseUrl must be http(s), got: ${JSON.stringify(e)}`);return r.toString()}function g(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.round(t*1e3));let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}async function _(e,t){let n=await m(t.credential),r=t.headers??new Headers;if(t.apiHeaders)for(let[e,n]of Object.entries(t.apiHeaders))r.has(e)||r.set(e,n);r.set(`x-api-key`,n.apiKey);try{return await fetch(e,{method:t.method??`GET`,headers:r,body:t.body,signal:t.signal,cache:`no-store`,credentials:`omit`,mode:`cors`})}catch(e){throw t.signal?.aborted?new l(`ABORTED`,0,`request aborted`,{cause:e}):new l(`NETWORK`,0,`network request failed: ${ee(e)}`,{cause:e})}}function ee(e){return e instanceof Error?e.message:String(e)}var te=1e3,ne=3e4,re=6e5,ie=3e5,ae=1e3,oe={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function se(e){let t=e===!0||e===!1?{}:e,n=Math.max(ae,t.floorMs??te),r=Math.max(n,t.ceilMs??ne),i=Math.max(0,t.imminentMs??re),a=Math.max(r,t.sanityFloorMs??ie);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:ce(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function ce(e){if(e==null)return;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function le(e,t,n){return Math.min(n,Math.max(t,e))}function ue(e){return Math.round(e*(1+.15*Math.random()))}function de(e,t,n,r){let i=r??n.kickoffMs,a=i==null?void 0:Math.max(0,i-t),o=Math.max(n.floorMs,e??0);if(a==null||a<=n.imminentMs)return{delay:le(e??n.floorMs,o,n.ceilMs),ttkMs:a};let s=Math.min(Math.floor(a/10),n.sanityFloorMs,a);return{delay:Math.max(o,s),ttkMs:a}}function fe(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new l(`ABORTED`,0,`wait-for-live aborted`));return}let i=()=>{clearTimeout(a),r(new l(`ABORTED`,0,`wait-for-live aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function pe(e,t,n){let r=se(t),i=Date.now(),a=r.timeoutMs==null?1/0:i+r.timeoutMs,o=0,s;for(;;){if(n?.aborted)throw new l(`ABORTED`,0,`wait-for-live aborted`);try{return await e()}catch(e){if(!(e instanceof l)||!p(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=de(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=ue(d)),t+d>a)throw new l(`TIMEOUT`,e.httpStatus,`timed out after ${r.timeoutMs}ms waiting for the stream to go live`,{retryAfterMs:e.retryAfterMs,cause:e});r.onState?.({phase:oe[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await fe(d,n)}}}async function v(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new l(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await _(h(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal,apiHeaders:e.apiHeaders});if(!t.ok)throw await me(t);return ge(await t.json(),e.matchUrn)}function y(e){let t=()=>v(e);return e.waitForLive?pe(t,e.waitForLive,e.signal):t()}async function me(e){let t=g(e.headers.get(`retry-after`)),n=e.headers.get(`x-request-id`)??e.headers.get(`x-amzn-requestid`)??void 0,r=e.statusText||`HTTP ${e.status}`,i,a;try{let t=await e.json();if(t?.error?.message&&(r=t.error.message),t?.error?.code&&(i=t.error.code),typeof t?.liveStartsAt==`string`){let e=Date.parse(t.liveStartsAt);Number.isFinite(e)&&(a=e)}}catch{}return new l(u(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:a})}var he=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`,`analytics`]);function b(e,t){let n;try{n=new URL(t)}catch{throw new l(`INTERNAL`,0,`playback ${e} is not a valid URL`)}if(n.protocol!==`https:`&&n.protocol!==`http:`)throw new l(`INTERNAL`,0,`playback ${e} has a disallowed scheme: ${n.protocol}`);return t}function ge(e,t){if(!e.manifestUrl)throw new l(`INTERNAL`,0,`playback response is missing manifestUrl`);let n=e.drmEnabled??!!e.drm,r={matchUrn:e.matchUrn??t,protocol:`hls`,drmEnabled:n,manifestUrl:b(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),typeof e.analytics?.sid==`string`&&e.analytics.sid&&(r.analytics={sid:e.analytics.sid}),n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:b(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:b(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:b(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))he.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}function x(e){return e.ownerDocument??document}function S(e){return e.fullscreenElement??e.webkitFullscreenElement??null}function C(e,t){let n=S(x(e));return n!=null&&(n===e||t!=null&&n===t)||e.webkitDisplayingFullscreen===!0}async function w(e,t){let n=t??e;if(typeof n.requestFullscreen==`function`)return await n.requestFullscreen(),!0;if(typeof n.webkitRequestFullscreen==`function`)return n.webkitRequestFullscreen(),!0;let r=e;return r.webkitSupportsFullscreen&&typeof r.webkitEnterFullscreen==`function`?(r.webkitEnterFullscreen(),!0):!1}async function T(e,t){let n=e;if(n.webkitDisplayingFullscreen){n.webkitExitFullscreen?.();return}let r=x(e),i=S(r);i!=null&&(i===e||t!=null&&i===t)&&(typeof r.exitFullscreen==`function`?await r.exitFullscreen():r.webkitExitFullscreen?.())}async function _e(e){let t=new URLSearchParams;e.status&&t.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e.sport&&t.set(`sport`,e.sport);let n=t.toString(),r=h(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let a=await _(r,{credential:e.credential,signal:e.signal,headers:i,apiHeaders:e.apiHeaders});if(a.status===304)return{tournaments:[],etag:e.etag,notModified:!0};if(!a.ok)throw new l(u(a.status),a.status,`catalog request failed (HTTP ${a.status})`);return{tournaments:ve(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function ve(e){return(e.tournaments??[]).map(e=>{let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:e.status??`upcoming`,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r}))}})}async function ye(e){let t=h(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await _(t,{credential:e.credential,signal:e.signal,headers:n,apiHeaders:e.apiHeaders});if(r.status===304)return{etag:e.etag,notModified:!0,notFound:!1};if(r.status===404)return{notModified:!1,notFound:!0};if(!r.ok)throw new l(u(r.status),r.status,`tournament request failed (HTTP ${r.status})`);return{tournament:be(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function be(e){let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:e.status??`upcoming`,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r}))}}function xe(e){return e.tournaments.flatMap(e=>e.matches)}function Se(e){let t=Math.max(2e3,e.intervalMs??1e4),n=new AbortController,r,i,a,o=!1,s=()=>{o||(r=setTimeout(c,t))},c=async()=>{try{let t=h(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let o=await _(t,{credential:e.credential,signal:n.signal,headers:r,apiHeaders:e.apiHeaders});if(o.status!==304){if(!o.ok)throw new l(u(o.status),o.status,`match status request failed (HTTP ${o.status})`);i=o.headers.get(`etag`)??i;let t=await o.json(),n=t.status??`upcoming`;n!==a&&(a=n,e.onChange({matchUrn:t.matchUrn??e.matchUrn,matchName:t.matchName,status:n,datePlannedStart:t.datePlannedStart}))}}catch(t){n.signal.aborted||e.onError?.(t instanceof l?t:new l(`NETWORK`,0,String(t)))}finally{s()}};return c(),{stop(){o=!0,n.abort(),r&&clearTimeout(r)}}}function E(e){let t=Math.max(250,e.minBackoffMs??1e3),n=Math.max(t,e.maxBackoffMs??15e3),r=new AbortController,i=!1,a=e=>new Promise(t=>{if(r.signal.aborted)return t();let n=setTimeout(t,e);r.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),o=t=>{e.onAlive?.();let n=`message`,r=[];for(let e of t.split(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("hls.js");c=s(c,1);var l=class extends Error{code;httpStatus;retryAfterMs;requestId;serverCode;liveStartsAtMs;constructor(e,t,n,r){super(n),this.name=`PlaybackError`,this.code=e,this.httpStatus=t,this.retryAfterMs=r?.retryAfterMs,this.requestId=r?.requestId,this.serverCode=r?.serverCode,this.liveStartsAtMs=r?.liveStartsAtMs,r?.cause!==void 0&&(this.cause=r.cause)}};function u(e){switch(e){case 400:return`INVALID_URN`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 410:return`GONE`;case 425:return`TOO_EARLY`;case 429:return`RATE_LIMITED`;case 503:return`UNAVAILABLE`;default:return`INTERNAL`}}function d(e){return e===401?`UNAUTHORIZED`:e===403?`FORBIDDEN`:`DRM_CLIENT`}var f=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function p(e){return f.has(e)}async function m(e){let t=typeof e==`function`?await e():e;if(!t||!t.apiKey)throw Error(`havik-player: credential is missing an apiKey`);return t}function h(e,t){let n=e.replace(/\/+$/,``),r;try{r=new URL(n+t)}catch{throw new l(`INTERNAL`,0,`invalid baseUrl: ${JSON.stringify(e)}`)}if(r.protocol!==`https:`&&r.protocol!==`http:`)throw new l(`INTERNAL`,0,`baseUrl must be http(s), got: ${JSON.stringify(e)}`);return r.toString()}function g(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.round(t*1e3));let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}async function _(e,t){let n=await m(t.credential),r=t.headers??new Headers;if(t.apiHeaders)for(let[e,n]of Object.entries(t.apiHeaders))r.has(e)||r.set(e,n);r.set(`x-api-key`,n.apiKey);try{return await fetch(e,{method:t.method??`GET`,headers:r,body:t.body,signal:t.signal,cache:`no-store`,credentials:`omit`,mode:`cors`})}catch(e){throw t.signal?.aborted?new l(`ABORTED`,0,`request aborted`,{cause:e}):new l(`NETWORK`,0,`network request failed: ${ee(e)}`,{cause:e})}}function ee(e){return e instanceof Error?e.message:String(e)}var te=1e3,ne=3e4,re=6e5,ie=3e5,ae=1e3,oe={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function se(e){let t=e===!0||e===!1?{}:e,n=Math.max(ae,t.floorMs??te),r=Math.max(n,t.ceilMs??ne),i=Math.max(0,t.imminentMs??re),a=Math.max(r,t.sanityFloorMs??ie);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:ce(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function ce(e){if(e==null)return;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function le(e,t,n){return Math.min(n,Math.max(t,e))}function ue(e){return Math.round(e*(1+.15*Math.random()))}function de(e,t,n,r){let i=r??n.kickoffMs,a=i==null?void 0:Math.max(0,i-t),o=Math.max(n.floorMs,e??0);if(a==null||a<=n.imminentMs)return{delay:le(e??n.floorMs,o,n.ceilMs),ttkMs:a};let s=Math.min(Math.floor(a/10),n.sanityFloorMs,a);return{delay:Math.max(o,s),ttkMs:a}}function fe(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new l(`ABORTED`,0,`wait-for-live aborted`));return}let i=()=>{clearTimeout(a),r(new l(`ABORTED`,0,`wait-for-live aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function pe(e,t,n){let r=se(t),i=Date.now(),a=r.timeoutMs==null?1/0:i+r.timeoutMs,o=0,s;for(;;){if(n?.aborted)throw new l(`ABORTED`,0,`wait-for-live aborted`);try{return await e()}catch(e){if(!(e instanceof l)||!p(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=de(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=ue(d)),t+d>a)throw new l(`TIMEOUT`,e.httpStatus,`timed out after ${r.timeoutMs}ms waiting for the stream to go live`,{retryAfterMs:e.retryAfterMs,cause:e});r.onState?.({phase:oe[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await fe(d,n)}}}async function v(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new l(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await _(h(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal,apiHeaders:e.apiHeaders});if(!t.ok)throw await me(t);return ge(await t.json(),e.matchUrn)}function y(e){let t=()=>v(e);return e.waitForLive?pe(t,e.waitForLive,e.signal):t()}async function me(e){let t=g(e.headers.get(`retry-after`)),n=e.headers.get(`x-request-id`)??e.headers.get(`x-amzn-requestid`)??void 0,r=e.statusText||`HTTP ${e.status}`,i,a;try{let t=await e.json();if(t?.error?.message&&(r=t.error.message),t?.error?.code&&(i=t.error.code),typeof t?.liveStartsAt==`string`){let e=Date.parse(t.liveStartsAt);Number.isFinite(e)&&(a=e)}}catch{}return new l(u(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:a})}var he=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`,`analytics`]);function b(e,t){let n;try{n=new URL(t)}catch{throw new l(`INTERNAL`,0,`playback ${e} is not a valid URL`)}if(n.protocol!==`https:`&&n.protocol!==`http:`)throw new l(`INTERNAL`,0,`playback ${e} has a disallowed scheme: ${n.protocol}`);return t}function ge(e,t){if(!e.manifestUrl)throw new l(`INTERNAL`,0,`playback response is missing manifestUrl`);let n=e.drmEnabled??!!e.drm,r={matchUrn:e.matchUrn??t,protocol:`hls`,drmEnabled:n,manifestUrl:b(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),typeof e.analytics?.sid==`string`&&e.analytics.sid&&(r.analytics={sid:e.analytics.sid}),n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:b(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:b(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:b(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))he.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}function x(e){return e.ownerDocument??document}function S(e){return e.fullscreenElement??e.webkitFullscreenElement??null}function C(e,t){let n=S(x(e));return n!=null&&(n===e||t!=null&&n===t)||e.webkitDisplayingFullscreen===!0}async function w(e,t){let n=t??e;if(typeof n.requestFullscreen==`function`)return await n.requestFullscreen(),!0;if(typeof n.webkitRequestFullscreen==`function`)return n.webkitRequestFullscreen(),!0;let r=e;return r.webkitSupportsFullscreen&&typeof r.webkitEnterFullscreen==`function`?(r.webkitEnterFullscreen(),!0):!1}async function T(e,t){let n=e;if(n.webkitDisplayingFullscreen){n.webkitExitFullscreen?.();return}let r=x(e),i=S(r);i!=null&&(i===e||t!=null&&i===t)&&(typeof r.exitFullscreen==`function`?await r.exitFullscreen():r.webkitExitFullscreen?.())}async function _e(e){let t=new URLSearchParams;e.status&&t.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e.sport&&t.set(`sport`,e.sport);let n=t.toString(),r=h(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let a=await _(r,{credential:e.credential,signal:e.signal,headers:i,apiHeaders:e.apiHeaders});if(a.status===304)return{tournaments:[],etag:e.etag,notModified:!0};if(!a.ok)throw new l(u(a.status),a.status,`catalog request failed (HTTP ${a.status})`);return{tournaments:ve(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function ve(e){return(e.tournaments??[]).map(e=>{let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:e.status??`upcoming`,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r}))}})}async function ye(e){let t=h(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await _(t,{credential:e.credential,signal:e.signal,headers:n,apiHeaders:e.apiHeaders});if(r.status===304)return{etag:e.etag,notModified:!0,notFound:!1};if(r.status===404)return{notModified:!1,notFound:!0};if(!r.ok)throw new l(u(r.status),r.status,`tournament request failed (HTTP ${r.status})`);return{tournament:be(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function be(e){let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:e.status??`upcoming`,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r}))}}function xe(e){return e.tournaments.flatMap(e=>e.matches)}function Se(e){let t=Math.max(2e3,e.intervalMs??1e4),n=new AbortController,r,i,a,o=!1,s=()=>{o||(r=setTimeout(c,t))},c=async()=>{try{let t=h(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let o=await _(t,{credential:e.credential,signal:n.signal,headers:r,apiHeaders:e.apiHeaders});if(o.status!==304){if(!o.ok)throw new l(u(o.status),o.status,`match status request failed (HTTP ${o.status})`);i=o.headers.get(`etag`)??i;let t=await o.json(),n=t.status??`upcoming`;n!==a&&(a=n,e.onChange({matchUrn:t.matchUrn??e.matchUrn,matchName:t.matchName,status:n,datePlannedStart:t.datePlannedStart}))}}catch(t){n.signal.aborted||e.onError?.(t instanceof l?t:new l(`NETWORK`,0,String(t)))}finally{s()}};return c(),{stop(){o=!0,n.abort(),r&&clearTimeout(r)}}}var Ce=45e3;function E(e){let t=Math.max(250,e.minBackoffMs??1e3),n=Math.max(t,e.maxBackoffMs??15e3),r=e.idleTimeoutMs??Ce,i=Number.isFinite(r)&&r>0?r:0,a=new AbortController,o=!1,s=e=>new Promise(t=>{if(a.signal.aborted)return t();let n=setTimeout(t,e);a.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),c=t=>{e.onAlive?.();let n=`message`,r=[];for(let e of t.split(`
2
2
  `)){let t=e.endsWith(`\r`)?e.slice(0,-1):e;if(t===``||t.startsWith(`:`))continue;let i=t.indexOf(`:`),a=i<0?t:t.slice(0,i),o=i<0?``:t.slice(i+1);o.startsWith(` `)&&(o=o.slice(1)),a===`event`?n=o:a===`data`&&r.push(o)}if(n===`state`&&r.length!==0)try{let t=JSON.parse(r.join(`
3
- `));t&&typeof t.state==`string`&&e.onState(t)}catch{}},s=/\r\n\r\n|\n\n|\r\r/,c=async(e,t)=>{let n=e.getReader(),r=new TextDecoder,a=``,c=!1;try{for(;;){let{value:e,done:l}=await n.read();if(l)return;!c&&e&&e.length>0&&(c=!0,t()),a+=r.decode(e,{stream:!0});let u;for(;(u=s.exec(a))!==null;)o(a.slice(0,u.index)),a=a.slice(u.index+u[0].length);if(i)return}}finally{await n.cancel().catch(()=>{})}};return(async()=>{let o=t;for(;!i;){try{let n=await m(e.credential);if(i)return;let a=h(e.eventsBaseUrl,`/v1/events/${encodeURIComponent(e.matchUrn)}`),s=await fetch(a,{method:`GET`,headers:{"x-api-key":n.apiKey,accept:`text/event-stream`},signal:r.signal,cache:`no-store`,credentials:`omit`,mode:`cors`});if(i)return;!s.ok||!s.body?e.onError?.(Error(`live-state subscribe failed: HTTP ${s.status}`)):await c(s.body,()=>{o=t})}catch(t){if(i||r.signal.aborted)return;e.onError?.(t)}if(i)return;await a(o),o=Math.min(n,o*2)}})(),{close(){i||(i=!0,r.abort())}}}function D(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var O=`havik.player.deviceId`,k;function A(){if(k)return k;try{let e=globalThis.localStorage?.getItem(O);if(e)return k=e,e}catch{}let e=we();k=e;try{globalThis.localStorage?.setItem(O,e)}catch{}return e}function Ce(){k=void 0;try{globalThis.localStorage?.removeItem(O)}catch{}}function we(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<16;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}function Te(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??A(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var j=new WeakMap;function Ee(e,t){let n=j.get(e);n||(n=new Map,j.set(e,n));let r=n.get(t.keySystem);if(r)return r;let i=t.createMediaKeys().catch(e=>{throw n.get(t.keySystem)===i&&n.delete(t.keySystem),e});return n.set(t.keySystem,i),i}function M(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var N=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function De(e){return e.startsWith(`com.widevine`)}function Oe(e,t){if(!De(e))return t;let n=(e,t)=>{let n=e.videoCapabilities;return!n?.length||!n.some(e=>e.robustness)?!1:n.every(e=>{let n=N.indexOf(e.robustness);return n===-1||N.indexOf(t)>n})},r=N.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function ke(e){return(t,n)=>M()?navigator.requestMediaKeySystemAccess(t,Oe(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>Ee(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var Ae=5e3,je=`video/mp4; codecs="avc1.42E01E"`,P=`audio/mp4; codecs="mp4a.40.2"`,Me={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function Ne(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:je,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:P,robustness:``,encryptionScheme:`cbcs`}]}]:Oe(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:je,robustness:`SW_SECURE_DECODE`,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:P,robustness:`SW_SECURE_CRYPTO`,encryptionScheme:`cbcs`}]}])}function F(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`probe-timeout`)),t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}async function Pe(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??Ae,r={};if(typeof window<`u`&&window.isSecureContext===!1)return{verdict:`insecure-context`,detail:r};let i=typeof navigator<`u`?navigator.requestMediaKeySystemAccess?.bind(navigator):void 0;if(!i)return{verdict:`no-cdm`,detail:r};let a=!1,o=!1,s=Date.now()+n,c=()=>Math.max(1,s-Date.now());for(let e of t){let t=Me[e];if(!t){r[e]=`unknown system`;continue}for(let n of t){if(Date.now()>=s){a=!0,r[e]??=`${n}: probe-timeout`;break}try{return await F((await F(i(n,Ne(e)),c())).createMediaKeys(),c()),r[e]=`ok (${n})`,{verdict:`supported`,system:e,detail:r}}catch(t){let i=t;r[e]=`${n}: ${(i?.name&&i.name!==`Error`?i.name:i?.message)||String(t)}`,i?.message===`probe-timeout`&&(a=!0),i?.name===`SecurityError`&&(o=!0)}}}return o?{verdict:`blocked-by-policy`,detail:r}:a?{verdict:`probe-timeout`,detail:r}:{verdict:`no-cdm`,detail:r}}var Fe=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function Ie(e){return Fe.test(e)}var I={droppedFrames:0};function L(e){try{return new URL(e).host}catch{return``}}var Le=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Re(e){if(typeof performance>`u`||typeof performance.getEntriesByType!=`function`)return``;let t=``,n=-1,r=performance.getEntriesByType(`resource`);for(let i of r)if(!(i.startTime<e)&&(i.initiatorType===`video`||i.initiatorType===`audio`||Le.test(i.name))&&i.startTime>=n){let e=L(i.name);e&&(t=e,n=i.startTime)}return t}function R(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}function ze(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function Be(e){try{let t=new TextDecoder(`utf-8`).decode(new Uint8Array(e));return/^skd:\/\/[0-9a-fA-F-]{36}:([0-9a-fA-F]{32})$/.exec(t)?.[1]}catch{return}}function z(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function B(){if(typeof window>`u`)return!1;let e=`WebKitMediaKeys`in window||typeof HTMLMediaElement<`u`&&`webkitSetMediaKeys`in HTMLMediaElement.prototype,t=typeof navigator<`u`&&/Apple/i.test(navigator.vendor??``);return e||t}var V=class{name=`native`;deps;onLoaded;onError;onEncrypted;fairplayLicenseUrl;keySession=null;fairplayArmed=!1;fairplayKeyIV;loadStarted;preloadTouched=!1;savedPreload=null;cdnHost=``;builtAt;constructor(e){this.deps=e,this.loadStarted=e.deferLoad!==!0,this.builtAt=typeof performance<`u`?performance.now():0}async load(){let{video:e,descriptor:t,emit:n}=this.deps;if(this.loadStarted||(this.preloadTouched=!0,this.savedPreload=e.getAttribute(`preload`),e.preload=`none`),t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new l(`DRM_CLIENT`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}this.armFairPlay()}let r=!this.loadStarted;this.onLoaded=r?void 0:()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=Ve(t.manifestUrl,t.analytics?.sid),e.load()}startLoad(){this.loadStarted||(this.loadStarted=!0,this.restorePreload())}restorePreload(){if(!this.preloadTouched)return;this.preloadTouched=!1;let{video:e}=this.deps;this.savedPreload===null?e.removeAttribute(`preload`):e.setAttribute(`preload`,this.savedPreload)}armFairPlay(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,emit:a}=this.deps,o=t.drm?.fairplay;if(!o)return;this.fairplayLicenseUrl=o.licenseUrl;let s=(e,t,n)=>a({type:`error`,error:new l(d(t),t,e),fatal:n});this.onEncrypted=a=>{let c=a;c.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=Be(c.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[c.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),l=await fetch(o.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!l.ok){this.fairplayArmed=!1,s(`FairPlay certificate request failed: ${l.status}`,l.status,!0);return}await a.setServerCertificate(await l.arrayBuffer()),await e.setMediaKeys(a);let u=a.createSession();this.keySession=u,u.addEventListener(`message`,e=>{(async()=>{try{let a=await fetch(this.fairplayLicenseUrl??o.licenseUrl,{method:`POST`,body:e.message,headers:{"x-api-key":n.apiKey,"X-Match-Urn":t.matchUrn,"X-Device-Id":r,...i?{"X-User-Id":i}:{},...this.fairplayKeyIV?{"X-Key-Iv":this.fairplayKeyIV}:{}}});if(!a.ok){s(`FairPlay license request failed: ${a.status}`,a.status,!0);return}await u.update(new Uint8Array(await a.arrayBuffer()))}catch(e){s(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await u.generateRequest(c.initDataType,c.initData)}catch(e){this.fairplayArmed=!1,s(`FairPlay key session failed: ${String(e)}`,0,!0)}})())},e.addEventListener(`encrypted`,this.onEncrypted)}setLicenseUrls(e){e.fairplay&&(this.fairplayLicenseUrl=e.fairplay)}getQualityLevels(){return[]}getCurrentQuality(){return-1}setQuality(e){}setMaxBitrate(e){}getAudioTracks(){let e=this.deps.video.audioTracks;return e?Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Audio ${n+1}`,lang:r.language||void 0,default:r.enabled}}):[]}setAudioTrack(e){let t=this.deps.video.audioTracks;if(t)for(let n=0;n<t.length;n+=1)t[n].enabled=n===e}getTextTracks(){let e=this.deps.video.textTracks;return Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Text ${n+1}`,lang:r.language||void 0}})}setTextTrack(e){let t=this.deps.video.textTracks;for(let n=0;n<t.length;n+=1)t[n].mode=n===e?`showing`:`disabled`}seekToLive(){let e=this.deps.video;e.seekable.length>0&&(e.currentTime=e.seekable.end(e.seekable.length-1))}getStats(){let e=this.deps.video,t=R(e),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames};return this.cdnHost||=Re(this.builtAt),this.cdnHost&&(n.cdnHost=this.cdnHost),this.deps.descriptor.drmEnabled&&(n.keySystem=`fairplay`),e.duration===1/0&&(n.isLive=!0,e.seekable.length>0&&(n.atLiveEdge=e.currentTime>=e.seekable.end(e.seekable.length-1)-2)),n}stop(){try{this.deps.video.pause()}catch{}}destroy(){let{video:e}=this.deps;this.onLoaded&&e.removeEventListener(`loadedmetadata`,this.onLoaded),this.onError&&e.removeEventListener(`error`,this.onError),this.onEncrypted&&e.removeEventListener(`encrypted`,this.onEncrypted),this.keySession?.close().catch(()=>{}),this.keySession=null,this.fairplayArmed=!1,this.fairplayKeyIV=void 0;try{e.pause()}catch{}e.removeAttribute(`src`),this.restorePreload();try{e.load()}catch{}}};function Ve(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function He(){return c.default.isSupported()}var Ue=3,We=5,Ge=3,Ke=3e4,qe=12e3,Je=3e3,H=6e3,Ye=4e3,Xe=2,Ze=5,Qe=2,$e=2,et=2e3,tt=3e4,nt=2,rt=9,it=.5,at=64;function ot(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=nt;let t=Math.max(12,e.liveSyncDuration+rt);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),st(e,e.liveSyncDuration)}function st(e,t){let n=(e,t,n)=>Math.min(n,Math.max(t,e));e.maxStarvationDelay??=n(t/2,.5,4),e.maxLoadingDelay??=n(t,1,4),e.abrEwmaFastLive??=n(t/2,1,3)}var U=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;bytesLoaded=0;playlistBytesLoaded=0;renditionSwitches=0;licenseTimeMs=0;licenseRequested=!1;upshifts=0;downshifts=0;lastLevelIndex=-1;requestCount=0;requestErrors=0;requestTimesMs=[];cdnHost=``;ladderHeights;ladderTopBitrateKbps=0;mediaRecoveries=0;networkRecoveries=0;licenseRecoveries=0;recoveryResetTimer=null;networkRetryTimer=null;licenseRetryTimer=null;onVisibility=null;onSeeking=null;sawLive=!1;lastEndSN=-1;lastAdvanceMs=0;endWatchdog=null;endedEmitted=!1;lastFragLoadingMs=0;starvedTicks=0;starvationKicks=0;kickPending=!1;kickTicks=0;starvationRebuilds=0;chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;capObserver=null;capTimer=null;sizeCapLevel=null;bitrateCapLevel=-1;sizeCapManaged=!0;dprMedia=null;onDprChange=null;loadStarted;constructor(e){this.deps=e,this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl,this.loadStarted=e.deferLoad!==!0}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=z(n)&&B(),a=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!a){r({type:`error`,error:new l(`DRM_CLIENT`,0,e.drm?.fairplay?.licenseUrl&&i?`FairPlay cannot be played on the hls.js engine (WebKit binds keys via the media sinf box); use engine "auto" or "native"`:`DRM is required but none of the stream’s key systems is usable on this platform (WebKit takes FairPlay only; other browsers take Widevine only)`),fatal:!0});return}this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),this.onSeeking=()=>this.clampOverSeek(),n.addEventListener(`seeking`,this.onSeeking),this.sizeCapManaged&&typeof ResizeObserver<`u`&&(this.capObserver=new ResizeObserver(()=>this.onMediaResize()),this.capObserver.observe(n),this.watchDprChanges())}startLoad(){this.loadStarted||(this.loadStarted=!0,this.hls?.startLoad(-1))}watchDprChanges(){if(typeof matchMedia!=`function`)return;this.unwatchDprChanges();let e=typeof self<`u`&&self.devicePixelRatio||1,t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+it||(n.currentTime=t)}startHls(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,lowLatency:a,debug:o,hlsConfig:s,emit:l}=this.deps;this.kickPending=!1,this.kickTicks=0,this.starvedTicks=0,this.lastFragLoadingMs=0,this.lastEndSN=-1,this.lastAdvanceMs=0;let u=t.drmEnabled&&!!(t.drm?.widevine?.licenseUrl||t.drm?.fairplay?.licenseUrl),d={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,maxBufferHole:.5,maxLiveSyncPlaybackRate:1.5,abrEwmaDefaultEstimate:1e6,capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...u?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:`SW_SECURE_DECODE`,audioRobustness:`SW_SECURE_CRYPTO`,videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`},...M()?{requestMediaKeySystemAccessFunc:ke(e)}:{},licenseXhrSetup:(e,a)=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0;let o=performance.now();e.addEventListener(`loadend`,()=>{this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o))})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};ot(d),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.loadStarted=d.autoStartLoad!==!1;let f=new c.default(d);this.hls=f,f.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0;let e=f.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=e.length?[...new Set(e)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=f.levels.length?Math.round(Math.max(...f.levels.map(e=>e.bitrate))/1e3):0,this.applySizeCap(),l({type:`ready`})}),f.on(c.default.Events.FRAG_BUFFERED,(e,t)=>{t?.frag?.type===`main`&&(this.kickPending=!1,this.kickTicks=0,(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0||this.starvationKicks>0||this.starvationRebuilds>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.starvationKicks=0,this.starvationRebuilds=0,this.recoveryResetTimer=null},Ke)))}),f.on(c.default.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),f.on(c.default.Events.FRAG_LOADED,(e,t)=>{let n=t?.frag?.stats,r=n?.loaded;typeof r==`number`&&(this.bytesLoaded+=r);let i=n?.loading;i&&i.end>0&&i.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(i.end-i.start))),this.requestTimesMs.length>at&&this.requestTimesMs.shift());let a=t?.frag?.url;if(a){let e=L(a);e&&(this.cdnHost=e)}}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.detectedLowLatency)return;let r=t.details;(r?.partList?.length||(r?.partTarget??0)>0)&&(this.detectedLowLatency=!0,l({type:`lowLatencyDetected`,value:!0}))}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation()},Je),f.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?f.levels[this.lastLevelIndex]:void 0,r=f.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,l({type:`qualitychange`,index:t.level})}),f.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),f.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),f.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),f.loadSource(t.manifestUrl),f.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=1;return!a.ignoreDevicePixelRatio&&typeof self<`u`&&self.devicePixelRatio>0&&(o=self.devicePixelRatio),o=Math.min(o,a.maxDevicePixelRatio??1/0),c.CapLevelController.getMaxLevelByMediaSize(e.levels,r*o,i*o)}onMediaResize(){if(!this.sizeCapManaged)return;let e=this.computeSizeCapTarget();if(e==null)return;if(this.sizeCapLevel==null){this.applySizeCap();return}if(e===this.sizeCapLevel){this.capTimer&&=(clearTimeout(this.capTimer),null);return}this.capTimer&&clearTimeout(this.capTimer);let t=e>this.sizeCapLevel?et:tt;this.capTimer=setTimeout(()=>{this.capTimer=null,this.computeSizeCapTarget()===e?this.applySizeCap():this.onMediaResize()},t)}applySizeCap(){if(!this.sizeCapManaged)return;this.capTimer&&=(clearTimeout(this.capTimer),null);let e=this.computeSizeCapTarget();e!=null&&(this.sizeCapLevel=e,this.pushCap())}pushCap(){let e=this.hls;if(!e)return;let t=this.sizeCapLevel??-1,n=this.bitrateCapLevel;e.autoLevelCapping=t<0?n:n<0?t:Math.min(t,n)}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=R(this.deps.video),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height),t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){this.sawLive=!0;let e=t.endSN??-1;e!==this.lastEndSN&&(this.lastEndSN=e,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>H&&this.suspendChasing(),e>qe&&this.emitEnded(`stalled`)}checkStarvation(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended)return;if(typeof document<`u`&&document.hidden){this.starvedTicks=0;return}let n=this.lastAdvanceMs!==0&&Date.now()-this.lastAdvanceMs<H,r=this.lastFragLoadingMs!==0&&Date.now()-this.lastFragLoadingMs>Ye;if(!(t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused&&n&&r)){this.starvedTicks=0;return}if(this.kickPending&&(this.kickTicks+=1),!(++this.starvedTicks<Xe)){if(this.starvedTicks=0,this.kickPending&&this.kickTicks>=Qe&&(this.kickPending=!1,this.kickTicks=0,this.starvationRebuilds<$e)){this.starvationRebuilds+=1,console.warn(`havik-player: restarting the load did not resume video (the wedge is in hls.js state that only a rebuild clears) — rebuilding the player`),this.rebuildInstance(`starvation rebuild`);return}if(!(this.starvationKicks>=Ze)){this.starvationKicks+=1,this.kickPending=!0,this.kickTicks=0,console.warn(`havik-player: video starved while the live playlist advances (wedged hls.js fragment pipeline) — restarting the load`);try{e.stopLoad(),e.startLoad(-1)}catch(e){console.warn(`havik-player: starvation kick failed`,e)}}}}suspendChasing(){let e=this.hls;e&&(this.chaseSuspended=!0,this.savedLiveMaxLatency=e.config.liveMaxLatencyDuration,this.savedMaxSyncRate=e.config.maxLiveSyncPlaybackRate,e.config.liveMaxLatencyDuration=2**53-1,e.config.maxLiveSyncPlaybackRate=1)}resumeChasing(){this.chaseSuspended=!1;let e=this.hls;e&&(e.config.liveMaxLatencyDuration=this.savedLiveMaxLatency,e.config.maxLiveSyncPlaybackRate=this.savedMaxSyncRate)}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.kickPending=!1,this.kickTicks=0;try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onSeeking&&=(this.deps.video.removeEventListener(`seeking`,this.onSeeking),null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(e.details!==c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED&&e.details!==c.default.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED)return!1;let t=e.response?.code??0;if(!(t===0||t===408||t===429||t>=500)||this.licenseRecoveries>=Ge)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls()}}onError(e){if(e.type===c.default.ErrorTypes.NETWORK_ERROR&&String(e.details??``).startsWith(`frag`)&&(this.requestErrors+=1),!e.fatal)return;let t=this.hls;if(t){if(this.clearRecoveryReset(),e.type===c.default.ErrorTypes.KEY_SYSTEM_ERROR){if(this.scheduleLicenseRetry(e))return;this.deps.emit({type:`error`,error:this.toError(e,`DRM`),fatal:!0,detail:e.details});return}if(e.type===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<We){this.networkRecoveries+=1;let e=Math.min(8e3,1e3*2**(this.networkRecoveries-1));this.networkRetryTimer=setTimeout(()=>{this.networkRetryTimer=null,this.hls&&this.hls.startLoad()},e);return}this.deps.emit({type:`error`,error:this.toError(e,`NETWORK`),fatal:!0,detail:e.details});return}if(e.type===c.default.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<Ue){this.mediaRecoveries+=1,t.recoverMediaError();return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``;return new l(t===`DRM`?d(n):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}},ct=15e3,lt=100,W=1,ut=1e3,G=3e4,dt=1e3,ft={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},pt={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`};function K(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}var mt=new Set([`INVALID_URN`,`NOT_FOUND`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),q={idle:`PLAYER_STATE_IDLE`,waiting:`PLAYER_STATE_WAITING`,loading:`PLAYER_STATE_LOADING`,playing:`PLAYER_STATE_PLAYING`,buffering:`PLAYER_STATE_BUFFERING`,paused:`PLAYER_STATE_PAUSED`,ended:`PLAYER_STATE_ENDED`,error:`PLAYER_STATE_ERROR`};function ht(e){try{let t=new URL(e),[n,...r]=t.hostname.split(`.`);return!n||r.length===0||n!==`feed`&&!n.startsWith(`feed-`)?void 0:(t.hostname=[n.replace(/^feed/,`beacons`),...r].join(`.`),t.pathname=``,t.search=``,t.origin)}catch{return}}var gt=class{opts;url;now;seq=0;pending=[];timer=null;endedFlag=!1;lastBytes=0;lastPlaylistBytes=0;lastDropped=0;lastSwitches=0;playingSinceMs=null;hiddenSinceMs=null;playingTotalMs=0;hiddenTotalMs=0;lastHbPlayingMs=0;lastHbHiddenMs=0;lastHbRebufferMs=0;lastHbRebufferCount=0;lastHbActiveMs=0;rebufferCount=0;rebufferTotalMs=0;bufferingSinceMs=null;isBuffering=!1;errorCount=0;seekCount=0;pauseCount=0;isPlaying=!1;isHidden=!1;isMuted=!1;activeSinceMs=null;activeTotalMs=0;mutedSinceMs=null;mutedTotalMs=0;lastHbMutedMs=0;volumeChanges=0;muteChanges=0;presentation=`inline`;presentationSinceMs;fullscreenTotalMs=0;pipTotalMs=0;waitingSinceMs=null;waitingTotalMs=0;firstAudioMs=0;timeToFirstStallMs=0;lastStallMs=0;lastErrorMs=0;lastSeekMs=-1;stallIsSeekInduced=!1;lastErrorStage=null;sawFirstBytes=!1;mediaInfoSignature=``;lastUpshifts=0;lastDownshifts=0;lastDecoded=0;lastRequestCount=0;lastRequestErrors=0;pendingStart=null;firstFlushTimer=null;bornMs;startupAnchorMs;startupTimeMs=0;manifestLoadMs=0;firstFragLoadMs=0;onPagehide=()=>this.end(`END_REASON_PAGEHIDE`);onVisibility=()=>{typeof document>`u`||(document.visibilityState===`hidden`?(this.hiddenSinceMs===null&&(this.hiddenSinceMs=this.now()),this.isHidden=!0):(this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=this.now()-this.hiddenSinceMs,this.hiddenSinceMs=null),this.isHidden=!1),this.syncActive(),this.syncBuffering())};constructor(e){this.opts={...e,heartbeatMs:e.heartbeatMs??ct},this.url=`${e.endpoint.replace(/\/$/,``)}/v1/beacons`,this.now=e.now??(()=>Date.now()),this.bornMs=this.now(),this.presentationSinceMs=this.bornMs,this.startupAnchorMs=this.bornMs}start(){if(this.endedFlag)return;let e={player:this.opts.player,sdkVersion:this.opts.sdkVersion,...this.opts.environment};this.pendingStart=e,this.enqueue({sessionStart:e}),this.firstFlushTimer=setTimeout(()=>this.flush(),ut),this.timer=setInterval(()=>this.heartbeat(),this.opts.heartbeatMs),typeof window<`u`&&window.addEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),this.onVisibility())}noteStateChange(e,t,n,r){if(this.endedFlag||e===t)return;let i=this.now();if(t===`playing`?(this.playingSinceMs===null&&(this.playingSinceMs=i),this.startupTimeMs===0&&(this.startupTimeMs=Math.max(W,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(W,i-this.startupAnchorMs)),this.isMuted&&this.mutedSinceMs===null&&(this.mutedSinceMs=i)):this.playingSinceMs!==null&&(this.playingTotalMs+=i-this.playingSinceMs,this.playingSinceMs=null,this.mutedSinceMs!==null&&(this.mutedTotalMs+=i-this.mutedSinceMs,this.mutedSinceMs=null)),this.isPlaying=t===`playing`,this.syncActive(),t===`waiting`?this.waitingSinceMs=i:this.waitingSinceMs!==null&&(this.waitingTotalMs+=i-this.waitingSinceMs,this.waitingSinceMs=null),t===`buffering`&&e===`playing`){this.stallIsSeekInduced=this.seekInduced(i);let e=!this.isHidden&&!this.stallIsSeekInduced;e&&(this.rebufferCount+=1),this.isBuffering=!0,this.lastStallMs=i,e&&this.timeToFirstStallMs===0&&(this.timeToFirstStallMs=Math.max(W,Math.round(this.playingTotalMs)))}else e===`buffering`&&(this.isBuffering=!1,this.stallIsSeekInduced=!1);this.syncBuffering(),t===`paused`&&(this.pauseCount+=1);let a={fromState:q[e]??`PLAYER_STATE_UNSPECIFIED`,toState:q[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:ft[this.presentation]},o=this.causeOf(e,t,i);o&&(a.cause=o),n>0&&(a.positionMs=Math.round(n)),r&&(a.renditionHeight=r),this.enqueue({stateChange:a})}seekInduced(e){return this.lastSeekMs>=0&&e-this.lastSeekMs<dt}causeOf(e,t,n){if(t===`error`)return`TRANSITION_CAUSE_ERROR`;if(t===`buffering`)return this.seekInduced(n)?`TRANSITION_CAUSE_SEEK`:`TRANSITION_CAUSE_NETWORK_STALL`;if(t===`paused`||t===`playing`&&e===`paused`)return`TRANSITION_CAUSE_USER`}syncActive(){let e=this.isPlaying&&!this.isHidden&&!this.isMuted;e&&this.activeSinceMs===null?this.activeSinceMs=this.now():!e&&this.activeSinceMs!==null&&(this.activeTotalMs+=this.now()-this.activeSinceMs,this.activeSinceMs=null)}syncBuffering(){let e=this.isBuffering&&!this.isHidden&&!this.stallIsSeekInduced;e&&this.bufferingSinceMs===null?this.bufferingSinceMs=this.now():!e&&this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=this.now()-this.bufferingSinceMs,this.bufferingSinceMs=null)}closePresentation(){let e=this.now(),t=e-this.presentationSinceMs;this.presentation===`fullscreen`?this.fullscreenTotalMs+=t:this.presentation===`pip`&&(this.pipTotalMs+=t),this.presentationSinceMs=e}noteAutoplay(e){this.pendingStart&&(this.pendingStart.autoplay=e)}noteEnvironment(e){this.pendingStart&&Object.assign(this.pendingStart,e)}seedVolume(e,t){this.endedFlag||(this.isMuted=e||t===0,this.isMuted&&this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=this.now()),this.syncActive())}noteVolume(e,t){if(this.endedFlag)return;let n=e||t===0;if(n===this.isMuted){this.volumeChanges+=1;return}this.muteChanges+=1;let r=this.now();n?this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=r):(this.mutedSinceMs!==null&&(this.mutedTotalMs+=r-this.mutedSinceMs,this.mutedSinceMs=null),this.firstAudioMs===0&&this.isPlaying&&(this.firstAudioMs=Math.max(W,r-this.startupAnchorMs))),this.isMuted=n,this.syncActive()}notePresentation(e){this.endedFlag||e===this.presentation||(this.closePresentation(),this.presentation=e)}notePlayIntent(){this.endedFlag||this.startupTimeMs>0||(this.startupAnchorMs=this.now(),this.manifestLoadMs>0&&(this.manifestLoadMs=W),this.firstFragLoadMs>0&&(this.firstFragLoadMs=W))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(W,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(W,this.now()-this.startupAnchorMs))}noteSeek(){this.endedFlag||(this.seekCount+=1,this.lastSeekMs=this.now())}noteError(e,t,n,r,i,a){if(this.endedFlag)return;this.errorCount+=1,this.lastErrorMs=this.now();let o={code:e};t&&(o.detail=t),n&&(o.fatal=!0),r>0&&(o.httpStatus=r),i>0&&(o.positionMs=Math.round(i));let s=this.stageOf(e,t,a);o.stage=s,this.lastErrorStage=s;let c=this.safeSample()?.cdnHost;c&&(o.cdnHost=c),this.enqueue({error:o}),this.flush()}stageOf(e,t,n){let r=n??``;if(r!==``)return/^fragLoad/i.test(r)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/^(manifest|level|audioTrack|subtitleTrack)/i.test(r)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(r)?`ERROR_STAGE_DRM`:/parsing|append|buffer|remux|decrypt|media/i.test(r)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`;if(e===`DRM_CLIENT`)return`ERROR_STAGE_DRM`;if(mt.has(e))return`ERROR_STAGE_RESOLVE`;let i=t??``;return/frag|segment/i.test(i)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/manifest|level|playlist/i.test(i)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(i)?`ERROR_STAGE_DRM`:/buffer|decode|media|append/i.test(i)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`}noteEnded(){this.end(`END_REASON_ENDED`)}noteDestroyed(){this.end(`END_REASON_STOPPED`)}noteFatal(){this.end(`END_REASON_FATAL_ERROR`)}heartbeat(){if(this.endedFlag)return;let e=this.opts.sample(),t=this.now(),n=this.playingTotalMs;this.playingSinceMs!==null&&(n+=t-this.playingSinceMs);let r=this.hiddenTotalMs;this.hiddenSinceMs!==null&&(r+=t-this.hiddenSinceMs);let i=this.rebufferTotalMs;this.bufferingSinceMs!==null&&(i+=t-this.bufferingSinceMs);let a=this.activeTotalMs;this.activeSinceMs!==null&&(a+=t-this.activeSinceMs);let o={},s=e.bytesLoaded??0;s>this.lastBytes&&(o.bytesDownloadedDelta=s-this.lastBytes),this.lastBytes=s;let c=e.playlistBytesLoaded??0;c>this.lastPlaylistBytes&&(o.playlistBytesDelta=c-this.lastPlaylistBytes),this.lastPlaylistBytes=c;let l=e.droppedFrames??0;l>this.lastDropped&&(o.droppedFramesDelta=l-this.lastDropped),this.lastDropped=l;let u=e.renditionSwitches??0;u>this.lastSwitches&&(o.renditionSwitchesDelta=u-this.lastSwitches),this.lastSwitches=u,n>this.lastHbPlayingMs&&(o.playingMsDelta=Math.round(n-this.lastHbPlayingMs)),this.lastHbPlayingMs=n,r>this.lastHbHiddenMs&&(o.hiddenMsDelta=Math.round(r-this.lastHbHiddenMs)),this.lastHbHiddenMs=r,i>this.lastHbRebufferMs&&(o.rebufferMsDelta=Math.round(i-this.lastHbRebufferMs)),this.lastHbRebufferMs=i,this.rebufferCount>this.lastHbRebufferCount&&(o.rebufferCountDelta=this.rebufferCount-this.lastHbRebufferCount),this.lastHbRebufferCount=this.rebufferCount,a>this.lastHbActiveMs&&(o.activeMsDelta=Math.round(a-this.lastHbActiveMs)),this.lastHbActiveMs=a,typeof e.latencySeconds==`number`&&(o.latencyMs=Math.round(e.latencySeconds*1e3)),typeof e.targetLatencySeconds==`number`&&(o.targetLatencyMs=Math.round(e.targetLatencySeconds*1e3)),typeof e.bandwidthKbps==`number`&&(o.bandwidthEstKbps=e.bandwidthKbps),typeof e.levelHeight==`number`&&(o.renditionHeight=e.levelHeight),typeof e.renditionBitrateKbps==`number`&&(o.renditionBitrateKbps=e.renditionBitrateKbps),e.atLiveEdge===!0&&(o.atLiveEdge=!0),typeof e.bufferedMs==`number`&&e.bufferedMs>0&&(o.bufferedMs=Math.round(e.bufferedMs)),o.playerState=q[e.state]??`PLAYER_STATE_UNSPECIFIED`;let d=this.mutedTotalMs;this.mutedSinceMs!==null&&(d+=t-this.mutedSinceMs),d>this.lastHbMutedMs&&(o.mutedMsDelta=Math.round(d-this.lastHbMutedMs)),this.lastHbMutedMs=d;let f=e.upshifts??0;f>this.lastUpshifts&&(o.upshiftsDelta=f-this.lastUpshifts),this.lastUpshifts=f;let p=e.downshifts??0;p>this.lastDownshifts&&(o.downshiftsDelta=p-this.lastDownshifts),this.lastDownshifts=p;let m=e.decodedFrames??0;m>this.lastDecoded&&(o.decodedFramesDelta=m-this.lastDecoded),this.lastDecoded=m;let h=e.requestErrors??0;h>this.lastRequestErrors&&(o.requestErrorsDelta=h-this.lastRequestErrors),this.lastRequestErrors=h;let g=e.requestCount??0,_=g-this.lastRequestCount;if(this.lastRequestCount=g,_>0){o.requestCountDelta=_;let t=e.requestTimesMs??[],n=t.slice(Math.max(0,t.length-_)).sort((e,t)=>e-t);n.length>0&&(o.requestTimeP50Ms=K(n,50),o.requestTimeP95Ms=K(n,95))}typeof e.latencySeconds==`number`&&typeof e.targetLatencySeconds==`number`&&(o.driftMs=Math.round((e.latencySeconds-e.targetLatencySeconds)*1e3)),typeof e.playbackRate==`number`&&e.playbackRate>0&&(o.playbackRate=e.playbackRate),e.qualityPinned===!0&&(o.qualityPinned=!0),e.cdnHost&&(o.cdnHost=e.cdnHost),this.maybeEmitMediaInfo(e),this.enqueue({heartbeat:o}),this.flush(),s>0&&this.noteFirstBytes()}maybeEmitMediaInfo(e){if(!(e.videoCodec??e.keySystem??e.ladderHeights))return;let t={};e.videoCodec&&(t.videoCodec=e.videoCodec),e.audioCodec&&(t.audioCodec=e.audioCodec),e.keySystem&&(t.keySystem=pt[e.keySystem]),e.drmSecurityLevel&&(t.drmSecurityLevel=e.drmSecurityLevel),e.ladderHeights?.length&&(t.ladderHeights=e.ladderHeights),e.ladderTopBitrateKbps&&(t.ladderTopBitrateKbps=e.ladderTopBitrateKbps),e.lowLatency&&(t.lowLatency=!0);let n=JSON.stringify(t);n!==this.mediaInfoSignature&&(this.mediaInfoSignature=n,this.enqueue({mediaInfo:t}))}end(e){if(this.endedFlag)return;this.endedFlag=!0;let t=this.now();this.playingSinceMs!==null&&(this.playingTotalMs+=t-this.playingSinceMs,this.playingSinceMs=null),this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=t-this.hiddenSinceMs,this.hiddenSinceMs=null),this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=t-this.bufferingSinceMs,this.bufferingSinceMs=null),this.mutedSinceMs!==null&&(this.mutedTotalMs+=t-this.mutedSinceMs,this.mutedSinceMs=null),this.waitingSinceMs!==null&&(this.waitingTotalMs+=t-this.waitingSinceMs,this.waitingSinceMs=null),this.isPlaying=!1,this.syncActive(),this.closePresentation(),this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.timer&&=(clearInterval(this.timer),null),typeof window<`u`&&window.removeEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&document.removeEventListener(`visibilitychange`,this.onVisibility);let n=this.safeSample();n&&this.maybeEmitMediaInfo(n);let r={reason:e},i=n?.bytesLoaded??this.lastBytes;i>0&&(r.bytesDownloadedTotal=i),this.playingTotalMs>0&&(r.watchTimeMs=Math.round(this.playingTotalMs)),this.rebufferCount>0&&(r.rebufferCount=this.rebufferCount),this.rebufferTotalMs>0&&(r.rebufferTimeMs=Math.round(this.rebufferTotalMs)),this.startupTimeMs>0&&(r.startupTimeMs=Math.round(this.startupTimeMs)),this.manifestLoadMs>0&&(r.manifestLoadMs=Math.round(this.manifestLoadMs)),this.firstFragLoadMs>0&&(r.firstFragLoadMs=Math.round(this.firstFragLoadMs));let a=n?.licenseTimeMs??0;a>0&&(r.licenseTimeMs=Math.round(a));let o=n?.droppedFrames??this.lastDropped;o>0&&(r.droppedFramesTotal=o),this.errorCount>0&&(r.errorCount=this.errorCount),this.hiddenTotalMs>0&&(r.hiddenTimeMs=Math.round(this.hiddenTotalMs)),this.seekCount>0&&(r.seekCount=this.seekCount),this.pauseCount>0&&(r.pauseCount=this.pauseCount),this.firstAudioMs>0&&(r.firstAudioMs=Math.round(this.firstAudioMs)),this.waitingTotalMs>0&&(r.waitingForLiveMs=Math.round(this.waitingTotalMs)),this.timeToFirstStallMs>0&&(r.timeToFirstStallMs=Math.round(this.timeToFirstStallMs));let s=n?.positionMs??0;s>0&&(r.exitPositionMs=Math.round(s)),this.activeTotalMs>0&&(r.activeWatchTimeMs=Math.round(this.activeTotalMs)),this.mutedTotalMs>0&&(r.mutedTimeMs=Math.round(this.mutedTotalMs));let c=e!==`END_REASON_ENDED`;c&&this.lastStallMs>0&&t-this.lastStallMs<=G&&(r.abandonAfterStallMs=Math.max(W,Math.round(t-this.lastStallMs))),c&&this.lastErrorMs>0&&t-this.lastErrorMs<=G&&(r.abandonAfterErrorMs=Math.max(W,Math.round(t-this.lastErrorMs))),this.fullscreenTotalMs>0&&(r.fullscreenTimeMs=Math.round(this.fullscreenTotalMs)),this.pipTotalMs>0&&(r.pipTimeMs=Math.round(this.pipTotalMs)),this.volumeChanges>0&&(r.volumeChanges=this.volumeChanges),this.muteChanges>0&&(r.muteChanges=this.muteChanges);let l=n?.decodedFrames??this.lastDecoded;l>0&&(r.decodedFramesTotal=l),this.startupTimeMs===0&&(r.failedStage=this.lastErrorStage??(this.manifestLoadMs===0?`ERROR_STAGE_MANIFEST`:this.firstFragLoadMs===0?`ERROR_STAGE_FIRST_SEGMENT`:`ERROR_STAGE_OTHER`)),this.pending.push(this.wrap({sessionEnd:r})),this.flush(e===`END_REASON_PAGEHIDE`)}safeSample(){try{return this.opts.sample()}catch{return null}}wrap(e){return this.seq+=1,{sid:this.opts.sid,clientTime:new Date(this.now()).toISOString(),seq:this.seq,...e}}enqueue(e){for(this.pending.push(this.wrap(e));this.pending.length>lt;){let e=this.pending.findIndex(e=>e.heartbeat||e.stateChange);this.pending.splice(e>=0?e:0,1)}}flush(e=!1){if(this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.pendingStart=null,this.pending.length===0)return;let t=JSON.stringify({beacons:this.pending});if(this.pending=[],e){let e=this.opts.sendBeacon??(typeof navigator<`u`&&navigator.sendBeacon?navigator.sendBeacon.bind(navigator):void 0);if(e&&e(this.url,t))return}let n=this.opts.fetchFn??(typeof fetch<`u`?fetch:void 0);n&&n(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:t,keepalive:!0}).catch(()=>{})}};function _t(){if(typeof window>`u`)return{integration:`INTEGRATION_KIND_SDK`};let e;try{e=window.top!==window.self}catch{e=!0}let t=window.location?.origin;if(!e)return{host:t&&t!==`null`?t:void 0,integration:`INTEGRATION_KIND_SDK`};let n;try{let e=window.location.ancestorOrigins;e&&e.length>0&&(n=e[e.length-1]??void 0),!n&&typeof document<`u`&&document.referrer&&(n=new URL(document.referrer).origin)}catch{n=void 0}return n===`null`&&(n=void 0),{host:n,integration:`INTEGRATION_KIND_IFRAME`}}function vt(){if(typeof navigator>`u`)return`DEVICE_CLASS_OTHER`;let e=navigator.userAgentData,t=e?.platform??``;if(/tv|tizen|webos/i.test(t))return`DEVICE_CLASS_TV`;let n=typeof screen<`u`?Math.min(screen.width,screen.height):0;return e?.mobile??(typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1&&n>0&&n<900)?n>=600?`DEVICE_CLASS_TABLET`:`DEVICE_CLASS_PHONE`:e||n>=900||/mac|win|linux|chrome os/i.test(t)?`DEVICE_CLASS_DESKTOP`:`DEVICE_CLASS_OTHER`}function yt(){let e=typeof navigator<`u`?navigator.connection:void 0;if(!e)return{connectionType:`CONNECTION_TYPE_UNKNOWN`};let t={wifi:`CONNECTION_TYPE_WIFI`,cellular:`CONNECTION_TYPE_CELLULAR`,ethernet:`CONNECTION_TYPE_ETHERNET`},n={"slow-2g":`RADIO_ACCESS_ESTIMATED_SLOW_2G`,"2g":`RADIO_ACCESS_ESTIMATED_2G`,"3g":`RADIO_ACCESS_ESTIMATED_3G`,"4g":`RADIO_ACCESS_ESTIMATED_4G`},r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,i={connectionType:e.type?r(t,e.type)??`CONNECTION_TYPE_OTHER`:`CONNECTION_TYPE_UNKNOWN`};if(e.effectiveType){let t=r(n,e.effectiveType);t&&(i.radioAccess=t)}return typeof e.downlink==`number`&&e.downlink>0&&(i.downlinkKbps=Math.round(e.downlink*1e3)),typeof e.rtt==`number`&&e.rtt>0&&(i.rttMs=Math.round(e.rtt)),e.saveData&&(i.saveData=!0),i}function bt(e){let t=_t(),n={deviceClass:vt(),integration:t.integration,...yt()};t.host&&(n.host=t.host),typeof screen<`u`&&screen.width>0&&(n.screenWidth=screen.width,n.screenHeight=screen.height),typeof window<`u`&&window.devicePixelRatio>0&&(n.devicePixelRatio=Math.round(window.devicePixelRatio*100)/100);let r=e.getBoundingClientRect?.();return r&&r.width>0&&(n.viewportWidth=Math.round(r.width),n.viewportHeight=Math.round(r.height)),n}async function xt(){let e=typeof navigator<`u`?navigator.userAgentData:void 0;if(!e?.getHighEntropyValues)return{};try{let t=await e.getHighEntropyValues([`model`,`platformVersion`]),n={};return t.model&&(n.deviceModel=t.model),t.platformVersion&&(n.osVersion=t.platformVersion),n}catch{return{}}}var St=`2.6.2`,J={accent:`#E1B600`,accentText:`#1B1C23`,background:`#0e0f13`,surface:`#1B1C23`,surfaceMuted:`#2a2c36`,text:`#ffffff`,textMuted:`#9aa0ad`,border:`rgba(255, 255, 255, 0.1)`,radius:`8px`,fontFamily:`ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`},Y={accent:`--havik-accent`,accentText:`--havik-accent-text`,background:`--havik-bg`,surface:`--havik-surface`,surfaceMuted:`--havik-surface-muted`,text:`--havik-text`,textMuted:`--havik-text-muted`,border:`--havik-border`,radius:`--havik-radius`,fontFamily:`--havik-font`};function X(e,t){let n={...J,...t};for(let t of Object.keys(Y))e.style.setProperty(Y[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var Z=`havik-player-styles`,Ct=`
3
+ `));t&&typeof t.state==`string`&&e.onState(t)}catch{}},l=/\r\n\r\n|\n\n|\r\r/,u=async(e,t,n)=>{let r=e.getReader(),a=new TextDecoder,s=``,u=!1,d,f=()=>{i&&(clearTimeout(d),d=setTimeout(()=>{n(),r.cancel().catch(()=>{})},i))};try{for(f();;){let{value:e,done:n}=await r.read();if(n)return;e&&e.length>0&&(f(),u||(u=!0,t())),s+=a.decode(e,{stream:!0});let i;for(;(i=l.exec(s))!==null;)c(s.slice(0,i.index)),s=s.slice(i.index+i[0].length);if(o)return}}finally{clearTimeout(d),await r.cancel().catch(()=>{})}};return(async()=>{let r=t;for(;!o;){let c=new AbortController,l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0});let d=null,f,p=()=>{d=`no data for ${i}ms`,c.abort()};try{let n=await m(e.credential);if(o)return;let a=h(e.eventsBaseUrl,`/v1/events/${encodeURIComponent(e.matchUrn)}`);i&&(f=setTimeout(()=>{d=`no response headers within ${i}ms`,c.abort()},i));let s=await fetch(a,{method:`GET`,headers:{"x-api-key":n.apiKey,accept:`text/event-stream`},signal:c.signal,cache:`no-store`,credentials:`omit`,mode:`cors`});if(clearTimeout(f),o)return;!s.ok||!s.body?e.onError?.(Error(`live-state subscribe failed: HTTP ${s.status}`)):await u(s.body,()=>{r=t},p)}catch(t){if(o||a.signal.aborted)return;d||e.onError?.(t)}finally{clearTimeout(f),a.signal.removeEventListener(`abort`,l),c.abort()}if(o)return;d&&e.onError?.(Error(`live-state subscribe idle: ${d} — reconnecting`)),await s(r),r=Math.min(n,r*2)}})(),{close(){o||(o=!0,a.abort())}}}function D(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var O=`havik.player.deviceId`,k;function A(){if(k)return k;try{let e=globalThis.localStorage?.getItem(O);if(e)return k=e,e}catch{}let e=Te();k=e;try{globalThis.localStorage?.setItem(O,e)}catch{}return e}function we(){k=void 0;try{globalThis.localStorage?.removeItem(O)}catch{}}function Te(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<16;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}function Ee(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??A(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var j=new WeakMap;function De(e,t){let n=j.get(e);n||(n=new Map,j.set(e,n));let r=n.get(t.keySystem);if(r)return r;let i=t.createMediaKeys().catch(e=>{throw n.get(t.keySystem)===i&&n.delete(t.keySystem),e});return n.set(t.keySystem,i),i}function M(){return typeof navigator<`u`&&typeof navigator.requestMediaKeySystemAccess==`function`}var N=[`SW_SECURE_DECODE`,`SW_SECURE_CRYPTO`];function Oe(e){return e.startsWith(`com.widevine`)}function ke(e,t){if(!Oe(e))return t;let n=(e,t)=>{let n=e.videoCapabilities;return!n?.length||!n.some(e=>e.robustness)?!1:n.every(e=>{let n=N.indexOf(e.robustness);return n===-1||N.indexOf(t)>n})},r=N.flatMap(e=>t.filter(t=>n(t,e)).map(t=>({...t,videoCapabilities:t.videoCapabilities?.map(t=>({...t,robustness:e}))})));return[...t,...r]}function Ae(e){return(t,n)=>M()?navigator.requestMediaKeySystemAccess(t,ke(t,n)).then(t=>({keySystem:t.keySystem,getConfiguration:()=>t.getConfiguration(),createMediaKeys:()=>De(e,t)})):Promise.reject(Error(`navigator.requestMediaKeySystemAccess is unavailable — EME needs a secure context (https, or localhost)`))}var je=5e3,Me=`video/mp4; codecs="avc1.42E01E"`,P=`audio/mp4; codecs="mp4a.40.2"`,Ne={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function Pe(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:Me,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:P,robustness:``,encryptionScheme:`cbcs`}]}]:ke(`com.widevine.alpha`,[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:Me,robustness:`SW_SECURE_DECODE`,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:P,robustness:`SW_SECURE_CRYPTO`,encryptionScheme:`cbcs`}]}])}function F(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`probe-timeout`)),t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}async function Fe(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??je,r={};if(typeof window<`u`&&window.isSecureContext===!1)return{verdict:`insecure-context`,detail:r};let i=typeof navigator<`u`?navigator.requestMediaKeySystemAccess?.bind(navigator):void 0;if(!i)return{verdict:`no-cdm`,detail:r};let a=!1,o=!1,s=Date.now()+n,c=()=>Math.max(1,s-Date.now());for(let e of t){let t=Ne[e];if(!t){r[e]=`unknown system`;continue}for(let n of t){if(Date.now()>=s){a=!0,r[e]??=`${n}: probe-timeout`;break}try{return await F((await F(i(n,Pe(e)),c())).createMediaKeys(),c()),r[e]=`ok (${n})`,{verdict:`supported`,system:e,detail:r}}catch(t){let i=t;r[e]=`${n}: ${(i?.name&&i.name!==`Error`?i.name:i?.message)||String(t)}`,i?.message===`probe-timeout`&&(a=!0),i?.name===`SecurityError`&&(o=!0)}}}return o?{verdict:`blocked-by-policy`,detail:r}:a?{verdict:`probe-timeout`,detail:r}:{verdict:`no-cdm`,detail:r}}var Ie=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function Le(e){return Ie.test(e)}var I={droppedFrames:0};function L(e){try{return new URL(e).host}catch{return``}}var Re=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function ze(e){if(typeof performance>`u`||typeof performance.getEntriesByType!=`function`)return``;let t=``,n=-1,r=performance.getEntriesByType(`resource`);for(let i of r)if(!(i.startTime<e)&&(i.initiatorType===`video`||i.initiatorType===`audio`||Re.test(i.name))&&i.startTime>=n){let e=L(i.name);e&&(t=e,n=i.startTime)}return t}function R(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}function Be(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function Ve(e){try{let t=new TextDecoder(`utf-8`).decode(new Uint8Array(e));return/^skd:\/\/[0-9a-fA-F-]{36}:([0-9a-fA-F]{32})$/.exec(t)?.[1]}catch{return}}function z(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function B(){if(typeof window>`u`)return!1;let e=`WebKitMediaKeys`in window||typeof HTMLMediaElement<`u`&&`webkitSetMediaKeys`in HTMLMediaElement.prototype,t=typeof navigator<`u`&&/Apple/i.test(navigator.vendor??``);return e||t}var V=class{name=`native`;deps;onLoaded;onError;onEncrypted;fairplayLicenseUrl;keySession=null;fairplayArmed=!1;fairplayKeyIV;loadStarted;preloadTouched=!1;savedPreload=null;cdnHost=``;builtAt;constructor(e){this.deps=e,this.loadStarted=e.deferLoad!==!0,this.builtAt=typeof performance<`u`?performance.now():0}async load(){let{video:e,descriptor:t,emit:n}=this.deps;if(this.loadStarted||(this.preloadTouched=!0,this.savedPreload=e.getAttribute(`preload`),e.preload=`none`),t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new l(`DRM_CLIENT`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}this.armFairPlay()}let r=!this.loadStarted;this.onLoaded=r?void 0:()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=He(t.manifestUrl,t.analytics?.sid),e.load()}startLoad(){this.loadStarted||(this.loadStarted=!0,this.restorePreload())}restorePreload(){if(!this.preloadTouched)return;this.preloadTouched=!1;let{video:e}=this.deps;this.savedPreload===null?e.removeAttribute(`preload`):e.setAttribute(`preload`,this.savedPreload)}armFairPlay(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,emit:a}=this.deps,o=t.drm?.fairplay;if(!o)return;this.fairplayLicenseUrl=o.licenseUrl;let s=(e,t,n)=>a({type:`error`,error:new l(d(t),t,e),fatal:n});this.onEncrypted=a=>{let c=a;c.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=Ve(c.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[c.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),l=await fetch(o.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!l.ok){this.fairplayArmed=!1,s(`FairPlay certificate request failed: ${l.status}`,l.status,!0);return}await a.setServerCertificate(await l.arrayBuffer()),await e.setMediaKeys(a);let u=a.createSession();this.keySession=u,u.addEventListener(`message`,e=>{(async()=>{try{let a=await fetch(this.fairplayLicenseUrl??o.licenseUrl,{method:`POST`,body:e.message,headers:{"x-api-key":n.apiKey,"X-Match-Urn":t.matchUrn,"X-Device-Id":r,...i?{"X-User-Id":i}:{},...this.fairplayKeyIV?{"X-Key-Iv":this.fairplayKeyIV}:{}}});if(!a.ok){s(`FairPlay license request failed: ${a.status}`,a.status,!0);return}await u.update(new Uint8Array(await a.arrayBuffer()))}catch(e){s(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await u.generateRequest(c.initDataType,c.initData)}catch(e){this.fairplayArmed=!1,s(`FairPlay key session failed: ${String(e)}`,0,!0)}})())},e.addEventListener(`encrypted`,this.onEncrypted)}setLicenseUrls(e){e.fairplay&&(this.fairplayLicenseUrl=e.fairplay)}getQualityLevels(){return[]}getCurrentQuality(){return-1}setQuality(e){}setMaxBitrate(e){}getAudioTracks(){let e=this.deps.video.audioTracks;return e?Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Audio ${n+1}`,lang:r.language||void 0,default:r.enabled}}):[]}setAudioTrack(e){let t=this.deps.video.audioTracks;if(t)for(let n=0;n<t.length;n+=1)t[n].enabled=n===e}getTextTracks(){let e=this.deps.video.textTracks;return Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Text ${n+1}`,lang:r.language||void 0}})}setTextTrack(e){let t=this.deps.video.textTracks;for(let n=0;n<t.length;n+=1)t[n].mode=n===e?`showing`:`disabled`}seekToLive(){let e=this.deps.video;e.seekable.length>0&&(e.currentTime=e.seekable.end(e.seekable.length-1))}getStats(){let e=this.deps.video,t=R(e),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames};return this.cdnHost||=ze(this.builtAt),this.cdnHost&&(n.cdnHost=this.cdnHost),this.deps.descriptor.drmEnabled&&(n.keySystem=`fairplay`),e.duration===1/0&&(n.isLive=!0,e.seekable.length>0&&(n.atLiveEdge=e.currentTime>=e.seekable.end(e.seekable.length-1)-2)),n}stop(){try{this.deps.video.pause()}catch{}}destroy(){let{video:e}=this.deps;this.onLoaded&&e.removeEventListener(`loadedmetadata`,this.onLoaded),this.onError&&e.removeEventListener(`error`,this.onError),this.onEncrypted&&e.removeEventListener(`encrypted`,this.onEncrypted),this.keySession?.close().catch(()=>{}),this.keySession=null,this.fairplayArmed=!1,this.fairplayKeyIV=void 0;try{e.pause()}catch{}e.removeAttribute(`src`),this.restorePreload();try{e.load()}catch{}}};function He(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function Ue(){return c.default.isSupported()}var We=3,Ge=5,Ke=3,qe=3e4,Je=12e3,Ye=3e3,H=6e3,Xe=5e3,Ze=4e3,Qe=2,$e=5,et=2,tt=2,nt=2e3,rt=3e4,it=2,at=9,ot=.5,st=64;function ct(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=it;let t=Math.max(12,e.liveSyncDuration+at);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),lt(e,e.liveSyncDuration)}function lt(e,t){let n=(e,t,n)=>Math.min(n,Math.max(t,e));e.maxStarvationDelay??=n(t/2,.5,4),e.maxLoadingDelay??=n(t,1,4),e.abrEwmaFastLive??=n(t/2,1,3)}var U=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;bytesLoaded=0;playlistBytesLoaded=0;renditionSwitches=0;licenseTimeMs=0;licenseRequested=!1;upshifts=0;downshifts=0;lastLevelIndex=-1;requestCount=0;requestErrors=0;requestTimesMs=[];cdnHost=``;ladderHeights;ladderTopBitrateKbps=0;mediaRecoveries=0;networkRecoveries=0;licenseRecoveries=0;recoveryResetTimer=null;networkRetryTimer=null;licenseRetryTimer=null;onVisibility=null;onSeeking=null;onPause=null;onPlay=null;pauseSuspendTimer=null;loadSuspended=!1;stopped=!1;sawLive=!1;lastEndSN=-1;lastAdvanceMs=0;endWatchdog=null;endedEmitted=!1;lastFragLoadingMs=0;starvedTicks=0;starvationKicks=0;kickPending=!1;kickTicks=0;starvationRebuilds=0;chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;capObserver=null;capTimer=null;sizeCapLevel=null;bitrateCapLevel=-1;sizeCapManaged=!0;dprMedia=null;onDprChange=null;loadStarted;constructor(e){this.deps=e,this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl,this.loadStarted=e.deferLoad!==!0}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=z(n)&&B(),a=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!a){r({type:`error`,error:new l(`DRM_CLIENT`,0,e.drm?.fairplay?.licenseUrl&&i?`FairPlay cannot be played on the hls.js engine (WebKit binds keys via the media sinf box); use engine "auto" or "native"`:`DRM is required but none of the stream’s key systems is usable on this platform (WebKit takes FairPlay only; other browsers take Widevine only)`),fatal:!0});return}this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),this.onSeeking=()=>{this.clampOverSeek(),this.loadSuspended&&(this.resumeLoading(),this.schedulePauseSuspend())},n.addEventListener(`seeking`,this.onSeeking),this.onPause=()=>this.schedulePauseSuspend(),this.onPlay=()=>this.resumeLoading(),n.addEventListener(`pause`,this.onPause),n.addEventListener(`play`,this.onPlay),this.sizeCapManaged&&typeof ResizeObserver<`u`&&(this.capObserver=new ResizeObserver(()=>this.onMediaResize()),this.capObserver.observe(n),this.watchDprChanges())}schedulePauseSuspend(){this.pauseSuspendTimer||this.loadSuspended||this.stopped||!this.loadStarted||(this.pauseSuspendTimer=setTimeout(()=>{this.pauseSuspendTimer=null;let{video:e}=this.deps;if(e.paused&&!e.ended&&!this.stopped&&this.hls){try{this.hls.stopLoad()}catch{return}this.loadSuspended=!0}},Xe))}resumeLoading(){if(this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.loadSuspended&&(this.loadSuspended=!1,!this.stopped&&this.hls)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.starvedTicks=0,this.kickPending=!1,this.kickTicks=0;try{this.hls.startLoad(-1)}catch{}}}startLoad(){this.loadStarted||(this.loadStarted=!0,this.deps.video.paused&&this.schedulePauseSuspend(),this.hls?.startLoad(-1))}watchDprChanges(){if(typeof matchMedia!=`function`)return;this.unwatchDprChanges();let e=typeof self<`u`&&self.devicePixelRatio||1,t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+ot||(n.currentTime=t)}startHls(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,lowLatency:a,debug:o,hlsConfig:s,emit:l}=this.deps;this.kickPending=!1,this.kickTicks=0,this.starvedTicks=0,this.lastFragLoadingMs=0,this.lastEndSN=-1,this.lastAdvanceMs=0;let u=t.drmEnabled&&!!(t.drm?.widevine?.licenseUrl||t.drm?.fairplay?.licenseUrl),d={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,maxBufferHole:.5,maxLiveSyncPlaybackRate:1.5,abrEwmaDefaultEstimate:1e6,capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...u?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:`SW_SECURE_DECODE`,audioRobustness:`SW_SECURE_CRYPTO`,videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`},...M()?{requestMediaKeySystemAccessFunc:Ae(e)}:{},licenseXhrSetup:(e,a)=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0;let o=performance.now();e.addEventListener(`loadend`,()=>{this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o))})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};ct(d),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.loadStarted=d.autoStartLoad!==!1;let f=new c.default(d);this.hls=f,f.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0;let t=f.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=f.levels.length?Math.round(Math.max(...f.levels.map(e=>e.bitrate))/1e3):0,this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),l({type:`ready`})}),f.on(c.default.Events.FRAG_BUFFERED,(e,t)=>{t?.frag?.type===`main`&&(this.kickPending=!1,this.kickTicks=0,(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0||this.starvationKicks>0||this.starvationRebuilds>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.starvationKicks=0,this.starvationRebuilds=0,this.recoveryResetTimer=null},qe)))}),f.on(c.default.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),f.on(c.default.Events.FRAG_LOADED,(e,t)=>{let n=t?.frag?.stats,r=n?.loaded;typeof r==`number`&&(this.bytesLoaded+=r);let i=n?.loading;i&&i.end>0&&i.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(i.end-i.start))),this.requestTimesMs.length>st&&this.requestTimesMs.shift());let a=t?.frag?.url;if(a){let e=L(a);e&&(this.cdnHost=e)}}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.detectedLowLatency)return;let r=t.details;(r?.partList?.length||(r?.partTarget??0)>0)&&(this.detectedLowLatency=!0,l({type:`lowLatencyDetected`,value:!0}))}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation()},Ye),f.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?f.levels[this.lastLevelIndex]:void 0,r=f.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,l({type:`qualitychange`,index:t.level})}),f.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),f.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),f.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),f.loadSource(t.manifestUrl),f.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=1;return!a.ignoreDevicePixelRatio&&typeof self<`u`&&self.devicePixelRatio>0&&(o=self.devicePixelRatio),o=Math.min(o,a.maxDevicePixelRatio??1/0),c.CapLevelController.getMaxLevelByMediaSize(e.levels,r*o,i*o)}onMediaResize(){if(!this.sizeCapManaged)return;let e=this.computeSizeCapTarget();if(e==null)return;if(this.sizeCapLevel==null){this.applySizeCap();return}if(e===this.sizeCapLevel){this.capTimer&&=(clearTimeout(this.capTimer),null);return}this.capTimer&&clearTimeout(this.capTimer);let t=e>this.sizeCapLevel?nt:rt;this.capTimer=setTimeout(()=>{this.capTimer=null,this.computeSizeCapTarget()===e?this.applySizeCap():this.onMediaResize()},t)}applySizeCap(){if(!this.sizeCapManaged)return;this.capTimer&&=(clearTimeout(this.capTimer),null);let e=this.computeSizeCapTarget();e!=null&&(this.sizeCapLevel=e,this.pushCap())}pushCap(){let e=this.hls;if(!e)return;let t=this.sizeCapLevel??-1,n=this.bitrateCapLevel;e.autoLevelCapping=t<0?n:n<0?t:Math.min(t,n)}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=R(this.deps.video),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height),t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){this.sawLive=!0;let e=t.endSN??-1;e!==this.lastEndSN&&(this.lastEndSN=e,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>H&&this.suspendChasing(),e>Je&&this.emitEnded(`stalled`)}checkStarvation(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended)return;if(typeof document<`u`&&document.hidden||this.loadSuspended){this.starvedTicks=0;return}let n=this.lastAdvanceMs!==0&&Date.now()-this.lastAdvanceMs<H,r=this.lastFragLoadingMs!==0&&Date.now()-this.lastFragLoadingMs>Ze;if(!(t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused&&n&&r)){this.starvedTicks=0;return}if(this.kickPending&&(this.kickTicks+=1),!(++this.starvedTicks<Qe)){if(this.starvedTicks=0,this.kickPending&&this.kickTicks>=et&&(this.kickPending=!1,this.kickTicks=0,this.starvationRebuilds<tt)){this.starvationRebuilds+=1,console.warn(`havik-player: restarting the load did not resume video (the wedge is in hls.js state that only a rebuild clears) — rebuilding the player`),this.rebuildInstance(`starvation rebuild`);return}if(!(this.starvationKicks>=$e)){this.starvationKicks+=1,this.kickPending=!0,this.kickTicks=0,console.warn(`havik-player: video starved while the live playlist advances (wedged hls.js fragment pipeline) — restarting the load`);try{e.stopLoad(),e.startLoad(-1)}catch(e){console.warn(`havik-player: starvation kick failed`,e)}}}}suspendChasing(){let e=this.hls;e&&(this.chaseSuspended=!0,this.savedLiveMaxLatency=e.config.liveMaxLatencyDuration,this.savedMaxSyncRate=e.config.maxLiveSyncPlaybackRate,e.config.liveMaxLatencyDuration=2**53-1,e.config.maxLiveSyncPlaybackRate=1)}resumeChasing(){this.chaseSuspended=!1;let e=this.hls;e&&(e.config.liveMaxLatencyDuration=this.savedLiveMaxLatency,e.config.maxLiveSyncPlaybackRate=this.savedMaxSyncRate)}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.kickPending=!1,this.kickTicks=0,this.stopped=!0,this.loadSuspended=!1,this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onSeeking&&=(this.deps.video.removeEventListener(`seeking`,this.onSeeking),null),this.onPause&&=(this.deps.video.removeEventListener(`pause`,this.onPause),null),this.onPlay&&=(this.deps.video.removeEventListener(`play`,this.onPlay),null),this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(e.details!==c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED&&e.details!==c.default.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED)return!1;let t=e.response?.code??0;if(!(t===0||t===408||t===429||t>=500)||this.licenseRecoveries>=Ke)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls()}}onError(e){if(e.type===c.default.ErrorTypes.NETWORK_ERROR&&String(e.details??``).startsWith(`frag`)&&(this.requestErrors+=1),!e.fatal)return;let t=this.hls;if(t){if(this.clearRecoveryReset(),e.type===c.default.ErrorTypes.KEY_SYSTEM_ERROR){if(this.scheduleLicenseRetry(e))return;this.deps.emit({type:`error`,error:this.toError(e,`DRM`),fatal:!0,detail:e.details});return}if(e.type===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<Ge){this.networkRecoveries+=1;let e=Math.min(8e3,1e3*2**(this.networkRecoveries-1));this.networkRetryTimer=setTimeout(()=>{this.networkRetryTimer=null,this.hls&&this.hls.startLoad()},e);return}this.deps.emit({type:`error`,error:this.toError(e,`NETWORK`),fatal:!0,detail:e.details});return}if(e.type===c.default.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<We){this.mediaRecoveries+=1,t.recoverMediaError();return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``;return new l(t===`DRM`?d(n):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}},ut=15e3,dt=100,W=1,ft=1e3,G=3e4,pt=1e3,mt={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},ht={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`};function K(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}var gt=new Set([`INVALID_URN`,`NOT_FOUND`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),q={idle:`PLAYER_STATE_IDLE`,waiting:`PLAYER_STATE_WAITING`,loading:`PLAYER_STATE_LOADING`,playing:`PLAYER_STATE_PLAYING`,buffering:`PLAYER_STATE_BUFFERING`,paused:`PLAYER_STATE_PAUSED`,ended:`PLAYER_STATE_ENDED`,error:`PLAYER_STATE_ERROR`};function _t(e){try{let t=new URL(e),[n,...r]=t.hostname.split(`.`);return!n||r.length===0||n!==`feed`&&!n.startsWith(`feed-`)?void 0:(t.hostname=[n.replace(/^feed/,`beacons`),...r].join(`.`),t.pathname=``,t.search=``,t.origin)}catch{return}}var vt=class{opts;url;now;seq=0;pending=[];timer=null;endedFlag=!1;lastBytes=0;lastPlaylistBytes=0;lastDropped=0;lastSwitches=0;playingSinceMs=null;hiddenSinceMs=null;playingTotalMs=0;hiddenTotalMs=0;lastHbPlayingMs=0;lastHbHiddenMs=0;lastHbRebufferMs=0;lastHbRebufferCount=0;lastHbActiveMs=0;rebufferCount=0;rebufferTotalMs=0;bufferingSinceMs=null;isBuffering=!1;errorCount=0;seekCount=0;pauseCount=0;isPlaying=!1;isHidden=!1;isMuted=!1;activeSinceMs=null;activeTotalMs=0;mutedSinceMs=null;mutedTotalMs=0;lastHbMutedMs=0;volumeChanges=0;muteChanges=0;presentation=`inline`;presentationSinceMs;fullscreenTotalMs=0;pipTotalMs=0;waitingSinceMs=null;waitingTotalMs=0;firstAudioMs=0;timeToFirstStallMs=0;lastStallMs=0;lastErrorMs=0;lastSeekMs=-1;stallIsSeekInduced=!1;lastErrorStage=null;sawFirstBytes=!1;mediaInfoSignature=``;lastUpshifts=0;lastDownshifts=0;lastDecoded=0;lastRequestCount=0;lastRequestErrors=0;pendingStart=null;firstFlushTimer=null;bornMs;startupAnchorMs;startupTimeMs=0;manifestLoadMs=0;firstFragLoadMs=0;onPagehide=()=>this.end(`END_REASON_PAGEHIDE`);onVisibility=()=>{typeof document>`u`||(document.visibilityState===`hidden`?(this.hiddenSinceMs===null&&(this.hiddenSinceMs=this.now()),this.isHidden=!0):(this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=this.now()-this.hiddenSinceMs,this.hiddenSinceMs=null),this.isHidden=!1),this.syncActive(),this.syncBuffering())};constructor(e){this.opts={...e,heartbeatMs:e.heartbeatMs??ut},this.url=`${e.endpoint.replace(/\/$/,``)}/v1/beacons`,this.now=e.now??(()=>Date.now()),this.bornMs=this.now(),this.presentationSinceMs=this.bornMs,this.startupAnchorMs=this.bornMs}start(){if(this.endedFlag)return;let e={player:this.opts.player,sdkVersion:this.opts.sdkVersion,...this.opts.environment};this.pendingStart=e,this.enqueue({sessionStart:e}),this.firstFlushTimer=setTimeout(()=>this.flush(),ft),this.timer=setInterval(()=>this.heartbeat(),this.opts.heartbeatMs),typeof window<`u`&&window.addEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),this.onVisibility())}noteStateChange(e,t,n,r){if(this.endedFlag||e===t)return;let i=this.now();if(t===`playing`?(this.playingSinceMs===null&&(this.playingSinceMs=i),this.startupTimeMs===0&&(this.startupTimeMs=Math.max(W,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(W,i-this.startupAnchorMs)),this.isMuted&&this.mutedSinceMs===null&&(this.mutedSinceMs=i)):this.playingSinceMs!==null&&(this.playingTotalMs+=i-this.playingSinceMs,this.playingSinceMs=null,this.mutedSinceMs!==null&&(this.mutedTotalMs+=i-this.mutedSinceMs,this.mutedSinceMs=null)),this.isPlaying=t===`playing`,this.syncActive(),t===`waiting`?this.waitingSinceMs=i:this.waitingSinceMs!==null&&(this.waitingTotalMs+=i-this.waitingSinceMs,this.waitingSinceMs=null),t===`buffering`&&e===`playing`){this.stallIsSeekInduced=this.seekInduced(i);let e=!this.isHidden&&!this.stallIsSeekInduced;e&&(this.rebufferCount+=1),this.isBuffering=!0,this.lastStallMs=i,e&&this.timeToFirstStallMs===0&&(this.timeToFirstStallMs=Math.max(W,Math.round(this.playingTotalMs)))}else e===`buffering`&&(this.isBuffering=!1,this.stallIsSeekInduced=!1);this.syncBuffering(),t===`paused`&&(this.pauseCount+=1);let a={fromState:q[e]??`PLAYER_STATE_UNSPECIFIED`,toState:q[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:mt[this.presentation]},o=this.causeOf(e,t,i);o&&(a.cause=o),n>0&&(a.positionMs=Math.round(n)),r&&(a.renditionHeight=r),this.enqueue({stateChange:a})}seekInduced(e){return this.lastSeekMs>=0&&e-this.lastSeekMs<pt}causeOf(e,t,n){if(t===`error`)return`TRANSITION_CAUSE_ERROR`;if(t===`buffering`)return this.seekInduced(n)?`TRANSITION_CAUSE_SEEK`:`TRANSITION_CAUSE_NETWORK_STALL`;if(t===`paused`||t===`playing`&&e===`paused`)return`TRANSITION_CAUSE_USER`}syncActive(){let e=this.isPlaying&&!this.isHidden&&!this.isMuted;e&&this.activeSinceMs===null?this.activeSinceMs=this.now():!e&&this.activeSinceMs!==null&&(this.activeTotalMs+=this.now()-this.activeSinceMs,this.activeSinceMs=null)}syncBuffering(){let e=this.isBuffering&&!this.isHidden&&!this.stallIsSeekInduced;e&&this.bufferingSinceMs===null?this.bufferingSinceMs=this.now():!e&&this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=this.now()-this.bufferingSinceMs,this.bufferingSinceMs=null)}closePresentation(){let e=this.now(),t=e-this.presentationSinceMs;this.presentation===`fullscreen`?this.fullscreenTotalMs+=t:this.presentation===`pip`&&(this.pipTotalMs+=t),this.presentationSinceMs=e}noteAutoplay(e){this.pendingStart&&(this.pendingStart.autoplay=e)}noteEnvironment(e){this.pendingStart&&Object.assign(this.pendingStart,e)}seedVolume(e,t){this.endedFlag||(this.isMuted=e||t===0,this.isMuted&&this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=this.now()),this.syncActive())}noteVolume(e,t){if(this.endedFlag)return;let n=e||t===0;if(n===this.isMuted){this.volumeChanges+=1;return}this.muteChanges+=1;let r=this.now();n?this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=r):(this.mutedSinceMs!==null&&(this.mutedTotalMs+=r-this.mutedSinceMs,this.mutedSinceMs=null),this.firstAudioMs===0&&this.isPlaying&&(this.firstAudioMs=Math.max(W,r-this.startupAnchorMs))),this.isMuted=n,this.syncActive()}notePresentation(e){this.endedFlag||e===this.presentation||(this.closePresentation(),this.presentation=e)}notePlayIntent(){this.endedFlag||this.startupTimeMs>0||(this.startupAnchorMs=this.now(),this.manifestLoadMs>0&&(this.manifestLoadMs=W),this.firstFragLoadMs>0&&(this.firstFragLoadMs=W))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(W,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(W,this.now()-this.startupAnchorMs))}noteSeek(){this.endedFlag||(this.seekCount+=1,this.lastSeekMs=this.now())}noteError(e,t,n,r,i,a){if(this.endedFlag)return;this.errorCount+=1,this.lastErrorMs=this.now();let o={code:e};t&&(o.detail=t),n&&(o.fatal=!0),r>0&&(o.httpStatus=r),i>0&&(o.positionMs=Math.round(i));let s=this.stageOf(e,t,a);o.stage=s,this.lastErrorStage=s;let c=this.safeSample()?.cdnHost;c&&(o.cdnHost=c),this.enqueue({error:o}),this.flush()}stageOf(e,t,n){let r=n??``;if(r!==``)return/^fragLoad/i.test(r)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/^(manifest|level|audioTrack|subtitleTrack)/i.test(r)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(r)?`ERROR_STAGE_DRM`:/parsing|append|buffer|remux|decrypt|media/i.test(r)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`;if(e===`DRM_CLIENT`)return`ERROR_STAGE_DRM`;if(gt.has(e))return`ERROR_STAGE_RESOLVE`;let i=t??``;return/frag|segment/i.test(i)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/manifest|level|playlist/i.test(i)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(i)?`ERROR_STAGE_DRM`:/buffer|decode|media|append/i.test(i)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`}noteEnded(){this.end(`END_REASON_ENDED`)}noteDestroyed(){this.end(`END_REASON_STOPPED`)}noteFatal(){this.end(`END_REASON_FATAL_ERROR`)}heartbeat(){if(this.endedFlag)return;let e=this.opts.sample(),t=this.now(),n=this.playingTotalMs;this.playingSinceMs!==null&&(n+=t-this.playingSinceMs);let r=this.hiddenTotalMs;this.hiddenSinceMs!==null&&(r+=t-this.hiddenSinceMs);let i=this.rebufferTotalMs;this.bufferingSinceMs!==null&&(i+=t-this.bufferingSinceMs);let a=this.activeTotalMs;this.activeSinceMs!==null&&(a+=t-this.activeSinceMs);let o={},s=e.bytesLoaded??0;s>this.lastBytes&&(o.bytesDownloadedDelta=s-this.lastBytes),this.lastBytes=s;let c=e.playlistBytesLoaded??0;c>this.lastPlaylistBytes&&(o.playlistBytesDelta=c-this.lastPlaylistBytes),this.lastPlaylistBytes=c;let l=e.droppedFrames??0;l>this.lastDropped&&(o.droppedFramesDelta=l-this.lastDropped),this.lastDropped=l;let u=e.renditionSwitches??0;u>this.lastSwitches&&(o.renditionSwitchesDelta=u-this.lastSwitches),this.lastSwitches=u,n>this.lastHbPlayingMs&&(o.playingMsDelta=Math.round(n-this.lastHbPlayingMs)),this.lastHbPlayingMs=n,r>this.lastHbHiddenMs&&(o.hiddenMsDelta=Math.round(r-this.lastHbHiddenMs)),this.lastHbHiddenMs=r,i>this.lastHbRebufferMs&&(o.rebufferMsDelta=Math.round(i-this.lastHbRebufferMs)),this.lastHbRebufferMs=i,this.rebufferCount>this.lastHbRebufferCount&&(o.rebufferCountDelta=this.rebufferCount-this.lastHbRebufferCount),this.lastHbRebufferCount=this.rebufferCount,a>this.lastHbActiveMs&&(o.activeMsDelta=Math.round(a-this.lastHbActiveMs)),this.lastHbActiveMs=a,typeof e.latencySeconds==`number`&&(o.latencyMs=Math.round(e.latencySeconds*1e3)),typeof e.targetLatencySeconds==`number`&&(o.targetLatencyMs=Math.round(e.targetLatencySeconds*1e3)),typeof e.bandwidthKbps==`number`&&(o.bandwidthEstKbps=e.bandwidthKbps),typeof e.levelHeight==`number`&&(o.renditionHeight=e.levelHeight),typeof e.renditionBitrateKbps==`number`&&(o.renditionBitrateKbps=e.renditionBitrateKbps),e.atLiveEdge===!0&&(o.atLiveEdge=!0),typeof e.bufferedMs==`number`&&e.bufferedMs>0&&(o.bufferedMs=Math.round(e.bufferedMs)),o.playerState=q[e.state]??`PLAYER_STATE_UNSPECIFIED`;let d=this.mutedTotalMs;this.mutedSinceMs!==null&&(d+=t-this.mutedSinceMs),d>this.lastHbMutedMs&&(o.mutedMsDelta=Math.round(d-this.lastHbMutedMs)),this.lastHbMutedMs=d;let f=e.upshifts??0;f>this.lastUpshifts&&(o.upshiftsDelta=f-this.lastUpshifts),this.lastUpshifts=f;let p=e.downshifts??0;p>this.lastDownshifts&&(o.downshiftsDelta=p-this.lastDownshifts),this.lastDownshifts=p;let m=e.decodedFrames??0;m>this.lastDecoded&&(o.decodedFramesDelta=m-this.lastDecoded),this.lastDecoded=m;let h=e.requestErrors??0;h>this.lastRequestErrors&&(o.requestErrorsDelta=h-this.lastRequestErrors),this.lastRequestErrors=h;let g=e.requestCount??0,_=g-this.lastRequestCount;if(this.lastRequestCount=g,_>0){o.requestCountDelta=_;let t=e.requestTimesMs??[],n=t.slice(Math.max(0,t.length-_)).sort((e,t)=>e-t);n.length>0&&(o.requestTimeP50Ms=K(n,50),o.requestTimeP95Ms=K(n,95))}typeof e.latencySeconds==`number`&&typeof e.targetLatencySeconds==`number`&&(o.driftMs=Math.round((e.latencySeconds-e.targetLatencySeconds)*1e3)),typeof e.playbackRate==`number`&&e.playbackRate>0&&(o.playbackRate=e.playbackRate),e.qualityPinned===!0&&(o.qualityPinned=!0),e.cdnHost&&(o.cdnHost=e.cdnHost),this.maybeEmitMediaInfo(e),this.enqueue({heartbeat:o}),this.flush(),s>0&&this.noteFirstBytes()}maybeEmitMediaInfo(e){if(!(e.videoCodec??e.keySystem??e.ladderHeights))return;let t={};e.videoCodec&&(t.videoCodec=e.videoCodec),e.audioCodec&&(t.audioCodec=e.audioCodec),e.keySystem&&(t.keySystem=ht[e.keySystem]),e.drmSecurityLevel&&(t.drmSecurityLevel=e.drmSecurityLevel),e.ladderHeights?.length&&(t.ladderHeights=e.ladderHeights),e.ladderTopBitrateKbps&&(t.ladderTopBitrateKbps=e.ladderTopBitrateKbps),e.lowLatency&&(t.lowLatency=!0);let n=JSON.stringify(t);n!==this.mediaInfoSignature&&(this.mediaInfoSignature=n,this.enqueue({mediaInfo:t}))}end(e){if(this.endedFlag)return;this.endedFlag=!0;let t=this.now();this.playingSinceMs!==null&&(this.playingTotalMs+=t-this.playingSinceMs,this.playingSinceMs=null),this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=t-this.hiddenSinceMs,this.hiddenSinceMs=null),this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=t-this.bufferingSinceMs,this.bufferingSinceMs=null),this.mutedSinceMs!==null&&(this.mutedTotalMs+=t-this.mutedSinceMs,this.mutedSinceMs=null),this.waitingSinceMs!==null&&(this.waitingTotalMs+=t-this.waitingSinceMs,this.waitingSinceMs=null),this.isPlaying=!1,this.syncActive(),this.closePresentation(),this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.timer&&=(clearInterval(this.timer),null),typeof window<`u`&&window.removeEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&document.removeEventListener(`visibilitychange`,this.onVisibility);let n=this.safeSample();n&&this.maybeEmitMediaInfo(n);let r={reason:e},i=n?.bytesLoaded??this.lastBytes;i>0&&(r.bytesDownloadedTotal=i),this.playingTotalMs>0&&(r.watchTimeMs=Math.round(this.playingTotalMs)),this.rebufferCount>0&&(r.rebufferCount=this.rebufferCount),this.rebufferTotalMs>0&&(r.rebufferTimeMs=Math.round(this.rebufferTotalMs)),this.startupTimeMs>0&&(r.startupTimeMs=Math.round(this.startupTimeMs)),this.manifestLoadMs>0&&(r.manifestLoadMs=Math.round(this.manifestLoadMs)),this.firstFragLoadMs>0&&(r.firstFragLoadMs=Math.round(this.firstFragLoadMs));let a=n?.licenseTimeMs??0;a>0&&(r.licenseTimeMs=Math.round(a));let o=n?.droppedFrames??this.lastDropped;o>0&&(r.droppedFramesTotal=o),this.errorCount>0&&(r.errorCount=this.errorCount),this.hiddenTotalMs>0&&(r.hiddenTimeMs=Math.round(this.hiddenTotalMs)),this.seekCount>0&&(r.seekCount=this.seekCount),this.pauseCount>0&&(r.pauseCount=this.pauseCount),this.firstAudioMs>0&&(r.firstAudioMs=Math.round(this.firstAudioMs)),this.waitingTotalMs>0&&(r.waitingForLiveMs=Math.round(this.waitingTotalMs)),this.timeToFirstStallMs>0&&(r.timeToFirstStallMs=Math.round(this.timeToFirstStallMs));let s=n?.positionMs??0;s>0&&(r.exitPositionMs=Math.round(s)),this.activeTotalMs>0&&(r.activeWatchTimeMs=Math.round(this.activeTotalMs)),this.mutedTotalMs>0&&(r.mutedTimeMs=Math.round(this.mutedTotalMs));let c=e!==`END_REASON_ENDED`;c&&this.lastStallMs>0&&t-this.lastStallMs<=G&&(r.abandonAfterStallMs=Math.max(W,Math.round(t-this.lastStallMs))),c&&this.lastErrorMs>0&&t-this.lastErrorMs<=G&&(r.abandonAfterErrorMs=Math.max(W,Math.round(t-this.lastErrorMs))),this.fullscreenTotalMs>0&&(r.fullscreenTimeMs=Math.round(this.fullscreenTotalMs)),this.pipTotalMs>0&&(r.pipTimeMs=Math.round(this.pipTotalMs)),this.volumeChanges>0&&(r.volumeChanges=this.volumeChanges),this.muteChanges>0&&(r.muteChanges=this.muteChanges);let l=n?.decodedFrames??this.lastDecoded;l>0&&(r.decodedFramesTotal=l),this.startupTimeMs===0&&(r.failedStage=this.lastErrorStage??(this.manifestLoadMs===0?`ERROR_STAGE_MANIFEST`:this.firstFragLoadMs===0?`ERROR_STAGE_FIRST_SEGMENT`:`ERROR_STAGE_OTHER`)),this.pending.push(this.wrap({sessionEnd:r})),this.flush(e===`END_REASON_PAGEHIDE`)}safeSample(){try{return this.opts.sample()}catch{return null}}wrap(e){return this.seq+=1,{sid:this.opts.sid,clientTime:new Date(this.now()).toISOString(),seq:this.seq,...e}}enqueue(e){for(this.pending.push(this.wrap(e));this.pending.length>dt;){let e=this.pending.findIndex(e=>e.heartbeat||e.stateChange);this.pending.splice(e>=0?e:0,1)}}flush(e=!1){if(this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.pendingStart=null,this.pending.length===0)return;let t=JSON.stringify({beacons:this.pending});if(this.pending=[],e){let e=this.opts.sendBeacon??(typeof navigator<`u`&&navigator.sendBeacon?navigator.sendBeacon.bind(navigator):void 0);if(e&&e(this.url,t))return}let n=this.opts.fetchFn??(typeof fetch<`u`?fetch:void 0);n&&n(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:t,keepalive:!0}).catch(()=>{})}};function yt(){if(typeof window>`u`)return{integration:`INTEGRATION_KIND_SDK`};let e;try{e=window.top!==window.self}catch{e=!0}let t=window.location?.origin;if(!e)return{host:t&&t!==`null`?t:void 0,integration:`INTEGRATION_KIND_SDK`};let n;try{let e=window.location.ancestorOrigins;e&&e.length>0&&(n=e[e.length-1]??void 0),!n&&typeof document<`u`&&document.referrer&&(n=new URL(document.referrer).origin)}catch{n=void 0}return n===`null`&&(n=void 0),{host:n,integration:`INTEGRATION_KIND_IFRAME`}}function bt(){if(typeof navigator>`u`)return`DEVICE_CLASS_OTHER`;let e=navigator.userAgentData,t=e?.platform??``;if(/tv|tizen|webos/i.test(t))return`DEVICE_CLASS_TV`;let n=typeof screen<`u`?Math.min(screen.width,screen.height):0;return e?.mobile??(typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1&&n>0&&n<900)?n>=600?`DEVICE_CLASS_TABLET`:`DEVICE_CLASS_PHONE`:e||n>=900||/mac|win|linux|chrome os/i.test(t)?`DEVICE_CLASS_DESKTOP`:`DEVICE_CLASS_OTHER`}function xt(){let e=typeof navigator<`u`?navigator.connection:void 0;if(!e)return{connectionType:`CONNECTION_TYPE_UNKNOWN`};let t={wifi:`CONNECTION_TYPE_WIFI`,cellular:`CONNECTION_TYPE_CELLULAR`,ethernet:`CONNECTION_TYPE_ETHERNET`},n={"slow-2g":`RADIO_ACCESS_ESTIMATED_SLOW_2G`,"2g":`RADIO_ACCESS_ESTIMATED_2G`,"3g":`RADIO_ACCESS_ESTIMATED_3G`,"4g":`RADIO_ACCESS_ESTIMATED_4G`},r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,i={connectionType:e.type?r(t,e.type)??`CONNECTION_TYPE_OTHER`:`CONNECTION_TYPE_UNKNOWN`};if(e.effectiveType){let t=r(n,e.effectiveType);t&&(i.radioAccess=t)}return typeof e.downlink==`number`&&e.downlink>0&&(i.downlinkKbps=Math.round(e.downlink*1e3)),typeof e.rtt==`number`&&e.rtt>0&&(i.rttMs=Math.round(e.rtt)),e.saveData&&(i.saveData=!0),i}function St(e){let t=yt(),n={deviceClass:bt(),integration:t.integration,...xt()};t.host&&(n.host=t.host),typeof screen<`u`&&screen.width>0&&(n.screenWidth=screen.width,n.screenHeight=screen.height),typeof window<`u`&&window.devicePixelRatio>0&&(n.devicePixelRatio=Math.round(window.devicePixelRatio*100)/100);let r=e.getBoundingClientRect?.();return r&&r.width>0&&(n.viewportWidth=Math.round(r.width),n.viewportHeight=Math.round(r.height)),n}async function Ct(){let e=typeof navigator<`u`?navigator.userAgentData:void 0;if(!e?.getHighEntropyValues)return{};try{let t=await e.getHighEntropyValues([`model`,`platformVersion`]),n={};return t.model&&(n.deviceModel=t.model),t.platformVersion&&(n.osVersion=t.platformVersion),n}catch{return{}}}var wt=`2.6.4`,J={accent:`#E1B600`,accentText:`#1B1C23`,background:`#0e0f13`,surface:`#1B1C23`,surfaceMuted:`#2a2c36`,text:`#ffffff`,textMuted:`#9aa0ad`,border:`rgba(255, 255, 255, 0.1)`,radius:`8px`,fontFamily:`ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`},Y={accent:`--havik-accent`,accentText:`--havik-accent-text`,background:`--havik-bg`,surface:`--havik-surface`,surfaceMuted:`--havik-surface-muted`,text:`--havik-text`,textMuted:`--havik-text-muted`,border:`--havik-border`,radius:`--havik-radius`,fontFamily:`--havik-font`};function X(e,t){let n={...J,...t};for(let t of Object.keys(Y))e.style.setProperty(Y[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var Z=`havik-player-styles`,Tt=`
4
4
  .havik-player{position:relative;display:block;width:100%;background:var(--havik-bg,#0e0f13);
5
5
  color:var(--havik-text,#fff);font-family:var(--havik-font,system-ui,sans-serif);
6
6
  overflow:hidden;line-height:1.4;-webkit-tap-highlight-color:transparent}
@@ -124,5 +124,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
124
124
  .havik-menu__item:hover{background:var(--havik-surface-muted,#2a2c36)}
125
125
  .havik-menu__item[aria-checked="true"]{color:var(--havik-accent,#E1B600);font-weight:600}
126
126
  .havik-menu__item[aria-checked="true"]::after{content:'✓'}
127
- `;function wt(e=document){if(e.getElementById(Z))return;let t=e.createElement(`style`);t.id=Z,t.textContent=Ct,e.head.appendChild(t)}var Tt={play:`<path d="M8 5v14l11-7z"/>`,pause:`<path d="M6 5h4v14H6zM14 5h4v14h-4z"/>`,volumeHigh:`<path d="M3 10v4h4l5 5V5L7 10H3zm13.5 2a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zm-2.5-9v2.06A7 7 0 0 1 14 19v2a9 9 0 0 0 0-18z"/>`,volumeMute:`<path d="M3 10v4h4l5 5V5L7 10H3zm16.5 2 2.5-2.5-1.4-1.4L18 10.6 15.4 8 14 9.4l2.6 2.6L14 14.6l1.4 1.4 2.6-2.6 2.6 2.6 1.4-1.4z"/>`,cc:`<path d="M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM10 11H8.5v-.5h-2v3h2V13H10v1a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H17v1a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1z"/>`,settings:`<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.11-.2.06-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>`,pip:`<path d="M19 7h-8v6h8V7zm4 12V5a2 2 0 0 0-2-2H3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2zm-2 .02H3V4.98h18v14.04z"/>`,fullscreen:`<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>`,fullscreenExit:`<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>`,liveDot:`<circle cx="12" cy="12" r="6"/>`,retry:`<path d="M17.65 6.35A8 8 0 1 0 19.73 13h-2.08A6 6 0 1 1 12 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>`};function Q(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Tt[e]}</svg>`}var Et=3e3,Dt=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`]);function Ot(e){return new kt(e)}var kt=class{root;video;player;doc;autoHideMs;overlay;center;spinner;bar;gradient;seek;seekBuffered;seekPlayed;seekThumb;playBtn;muteBtn;volSlider;live;liveGo;time;ccBtn;audioBtn;qualityBtn;pipBtn;fsBtn;menu;statusBox=null;statusKind=null;statusMsg=null;hasPlayed=!1;lastError=null;logoUrl;statusOverlays;endedMessage;interruptedMessage;errorMessage;hideTimer;openMenu=null;scrubbing=!1;offFns=[];constructor(e){this.root=e.root,this.video=e.video,this.player=e.player,this.doc=e.root.ownerDocument??document,this.autoHideMs=e.autoHideMs??Et,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.endedMessage=e.endedMessage??`This stream has ended`,this.interruptedMessage=e.interruptedMessage??`Reconnecting — please stand by`,this.errorMessage=e.errorMessage,wt(this.doc),this.root.classList.add(`havik-player`),this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=0),this.root.setAttribute(`role`,`region`),this.root.setAttribute(`aria-label`,`Video player`);let t=(e,t,n)=>{let r=this.doc.createElement(e);if(r.className=t,n)for(let[e,t]of Object.entries(n))r.setAttribute(e,t);return r},n=(e,n,r)=>{let i=t(`button`,e,{type:`button`,"aria-label":r,title:r});return i.innerHTML=Q(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Q(`play`),this.spinner=t(`div`,`havik-spinner`),this.spinner.style.display=`none`,this.overlay.append(this.center,this.spinner),this.gradient=t(`div`,`havik-gradient`),this.bar=t(`div`,`havik-bar`),this.seek=t(`div`,`havik-seek`,{role:`slider`,"aria-label":`Seek`,"aria-valuemin":`0`,"aria-valuemax":`100`,tabindex:`0`});let r=t(`div`,`havik-seek__track`);this.seekBuffered=t(`div`,`havik-seek__buffered`),this.seekPlayed=t(`div`,`havik-seek__played`),this.seekThumb=t(`div`,`havik-seek__thumb`),r.append(this.seekBuffered,this.seekPlayed,this.seekThumb),this.seek.append(r);let i=t(`div`,`havik-controls`);this.playBtn=n(`havik-btn`,`play`,`Play`),this.muteBtn=n(`havik-btn`,`volumeHigh`,`Mute`),this.volSlider=t(`input`,`havik-vol__slider`,{type:`range`,min:`0`,max:`1`,step:`0.05`,"aria-label":`Volume`});let a=t(`div`,`havik-vol`);a.append(this.muteBtn,this.volSlider),this.live=t(`div`,`havik-live`),this.live.innerHTML=Q(`liveDot`);let o=this.doc.createElement(`span`);o.textContent=`LIVE`,this.liveGo=t(`button`,`havik-live__go`,{type:`button`}),this.liveGo.textContent=`Go live`,this.live.append(o,this.liveGo),this.time=t(`div`,`havik-time`),this.time.textContent=`0:00`,this.time.style.display=`none`;let s=t(`div`,`havik-spacer`);if(this.ccBtn=n(`havik-btn`,`cc`,`Subtitles`),this.audioBtn=n(`havik-btn`,`settings`,`Audio track`),this.qualityBtn=n(`havik-btn`,`settings`,`Quality`),this.pipBtn=n(`havik-btn`,`pip`,`Picture in picture`),this.fsBtn=n(`havik-btn`,`fullscreen`,`Fullscreen`),this.ccBtn.style.display=`none`,this.audioBtn.style.display=`none`,this.qualityBtn.style.display=`none`,this.pipSupported()||(this.pipBtn.style.display=`none`),i.append(this.playBtn,a,this.live,this.time,s,this.ccBtn,this.audioBtn,this.qualityBtn,this.pipBtn,this.fsBtn),this.bar.append(this.seek,i),this.menu=t(`div`,`havik-menu`,{role:`menu`}),this.menu.hidden=!0,this.root.append(this.gradient,this.overlay,this.bar,this.menu),e.logoUrl){let n=t(`div`,`havik-watermark`);n.style.backgroundImage=`url("${e.logoUrl}")`,this.root.append(n)}this.wire(),this.syncPlayPause(),this.syncVolume(),this.scheduleHide()}on(e,t,n,r){e.addEventListener(t,n,r),this.offFns.push(()=>e.removeEventListener(t,n,r))}wire(){let e=this.video;this.on(this.playBtn,`click`,()=>this.togglePlay()),this.on(this.center,`click`,()=>this.togglePlay()),this.on(this.overlay,`click`,e=>{e.target===this.overlay&&this.togglePlay()}),this.on(this.muteBtn,`click`,()=>this.player.setMuted(!e.muted)),this.on(this.volSlider,`input`,()=>{let t=Number(this.volSlider.value);this.setVolumeFill(t),this.player.setVolume(t),t>0&&e.muted&&this.player.setMuted(!1)}),this.on(this.liveGo,`click`,()=>this.player.seekToLive()),this.on(this.pipBtn,`click`,()=>void this.togglePip()),this.on(this.fsBtn,`click`,()=>void this.toggleFullscreen()),this.on(this.ccBtn,`click`,()=>this.toggleMenu(`cc`)),this.on(this.audioBtn,`click`,()=>this.toggleMenu(`audio`)),this.on(this.qualityBtn,`click`,()=>this.toggleMenu(`quality`)),this.on(this.seek,`pointerdown`,e=>this.onSeekDown(e)),this.on(this.seek,`keydown`,e=>this.onSeekKey(e)),this.on(e,`play`,()=>this.syncPlayPause()),this.on(e,`pause`,()=>this.syncPlayPause()),this.on(e,`volumechange`,()=>this.syncVolume()),this.on(e,`timeupdate`,()=>this.syncProgress()),this.on(e,`progress`,()=>this.syncProgress()),this.on(e,`durationchange`,()=>this.syncProgress()),this.offFns.push(this.player.on(`statechange`,()=>this.syncState())),this.offFns.push(this.player.on(`ended`,()=>this.syncState())),this.offFns.push(this.player.on(`ready`,()=>this.refreshTracks())),this.offFns.push(this.player.on(`qualitychange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`audiotrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`texttrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`pipchange`,e=>this.syncPip(e))),this.offFns.push(this.player.on(`stats`,()=>this.syncLive())),this.offFns.push(this.player.on(`error`,e=>{this.lastError=e,this.statusKind=null,this.syncState()})),this.on(this.root,`pointermove`,()=>this.poke()),this.on(this.root,`pointerleave`,()=>this.scheduleHide(0)),this.on(this.root,`focusin`,()=>this.poke()),this.on(this.root,`keydown`,e=>this.onKey(e)),this.on(this.doc,`pointerdown`,e=>this.onDocPointer(e),{capture:!0}),this.on(this.doc,`fullscreenchange`,()=>this.syncFullscreen()),this.on(this.doc,`webkitfullscreenchange`,()=>this.syncFullscreen()),this.on(e,`webkitbeginfullscreen`,()=>this.syncFullscreen()),this.on(e,`webkitendfullscreen`,()=>this.syncFullscreen()),this.syncState()}togglePlay(){this.video.paused||this.video.ended?this.player.play():this.player.pause()}syncPlayPause(){let e=!this.video.paused&&!this.video.ended;this.setIcon(this.playBtn,e?`pause`:`play`),this.playBtn.setAttribute(`aria-label`,e?`Pause`:`Play`),this.setIcon(this.center,e?`pause`:`play`),this.center.classList.toggle(`havik-gone`,e||!!this.statusBox),e?this.scheduleHide():this.show()}syncState(){let e=this.player.state;(e===`playing`||e===`buffering`)&&(this.hasPlayed=!0),this.syncStatus(e);let t=e===`loading`||e===`buffering`;this.spinner.style.display=t&&!this.statusBox?``:`none`,(t||this.statusBox)&&this.center.classList.add(`havik-gone`),this.syncLive()}syncStatus(e){let t=null;this.statusOverlays&&(e===`ended`?t=`ended`:e===`error`?t=`error`:e===`waiting`?t=`waiting`:!this.hasPlayed&&(e===`idle`||e===`paused`)&&(t=`preplay`)),this.renderStatus(t)}statusMessageFor(e){return e===`ended`?this.player.endedReason===`interrupted`?this.interruptedMessage:this.endedMessage:e===`waiting`?this.hasPlayed?`Reconnecting — please stand by`:`Starting soon…`:e===`error`?this.errorMessage??this.lastError?.message??`Playback unavailable`:null}renderStatus(e){let t=this.statusMessageFor(e);if(e===this.statusKind&&t===this.statusMsg||(this.statusKind=e,this.statusMsg=t,this.statusBox?.remove(),this.statusBox=null,this.root.classList.toggle(`havik-has-status`,!!e),!e))return;let n=this.doc.createElement(`div`);if(n.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,n.append(e)}if(e===`preplay`){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn havik-status__btn--play`,e.setAttribute(`aria-label`,`Play`),e.innerHTML=Q(`play`),e.addEventListener(`click`,()=>void this.player.play()),n.append(e)}else{let r=this.doc.createElement(`div`);if(r.className=`havik-status__msg`,r.textContent=t??``,n.append(r),e===`error`&&this.lastError&&!Dt.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Q(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),n.append(e)}}this.root.append(n),this.statusBox=n,this.show()}syncVolume(){let e=this.video,t=e.muted||e.volume===0;this.setIcon(this.muteBtn,t?`volumeMute`:`volumeHigh`),this.muteBtn.setAttribute(`aria-label`,t?`Unmute`:`Mute`);let n=t?0:e.volume;this.volSlider.value=String(n),this.setVolumeFill(n)}setVolumeFill(e){this.volSlider.style.setProperty(`--havik-vol`,String(Math.min(1,Math.max(0,e))))}seekableRange(){let e=this.video,t,n;if(e.seekable&&e.seekable.length>0)t=e.seekable.start(0),n=e.seekable.end(e.seekable.length-1);else if(Number.isFinite(e.duration)&&e.duration>0)t=0,n=e.duration;else return null;let r=this.player.getStats();return r.isLive!==!1&&r.targetLatencySeconds&&r.targetLatencySeconds>0&&(n=Math.max(t,n-r.targetLatencySeconds)),n>t?{start:t,end:n}:null}syncProgress(){if(this.scrubbing)return;let e=this.seekableRange();if(!e){this.seekPlayed.style.width=`100%`;return}let t=e.end-e.start,n=Math.min(1,Math.max(0,(this.video.currentTime-e.start)/t));this.seekPlayed.style.width=`${(n*100).toFixed(2)}%`,this.seekThumb.style.left=`${(n*100).toFixed(2)}%`,this.seek.setAttribute(`aria-valuenow`,String(Math.round(n*100)));let r=this.video.buffered;if(r&&r.length>0){let n=r.end(r.length-1),i=Math.min(1,Math.max(0,(n-e.start)/t));this.seekBuffered.style.width=`${(i*100).toFixed(2)}%`}!this.player.getStats().isLive&&Number.isFinite(this.video.duration)&&(this.time.textContent=`${At(this.video.currentTime)} / ${At(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1;this.live.style.display=t?``:`none`,this.time.style.display=t?`none`:``,this.live.classList.toggle(`is-live`,e.atLiveEdge!==!1&&t)}onSeekDown(e){let t=this.seekableRange();if(!t)return;e.preventDefault(),this.scrubbing=!0;let n=e=>this.seekToPointer(e,t),r=()=>{this.scrubbing=!1,this.doc.removeEventListener(`pointermove`,n),this.doc.removeEventListener(`pointerup`,r)};this.doc.addEventListener(`pointermove`,n),this.doc.addEventListener(`pointerup`,r),this.seekToPointer(e,t)}seekToPointer(e,t){let n=this.seek.getBoundingClientRect(),r=n.width>0?Math.min(1,Math.max(0,(e.clientX-n.left)/n.width)):0;this.seekPlayed.style.width=`${(r*100).toFixed(2)}%`,this.seekThumb.style.left=`${(r*100).toFixed(2)}%`,this.video.currentTime=t.start+r*(t.end-t.start)}onSeekKey(e){e.key===`ArrowLeft`?(this.nudge(-5),e.preventDefault()):e.key===`ArrowRight`&&(this.nudge(5),e.preventDefault())}nudge(e){let t=this.seekableRange();t&&(this.video.currentTime=Math.min(t.end,Math.max(t.start,this.video.currentTime+e)))}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e,this.renderMenu(e),this.menu.hidden=!1,this.show()}closeMenu(){this.openMenu=null,this.menu.hidden=!0,this.menu.replaceChildren()}renderMenu(e){e===`quality`?this.renderQualityMenu():e===`audio`?this.renderAudioMenu():this.renderCcMenu()}menuItem(e,t,n){let r=this.doc.createElement(`button`);r.type=`button`,r.className=`havik-menu__item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,t?`true`:`false`);let i=this.doc.createElement(`span`);return i.textContent=e,r.append(i),r.addEventListener(`click`,()=>{n(),this.closeMenu()}),r}renderQualityMenu(){let e=this.player.getQualityLevels(),t=this.player.getCurrentQuality(),n=this.doc.createElement(`div`);n.className=`havik-menu__title`,n.textContent=`Quality`,this.menu.replaceChildren(n,this.menuItem(`Auto`,t===-1,()=>this.player.setQuality(`auto`)));for(let n of e)this.menu.append(this.menuItem(jt(n),t===n.index,()=>this.player.setQuality(n.index)))}renderAudioMenu(){let e=this.player.getAudioTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Audio`,this.menu.replaceChildren(t);for(let t of e)this.menu.append(this.menuItem(Mt(t),t.default,()=>this.player.setAudioTrack(t.id)))}renderCcMenu(){let e=this.player.getTextTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Subtitles`,this.menu.replaceChildren(t,this.menuItem(`Off`,!1,()=>this.player.setTextTrack(-1)));for(let t of e)this.menu.append(this.menuItem(Nt(t),!1,()=>this.player.setTextTrack(t.id)))}onTracksChanged(){this.openMenu&&this.renderMenu(this.openMenu)}refreshTracks(){let e=this.player.getQualityLevels(),t=this.player.getAudioTracks(),n=this.player.getTextTracks();this.qualityBtn.style.display=e.length>1?``:`none`,this.audioBtn.style.display=t.length>1?``:`none`,this.ccBtn.style.display=n.length>0?``:`none`,this.onTracksChanged()}pipSupported(){return`pictureInPictureEnabled`in this.doc&&typeof this.video.requestPictureInPicture==`function`}async togglePip(){this.doc.pictureInPictureElement===this.video?await this.player.exitPictureInPicture():await this.player.enterPictureInPicture()}syncPip(e){this.pipBtn.setAttribute(`aria-pressed`,e?`true`:`false`)}async toggleFullscreen(){try{C(this.video,this.root)?await T(this.video,this.root):await w(this.video,this.root)}catch{}}syncFullscreen(){let e=C(this.video,this.root);this.setIcon(this.fsBtn,e?`fullscreenExit`:`fullscreen`),this.fsBtn.setAttribute(`aria-label`,e?`Exit fullscreen`:`Fullscreen`)}poke(){this.show(),this.scheduleHide()}show(){this.root.classList.remove(`havik-hide`)}scheduleHide(e=this.autoHideMs){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{!this.video.paused&&!this.video.ended&&!this.openMenu&&!this.statusBox&&this.root.classList.add(`havik-hide`)},e)}onDocPointer(e){this.openMenu&&!this.menu.contains(e.target)&&([this.qualityBtn,this.audioBtn,this.ccBtn].some(t=>t.contains(e.target))||this.closeMenu())}onKey(e){let t=e.target;if(!(t&&t!==this.root&&t!==this.seek&&t.tagName===`INPUT`)){switch(e.key){case` `:case`k`:this.togglePlay();break;case`m`:this.player.setMuted(!this.video.muted);break;case`f`:this.toggleFullscreen();break;case`c`:this.ccBtn.style.display!==`none`&&this.toggleMenu(`cc`);break;case`l`:this.player.seekToLive();break;case`ArrowUp`:this.player.setVolume(Math.min(1,this.video.volume+.1));break;case`ArrowDown`:this.player.setVolume(Math.max(0,this.video.volume-.1));break;case`ArrowLeft`:this.nudge(-5);break;case`ArrowRight`:this.nudge(5);break;default:return}this.poke(),e.preventDefault()}}setIcon(e,t){e.innerHTML=Q(t)}destroy(){this.hideTimer&&clearTimeout(this.hideTimer);for(let e of this.offFns)try{e()}catch{}this.offFns.length=0,this.closeMenu(),this.statusBox?.remove();for(let e of[this.overlay,this.gradient,this.bar,this.menu])e.remove();this.root.classList.remove(`havik-player`,`havik-hide`,`havik-has-status`)}};function At(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=Math.floor(e%60),n=Math.floor(e/60%60),r=Math.floor(e/3600),i=r>0?String(n).padStart(2,`0`):String(n),a=String(t).padStart(2,`0`);return r>0?`${r}:${i}:${a}`:`${i}:${a}`}function jt(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function Mt(e){return e.name||e.lang||`Track ${e.id}`}function Nt(e){return e.name||e.lang||`Track ${e.id}`}var Pt=6e3,Ft=45e3,It=2e3,Lt=3,Rt=2e3,zt=48e4;async function Bt(e){if(!e.video||typeof e.video.play!=`function`)throw new l(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);if(!e.baseUrl)throw new l(`INTERNAL`,0,`createPlayer: baseUrl is required`);if(!e.matchUrn)throw new l(`INVALID_URN`,0,`createPlayer: matchUrn is required`);if(!e.credential)throw new l(`INTERNAL`,0,`createPlayer: credential is required`);let t=new Vt(e);return await t.start(),t}var Vt=class{opts;abort=new AbortController;listeners={};engine=null;controlBar=null;container=null;detachMedia;detachPip;statsTimer;refreshTimer;_state=`idle`;_descriptor=null;destroyed=!1;loadGen=0;liveStateSub=null;endedHandled=!1;_endedReason=null;rejoinTimer=null;armingSub=null;armSseTimer=null;armFallbackCtrl=null;_lastError=null;analyticsSession=null;detachMediaListeners;playRequested=!1;pendingStartLoad=!1;constructor(e){this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}get endedReason(){return this._endedReason}async start(){this.opts.muted&&(this.opts.video.muted=!0),this.opts.poster&&(this.opts.video.poster=this.opts.poster),this.mountControls(),this.attachPipListeners(),this.setState(`loading`);let e=++this.loadGen,t=this.resolveOptions();try{let n=await v(t);if(await this.onResolved(n,e),e===this.loadGen&&this._state===`error`&&this._lastError){let e=this._lastError;throw this.destroy(),e}}catch(t){if(this.opts.waitForLive&&t instanceof l&&p(t.code)){this.setState(`waiting`),this.beginArming(e,t.liveStartsAtMs);return}throw t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal,apiHeaders:this.opts.apiHeaders}}beginArming(e,t,n=!1){let r=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??D(this.opts.baseUrl);r?this.armWithSse(e,r,t,n):this.beginArmingByPolling(e)}beginArmingByPolling(e){y({...this.resolveOptions(),signal:this.abort.signal,waitForLive:this.buildWaitConfig(e)}).then(t=>{if(!(this.destroyed||this.abort.signal.aborted||e!==this.loadGen))return this.onResolved(t,e)}).catch(t=>{this.destroyed||this.abort.signal.aborted||e!==this.loadGen||this.fail(t instanceof l?t:new l(`INTERNAL`,0,String(t)))})}armWithSse(e,t,n,r=!1){let i=!1,a=!1,o=new AbortController;this.armFallbackCtrl=o,this.setState(`waiting`);let s=this.opts.waitForLive,c=s&&s!==!0?s.kickoffAt:void 0,u=typeof c==`number`?c:typeof c==`string`?Date.parse(c):NaN,d=n??(Number.isFinite(u)?u:void 0);setTimeout(()=>{i||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:r?`unavailable`:`tooEarly`,retryInMs:Ft,attempt:1,elapsedMs:0,...!r&&d!==void 0&&d>Date.now()?{ttkMs:d-Date.now()}:{}})},0);let f=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,m=async t=>{if(!(i||f())){i=!0,this.closeArming(),o.abort();try{await this.onResolved(t,e)}catch(e){if(f())return;this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e)))}}},h=()=>{i||a||f()||(a=!0,y({...this.resolveOptions(),signal:o.signal,waitForLive:this.buildWaitConfig(e)}).then(e=>m(e)).catch(e=>{i||f()||o.signal.aborted||(i=!0,this.closeArming(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))}))},g=()=>{i||f()||v(this.resolveOptions()).then(e=>m(e)).catch(e=>{if(!(i||f())){if(e instanceof l&&p(e.code)){h();return}i=!0,this.closeArming(),o.abort(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e)))}})},_=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!i&&!f()&&h()},e)};_(Pt),this.armingSub=E({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(Ft),onState:e=>{i||f()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*It)},onError:()=>h()})}closeArming(){this.armSseTimer&&=(clearTimeout(this.armSseTimer),null),this.armFallbackCtrl?.abort(),this.armFallbackCtrl=null,this.armingSub?.close(),this.armingSub=null}buildWaitConfig(e){let t=this.opts.waitForLive&&this.opts.waitForLive!==!0?this.opts.waitForLive:{};return{...t,onState:n=>{this.destroyed||e!==this.loadGen||(this.setState(`waiting`),this.emit(`waiting`,n),t.onState?.(n))}}}async onResolved(e,t){if(this.destroyed||t!==this.loadGen)return;this._descriptor=e,this.endedHandled=!1,this._endedReason=null;let n=await m(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.opts.autoplay===!1&&!this.playRequested,i=this.createEngine(e,n,r),a=ze(this.opts.video,e=>{this._state!==`ended`&&this._state!==`error`&&this.setState(e)});if(await i.load(),this.destroyed||t!==this.loadGen){a(),i.destroy();return}if(this._state===`error`){a(),i.destroy();return}this.engine=i,this.detachMedia=a,this.opts.maxBitrate!=null&&i.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t),this.startAnalytics(e,i),r&&(this.pendingStartLoad=!0,this.setState(`paused`),i.name===`native`&&setTimeout(()=>{this.destroyed||t!==this.loadGen||this.engine!==i||(this.analyticsSession?.noteReady(),this.emit(`ready`))},0))}startAnalytics(e,t){if(this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.opts.analytics===!1)return;let n=e.analytics?.sid;if(!n)return;let r=(typeof this.opts.analytics==`object`?this.opts.analytics.endpoint:void 0)??ht(this.opts.baseUrl);if(!r)return;let i=this.opts.video,a=new gt({endpoint:r,sid:n,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:St,environment:bt(i),sample:()=>{let e=this.engine?.getStats()??I,t=i.buffered.length?Math.max(0,i.buffered.end(i.buffered.length-1)-i.currentTime):0;return{...e,bufferedMs:Math.round(t*1e3),state:this._state,positionMs:Math.round(i.currentTime*1e3),playbackRate:i.playbackRate}}});this.analyticsSession=a;let o=()=>a.noteSeek(),s=()=>a.noteVolume(i.muted,i.volume);i.addEventListener(`seeking`,o),i.addEventListener(`volumechange`,s),this.detachMediaListeners=()=>{i.removeEventListener(`seeking`,o),i.removeEventListener(`volumechange`,s)},a.start(),a.seedVolume(i.muted,i.volume),a.notePresentation(this.currentPresentation()),xt().then(e=>a.noteEnvironment(e)),this.opts.autoplay===!1&&a.noteAutoplay(`AUTOPLAY_RESULT_NOT_ATTEMPTED`)}currentPresentation(){let e=this.opts.video;if(typeof document<`u`&&document.pictureInPictureElement===e)return`pip`;let t=typeof document<`u`?document.fullscreenElement:null;return e.webkitDisplayingFullscreen===!0||t&&(t===e||t.contains(e))?`fullscreen`:`inline`}createEngine(e,t,n=!1){let r={...this.opts.hlsConfig};this.opts.startLevel!=null&&(r.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(r.liveSyncDuration=this.opts.liveLatencyTarget);let i={video:this.opts.video,descriptor:e,credential:t,deviceId:A(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,debug:this.opts.debug,deferLoad:n,hlsConfig:r,emit:e=>this.onEngineEvent(e)},a=this.opts.engine??`auto`;if(a===`native`)return new V(i);if(a===`hls`)return new U(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&z(this.opts.video)&&B())return new V(i);if(He())return new U(i);if(z(this.opts.video))return new V(i);throw new l(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`ready`:this.analyticsSession?.noteReady(),this.emit(`ready`),(this.opts.autoplay!==!1||this.playRequested)&&this.play();break;case`lowLatencyDetected`:this._descriptor&&(this._descriptor.isLowLatency=e.value);break;case`qualitychange`:this.emit(`qualitychange`,e.index);break;case`audiotrackchange`:this.emit(`audiotrackchange`,e.id);break;case`texttrackchange`:this.emit(`texttrackchange`,e.id);break;case`ended`:this.onStreamEnded();break;case`error`:this.analyticsSession?.noteError(e.error.code,e.error.message,e.fatal,e.error.httpStatus??0,Math.round(this.opts.video.currentTime*1e3),e.detail),e.fatal?this.fail(e.error):this.emit(`warning`,e.error)}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??D(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=E({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`gone`?this.onStreamEnded(!0,t.reason??`match_ended`):t.state===`ended`?this.onStreamEnded(!1,t.reason):t.state===`live`&&this.endedHandled&&this.scheduleRejoin(e))},onAlive:()=>{n=0,r=!1},onError:()=>{this.destroyed||e!==this.loadGen||r||this.endedHandled||(n+=1,n>=Lt&&(r=!0,this.emit(`warning`,new l(`NETWORK`,0,`live-state events unreachable at ${t} after ${n} attempts — end-of-stream detection degraded to the HLS staleness watchdog. Check the events host, the api-key's allowed origins, and CSP connect-src.`))))}})}closeLiveState(){this.liveStateSub?.close(),this.liveStateSub=null}onStreamEnded(e=!1,t){if(!this.destroyed){if((e||!this.rejoinEnabled())&&(this.cancelRejoin(),this.closeLiveState()),this.endedHandled){t===`match_ended`&&this._endedReason!==`match_ended`&&(this._endedReason=t,this.emit(`ended`,t));return}this.endedHandled=!0,this._endedReason=t??null,this.stopRefresh(),this.pendingStartLoad=!1,this.engine?.stop(),this.setState(`ended`)}}rejoinEnabled(){return this.opts.rejoinOnLive!==!1&&this.opts.liveStateEvents!==!1}scheduleRejoin(e){this.rejoinEnabled()&&!this.rejoinTimer&&(this.rejoinTimer=setTimeout(()=>{this.rejoinTimer=null,!(this.destroyed||e!==this.loadGen||this._state!==`ended`)&&this.rejoin()},Math.random()*It))}cancelRejoin(){this.rejoinTimer&&=(clearTimeout(this.rejoinTimer),null)}rejoin(){let e=++this.loadGen;this.teardownPlayback(),this.setState(`waiting`),this.beginArming(e,void 0,!0)}teardownPlayback(){this.stopStats(),this.stopRefresh(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null,this.pendingStartLoad=!1}mountControls(){let e=this.opts.controls??`custom`,t=this.opts.video;if(e===`native`){t.controls=!0;return}if(e===`none`){t.controls=!1;return}t.controls=!1;let n=(t.ownerDocument??document).createElement(`div`),r=t.parentNode;r&&r.insertBefore(n,t),n.appendChild(t),X(n,this.opts.theme),this.container=n,this.controlBar=Ot({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,interruptedMessage:this.opts.interruptedMessage,errorMessage:this.opts.errorMessage})}unmountControls(){this.controlBar?.destroy(),this.controlBar=null;let e=this.container;e&&(e.parentNode?(e.parentNode.insertBefore(this.opts.video,e),e.remove()):this.opts.video.parentNode===e&&e.removeChild(this.opts.video)),this.container=null}attachPipListeners(){let e=this.opts.video,t=()=>this.analyticsSession?.notePresentation(this.currentPresentation()),n=()=>{t(),this.emit(`pipchange`,!0)},r=()=>{t(),this.emit(`pipchange`,!1)};e.addEventListener(`enterpictureinpicture`,n),e.addEventListener(`leavepictureinpicture`,r);let i=typeof document<`u`?document:void 0;i?.addEventListener(`fullscreenchange`,t),i?.addEventListener(`webkitfullscreenchange`,t),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,n),e.removeEventListener(`leavepictureinpicture`,r),i?.removeEventListener(`fullscreenchange`,t),i?.removeEventListener(`webkitfullscreenchange`,t)}}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??Rt);this.statsTimer=setInterval(()=>{if(!this.engine)return;let e=this.engine.getStats();(e.bytesLoaded??0)>0&&this.analyticsSession?.noteFirstBytes(),this.emit(`stats`,e)},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}scheduleLicenseRefresh(){this.stopRefresh();let e=this.opts.licenseRefreshMs??zt;e&&this._descriptor?.drmEnabled&&(this.refreshTimer=setInterval(()=>void this.refreshLicense(),e))}stopRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=void 0}async refreshLicense(){let e=this.engine;if(!this.destroyed&&e)try{let t=await v(this.resolveOptions());if(this.destroyed||this.engine!==e)return;let n=t.drm?.widevine?.licenseUrl,r=t.drm?.fairplay?.licenseUrl;(n||r)&&(e.setLicenseUrls({widevine:n,fairplay:r}),this._descriptor=t)}catch(e){e instanceof l&&!p(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e))}}async play(){if(this.destroyed)return;let e=!this.playRequested;this.playRequested=!0;let t=this.pendingStartLoad&&this._state!==`ended`&&this._state!==`error`;this.opts.autoplay===!1&&this.analyticsSession?.notePlayIntent(),t&&(this.pendingStartLoad=!1,this.setState(`loading`),this.engine?.startLoad());try{await this.opts.video.play(),e&&this.analyticsSession?.noteAutoplay(this.opts.video.muted?`AUTOPLAY_RESULT_ALLOWED_MUTED`:`AUTOPLAY_RESULT_ALLOWED`)}catch(n){n instanceof DOMException&&n.name===`NotAllowedError`&&(this.analyticsSession?.noteAutoplay(`AUTOPLAY_RESULT_BLOCKED`),e&&(this.playRequested=!1),t&&!this.destroyed&&this._state===`loading`&&this.setState(`paused`),this.emit(`autoplayblocked`))}}pause(){this.destroyed||this.opts.video.pause()}setMuted(e){this.destroyed||(this.opts.video.muted=e)}setVolume(e){this.destroyed||(this.opts.video.volume=Math.min(1,Math.max(0,e)))}getStats(){return this.engine?.getStats()??I}getQualityLevels(){return this.engine?.getQualityLevels()??[]}getCurrentQuality(){return this.engine?.getCurrentQuality()??-1}setQuality(e){this.destroyed||this.engine?.setQuality(e===`auto`?-1:e)}setMaxBitrate(e){this.destroyed||this.engine?.setMaxBitrate(e)}getAudioTracks(){return this.engine?.getAudioTracks()??[]}setAudioTrack(e){this.destroyed||this.engine?.setAudioTrack(e)}getTextTracks(){return this.engine?.getTextTracks()??[]}setTextTrack(e){this.destroyed||this.engine?.setTextTrack(e)}seekToLive(){this.destroyed||this.engine?.seekToLive()}async enterPictureInPicture(){if(this.destroyed)return;let e=this.opts.video;typeof e.requestPictureInPicture==`function`&&await e.requestPictureInPicture()}async exitPictureInPicture(){let e=document;e.pictureInPictureElement===this.opts.video&&typeof e.exitPictureInPicture==`function`&&await e.exitPictureInPicture()}async enterFullscreen(){return!this.destroyed&&w(this.opts.video,this.container??void 0)}async exitFullscreen(){await T(this.opts.video,this.container??void 0)}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.teardownPlayback();try{let t=await y({...this.resolveOptions(),waitForLive:this.opts.waitForLive?this.buildWaitConfig(e):void 0});if(await this.onResolved(t,e),e===this.loadGen&&this._state===`error`&&this._lastError)throw this._lastError}catch(t){if(this.destroyed||this.abort.signal.aborted||e!==this.loadGen)return;throw t!==this._lastError&&this.fail(t instanceof l?t:new l(`INTERNAL`,0,String(t))),t}}on(e,t){let n=this.listeners[e]??=new Set;return n.add(t),()=>n.delete(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadGen+=1,this.abort.abort(),this.stopStats(),this.stopRefresh(),this.unmountControls(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.detachPip?.(),this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.engine?.destroy(),this.engine=null,this.setState(`idle`),this.clearListeners())}clearListeners(){for(let e of Object.keys(this.listeners))this.listeners[e]?.clear()}fail(e){this._lastError=e,this.setState(`error`),this.analyticsSession?.noteFatal(),this.emit(`error`,e)}setState(e){if(e===this._state)return;let t=this._state;if(this._state=e,this.analyticsSession){let n=this.opts.video;this.analyticsSession.noteStateChange(t,e,Math.round(n.currentTime*1e3),this.engine?.getStats().levelHeight),e===`ended`&&this.analyticsSession.noteEnded()}switch(this.emit(`statechange`,e),e){case`playing`:this.emit(`playing`);break;case`buffering`:this.emit(`buffering`);break;case`paused`:this.emit(`paused`);break;case`ended`:this.emit(`ended`,this._endedReason??void 0)}}emit(e,t){this.listeners[e]?.forEach(e=>{try{e(t)}catch{}})}};function $(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function Ht(e){if(!e.container||typeof e.container.appendChild!=`function`)throw Error(`mountEmbed: opts.container must be a DOM element`);if(!e.src)throw Error(`mountEmbed: opts.src is required`);if(!e.baseUrl||!e.matchUrn)throw Error(`mountEmbed: opts.baseUrl and opts.matchUrn are required`);let t=new URL(e.src,location.href),n=e.allowedFrameOrigin??t.origin;t.searchParams.set(`baseUrl`,e.baseUrl),t.searchParams.set(`matchUrn`,e.matchUrn),t.searchParams.set(`parentOrigin`,location.origin),e.muted!=null&&t.searchParams.set(`muted`,String(e.muted)),e.apiKey&&(t.searchParams.set(`apiKey`,e.apiKey),console.warn(`havik-player: passing apiKey to mountEmbed places it in the iframe URL — DEV/DEMO only. In production inject it server-side into window.HAVIK_EMBED_CONFIG on the embed page.`));let r=document.createElement(`iframe`);r.src=t.toString(),r.allow=`autoplay; encrypted-media; fullscreen`,r.setAttribute(`allowfullscreen`,``),r.referrerPolicy=`no-referrer`,r.setAttribute(`sandbox`,e.sandbox??`allow-scripts allow-same-origin allow-presentation`),r.style.cssText=`border:0;width:100%;height:100%;display:block`,e.container.appendChild(r);let i=new Set,a=t=>{if(t.source!==r.contentWindow||t.origin!==n||!$(t.data))return;let a=t.data;a.type===`oddin:ready`&&a.protocol!==1&&console.warn(`havik-player: embed protocol v${a.protocol} != host v1. Pin the embed page version to the SDK version to avoid skew.`),e.onEvent?.(a),i.forEach(e=>e(a))};window.addEventListener(`message`,a);let o=e=>r.contentWindow?.postMessage(e,n);return{iframe:r,play:()=>o({type:`oddin:play`}),pause:()=>o({type:`oddin:pause`}),setMuted:e=>o({type:`oddin:setMuted`,muted:e}),setVolume:e=>o({type:`oddin:setVolume`,volume:e}),setQuality:e=>o({type:`oddin:setQuality`,index:e}),setMaxBitrate:e=>o({type:`oddin:setMaxBitrate`,bitrate:e}),setAudioTrack:e=>o({type:`oddin:setAudioTrack`,id:e}),setTextTrack:e=>o({type:`oddin:setTextTrack`,id:e}),seekToLive:()=>o({type:`oddin:seekToLive`}),enterPip:()=>o({type:`oddin:enterPip`}),exitPip:()=>o({type:`oddin:exitPip`}),retry:()=>o({type:`oddin:retry`}),load:e=>o({type:`oddin:load`,matchUrn:e}),on:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{o({type:`oddin:destroy`}),window.removeEventListener(`message`,a),r.remove()}}}var Ut=/^[A-Za-z0-9:_.-]{1,128}$/;function Wt(){let e=window.HAVIK_EMBED_CONFIG;if(e)return{baseUrl:e.baseUrl??``,matchUrn:e.matchUrn??``,apiKey:e.apiKey??``,parentOrigin:e.parentOrigin,autoplay:e.autoplay??!0,muted:e.muted??!0,waitForLive:e.waitForLive??!0};let t=new URLSearchParams(location.search);return{baseUrl:t.get(`baseUrl`)??``,matchUrn:t.get(`matchUrn`)??``,apiKey:t.get(`apiKey`)??``,parentOrigin:t.get(`parentOrigin`)??void 0,autoplay:!0,muted:t.get(`muted`)!==`false`,waitForLive:!0}}async function Gt(){let e=Wt();qt();let t=document.createElement(`video`);t.setAttribute(`playsinline`,``),t.muted=e.muted??!0,t.style.cssText=`width:100%;height:100%;object-fit:contain;background:#000;aspect-ratio:auto`,document.body.appendChild(t);let n=e.parentOrigin&&e.parentOrigin!==`null`?e.parentOrigin:null;n||console.warn(`havik-player: embed has no parentOrigin — the postMessage bridge is disabled (no events posted, no commands accepted). mountEmbed sets parentOrigin automatically.`);let r=e=>{if(n)try{window.parent?.postMessage(e,n)}catch{}};if(!e.baseUrl||!e.matchUrn||!e.apiKey){r({type:`oddin:error`,code:`INTERNAL`,message:`embed missing baseUrl/matchUrn/apiKey`});return}let i=null,a=e=>{e.on(`statechange`,e=>r({type:`oddin:state`,state:e})),e.on(`ready`,()=>r({type:`oddin:tracks`,quality:e.getQualityLevels(),audio:e.getAudioTracks(),text:e.getTextTracks()})),e.on(`waiting`,e=>r({type:`oddin:waiting`,retryInMs:e.retryInMs,attempt:e.attempt,phase:e.phase})),e.on(`qualitychange`,e=>r({type:`oddin:qualitychange`,index:e})),e.on(`audiotrackchange`,e=>r({type:`oddin:audiotrackchange`,id:e})),e.on(`texttrackchange`,e=>r({type:`oddin:texttrackchange`,id:e})),e.on(`stats`,e=>r({type:`oddin:stats`,droppedFrames:e.droppedFrames,latencySeconds:e.latencySeconds,bandwidthKbps:e.bandwidthKbps,levelHeight:e.levelHeight,lowLatency:e.lowLatency,isLive:e.isLive,atLiveEdge:e.atLiveEdge})),e.on(`error`,e=>r({type:`oddin:error`,code:e.code,message:e.message})),e.on(`autoplayblocked`,()=>{r({type:`oddin:autoplayblocked`}),Kt(t,e)})},o=async n=>{i?.destroy(),i=null;try{let r=await Bt({video:t,baseUrl:e.baseUrl,matchUrn:n,credential:{apiKey:e.apiKey},autoplay:e.autoplay,muted:e.muted,waitForLive:e.waitForLive});i=r;let o=t.parentElement;o?.classList.contains(`havik-player`)&&(o.style.cssText=`position:absolute;inset:0;width:100%;height:100%;aspect-ratio:auto`),a(r)}catch(e){let t=e instanceof l?e.code:`INTERNAL`,n=e instanceof Error?e.message:String(e);r({type:`oddin:error`,code:t,message:n})}},s=()=>{window.removeEventListener(`message`,u),window.removeEventListener(`pagehide`,s),i?.destroy(),i=null},c=e=>{switch(e.type){case`oddin:play`:i?.play();break;case`oddin:pause`:i?.pause();break;case`oddin:setMuted`:typeof e.muted==`boolean`&&i?.setMuted(e.muted);break;case`oddin:setVolume`:typeof e.volume==`number`&&Number.isFinite(e.volume)&&i?.setVolume(e.volume);break;case`oddin:setQuality`:typeof e.index==`number`&&i?.setQuality(e.index);break;case`oddin:setMaxBitrate`:(e.bitrate===null||typeof e.bitrate==`number`&&Number.isFinite(e.bitrate))&&i?.setMaxBitrate(e.bitrate);break;case`oddin:setAudioTrack`:typeof e.id==`number`&&i?.setAudioTrack(e.id);break;case`oddin:setTextTrack`:typeof e.id==`number`&&i?.setTextTrack(e.id);break;case`oddin:seekToLive`:i?.seekToLive();break;case`oddin:enterPip`:i?.enterPictureInPicture();break;case`oddin:exitPip`:i?.exitPictureInPicture();break;case`oddin:retry`:i?.retry();break;case`oddin:load`:typeof e.matchUrn==`string`&&Ut.test(e.matchUrn)&&o(e.matchUrn);break;case`oddin:destroy`:s()}},u=e=>{n&&e.origin===n&&$(e.data)&&c(e.data)};n&&window.addEventListener(`message`,u),window.addEventListener(`pagehide`,s,{once:!0}),await o(e.matchUrn),r({type:`oddin:ready`,protocol:1})}function Kt(e,t){if(document.getElementById(`havik-tap`))return;let n=document.createElement(`button`);n.id=`havik-tap`,n.textContent=`▶ Tap to play`,n.style.cssText=`position:fixed;inset:0;width:100%;height:100%;border:0;background:rgba(0,0,0,.55);color:#fff;font:600 18px system-ui,sans-serif;cursor:pointer;z-index:9`,n.addEventListener(`click`,()=>{n.remove(),t.play()}),document.body.appendChild(n)}function qt(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}exports.ODDIN_THEME=J,exports.PlaybackError=l,exports.applyTheme=X,exports.bootEmbed=Gt,exports.clearDeviceId=Ce,exports.createPlayer=Bt,exports.deriveEventsBaseUrl=D,exports.detectDrmSupport=Pe,exports.enterVideoFullscreen=w,exports.exitVideoFullscreen=T,exports.fetchCatalog=_e,exports.fetchTournament=ye,exports.flattenMatches=xe,exports.getDeviceId=A,exports.isLowLatencyManifest=Ie,exports.isOddinMessage=$,exports.licenseRequestHeaders=Te,exports.mountEmbed=Ht,exports.pollToLive=pe,exports.resolveStream=y,exports.subscribeLiveState=E,exports.videoFullscreenActive=C,exports.watchStatus=Se;
127
+ `;function Et(e=document){if(e.getElementById(Z))return;let t=e.createElement(`style`);t.id=Z,t.textContent=Tt,e.head.appendChild(t)}var Dt={play:`<path d="M8 5v14l11-7z"/>`,pause:`<path d="M6 5h4v14H6zM14 5h4v14h-4z"/>`,volumeHigh:`<path d="M3 10v4h4l5 5V5L7 10H3zm13.5 2a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zm-2.5-9v2.06A7 7 0 0 1 14 19v2a9 9 0 0 0 0-18z"/>`,volumeMute:`<path d="M3 10v4h4l5 5V5L7 10H3zm16.5 2 2.5-2.5-1.4-1.4L18 10.6 15.4 8 14 9.4l2.6 2.6L14 14.6l1.4 1.4 2.6-2.6 2.6 2.6 1.4-1.4z"/>`,cc:`<path d="M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM10 11H8.5v-.5h-2v3h2V13H10v1a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H17v1a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1z"/>`,settings:`<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.11-.2.06-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>`,pip:`<path d="M19 7h-8v6h8V7zm4 12V5a2 2 0 0 0-2-2H3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2zm-2 .02H3V4.98h18v14.04z"/>`,fullscreen:`<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>`,fullscreenExit:`<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>`,liveDot:`<circle cx="12" cy="12" r="6"/>`,retry:`<path d="M17.65 6.35A8 8 0 1 0 19.73 13h-2.08A6 6 0 1 1 12 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>`};function Q(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Dt[e]}</svg>`}var Ot=3e3,kt=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`]);function At(e){return new jt(e)}var jt=class{root;video;player;doc;autoHideMs;overlay;center;spinner;bar;gradient;seek;seekBuffered;seekPlayed;seekThumb;playBtn;muteBtn;volSlider;live;liveGo;time;ccBtn;audioBtn;qualityBtn;pipBtn;fsBtn;menu;statusBox=null;statusKind=null;statusMsg=null;hasPlayed=!1;lastError=null;logoUrl;statusOverlays;endedMessage;interruptedMessage;errorMessage;hideTimer;openMenu=null;scrubbing=!1;offFns=[];constructor(e){this.root=e.root,this.video=e.video,this.player=e.player,this.doc=e.root.ownerDocument??document,this.autoHideMs=e.autoHideMs??Ot,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.endedMessage=e.endedMessage??`This stream has ended`,this.interruptedMessage=e.interruptedMessage??`Reconnecting — please stand by`,this.errorMessage=e.errorMessage,Et(this.doc),this.root.classList.add(`havik-player`),this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=0),this.root.setAttribute(`role`,`region`),this.root.setAttribute(`aria-label`,`Video player`);let t=(e,t,n)=>{let r=this.doc.createElement(e);if(r.className=t,n)for(let[e,t]of Object.entries(n))r.setAttribute(e,t);return r},n=(e,n,r)=>{let i=t(`button`,e,{type:`button`,"aria-label":r,title:r});return i.innerHTML=Q(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Q(`play`),this.spinner=t(`div`,`havik-spinner`),this.spinner.style.display=`none`,this.overlay.append(this.center,this.spinner),this.gradient=t(`div`,`havik-gradient`),this.bar=t(`div`,`havik-bar`),this.seek=t(`div`,`havik-seek`,{role:`slider`,"aria-label":`Seek`,"aria-valuemin":`0`,"aria-valuemax":`100`,tabindex:`0`});let r=t(`div`,`havik-seek__track`);this.seekBuffered=t(`div`,`havik-seek__buffered`),this.seekPlayed=t(`div`,`havik-seek__played`),this.seekThumb=t(`div`,`havik-seek__thumb`),r.append(this.seekBuffered,this.seekPlayed,this.seekThumb),this.seek.append(r);let i=t(`div`,`havik-controls`);this.playBtn=n(`havik-btn`,`play`,`Play`),this.muteBtn=n(`havik-btn`,`volumeHigh`,`Mute`),this.volSlider=t(`input`,`havik-vol__slider`,{type:`range`,min:`0`,max:`1`,step:`0.05`,"aria-label":`Volume`});let a=t(`div`,`havik-vol`);a.append(this.muteBtn,this.volSlider),this.live=t(`div`,`havik-live`),this.live.innerHTML=Q(`liveDot`);let o=this.doc.createElement(`span`);o.textContent=`LIVE`,this.liveGo=t(`button`,`havik-live__go`,{type:`button`}),this.liveGo.textContent=`Go live`,this.live.append(o,this.liveGo),this.time=t(`div`,`havik-time`),this.time.textContent=`0:00`,this.time.style.display=`none`;let s=t(`div`,`havik-spacer`);if(this.ccBtn=n(`havik-btn`,`cc`,`Subtitles`),this.audioBtn=n(`havik-btn`,`settings`,`Audio track`),this.qualityBtn=n(`havik-btn`,`settings`,`Quality`),this.pipBtn=n(`havik-btn`,`pip`,`Picture in picture`),this.fsBtn=n(`havik-btn`,`fullscreen`,`Fullscreen`),this.ccBtn.style.display=`none`,this.audioBtn.style.display=`none`,this.qualityBtn.style.display=`none`,this.pipSupported()||(this.pipBtn.style.display=`none`),i.append(this.playBtn,a,this.live,this.time,s,this.ccBtn,this.audioBtn,this.qualityBtn,this.pipBtn,this.fsBtn),this.bar.append(this.seek,i),this.menu=t(`div`,`havik-menu`,{role:`menu`}),this.menu.hidden=!0,this.root.append(this.gradient,this.overlay,this.bar,this.menu),e.logoUrl){let n=t(`div`,`havik-watermark`);n.style.backgroundImage=`url("${e.logoUrl}")`,this.root.append(n)}this.wire(),this.syncPlayPause(),this.syncVolume(),this.scheduleHide()}on(e,t,n,r){e.addEventListener(t,n,r),this.offFns.push(()=>e.removeEventListener(t,n,r))}wire(){let e=this.video;this.on(this.playBtn,`click`,()=>this.togglePlay()),this.on(this.center,`click`,()=>this.togglePlay()),this.on(this.overlay,`click`,e=>{e.target===this.overlay&&this.togglePlay()}),this.on(this.muteBtn,`click`,()=>this.player.setMuted(!e.muted)),this.on(this.volSlider,`input`,()=>{let t=Number(this.volSlider.value);this.setVolumeFill(t),this.player.setVolume(t),t>0&&e.muted&&this.player.setMuted(!1)}),this.on(this.liveGo,`click`,()=>this.player.seekToLive()),this.on(this.pipBtn,`click`,()=>void this.togglePip()),this.on(this.fsBtn,`click`,()=>void this.toggleFullscreen()),this.on(this.ccBtn,`click`,()=>this.toggleMenu(`cc`)),this.on(this.audioBtn,`click`,()=>this.toggleMenu(`audio`)),this.on(this.qualityBtn,`click`,()=>this.toggleMenu(`quality`)),this.on(this.seek,`pointerdown`,e=>this.onSeekDown(e)),this.on(this.seek,`keydown`,e=>this.onSeekKey(e)),this.on(e,`play`,()=>this.syncPlayPause()),this.on(e,`pause`,()=>this.syncPlayPause()),this.on(e,`volumechange`,()=>this.syncVolume()),this.on(e,`timeupdate`,()=>this.syncProgress()),this.on(e,`progress`,()=>this.syncProgress()),this.on(e,`durationchange`,()=>this.syncProgress()),this.offFns.push(this.player.on(`statechange`,()=>this.syncState())),this.offFns.push(this.player.on(`ended`,()=>this.syncState())),this.offFns.push(this.player.on(`ready`,()=>this.refreshTracks())),this.offFns.push(this.player.on(`qualitychange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`audiotrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`texttrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`pipchange`,e=>this.syncPip(e))),this.offFns.push(this.player.on(`stats`,()=>this.syncLive())),this.offFns.push(this.player.on(`error`,e=>{this.lastError=e,this.statusKind=null,this.syncState()})),this.on(this.root,`pointermove`,()=>this.poke()),this.on(this.root,`pointerleave`,()=>this.scheduleHide(0)),this.on(this.root,`focusin`,()=>this.poke()),this.on(this.root,`keydown`,e=>this.onKey(e)),this.on(this.doc,`pointerdown`,e=>this.onDocPointer(e),{capture:!0}),this.on(this.doc,`fullscreenchange`,()=>this.syncFullscreen()),this.on(this.doc,`webkitfullscreenchange`,()=>this.syncFullscreen()),this.on(e,`webkitbeginfullscreen`,()=>this.syncFullscreen()),this.on(e,`webkitendfullscreen`,()=>this.syncFullscreen()),this.syncState()}togglePlay(){this.video.paused||this.video.ended?this.player.play():this.player.pause()}syncPlayPause(){let e=!this.video.paused&&!this.video.ended;this.setIcon(this.playBtn,e?`pause`:`play`),this.playBtn.setAttribute(`aria-label`,e?`Pause`:`Play`),this.setIcon(this.center,e?`pause`:`play`),this.center.classList.toggle(`havik-gone`,e||!!this.statusBox),e?this.scheduleHide():this.show()}syncState(){let e=this.player.state;(e===`playing`||e===`buffering`)&&(this.hasPlayed=!0),this.syncStatus(e);let t=e===`loading`||e===`buffering`;this.spinner.style.display=t&&!this.statusBox?``:`none`,(t||this.statusBox)&&this.center.classList.add(`havik-gone`),this.syncLive()}syncStatus(e){let t=null;this.statusOverlays&&(e===`ended`?t=`ended`:e===`error`?t=`error`:e===`waiting`?t=`waiting`:!this.hasPlayed&&(e===`idle`||e===`paused`)&&(t=`preplay`)),this.renderStatus(t)}statusMessageFor(e){return e===`ended`?this.player.endedReason===`interrupted`?this.interruptedMessage:this.endedMessage:e===`waiting`?this.hasPlayed?`Reconnecting — please stand by`:`Starting soon…`:e===`error`?this.errorMessage??this.lastError?.message??`Playback unavailable`:null}renderStatus(e){let t=this.statusMessageFor(e);if(e===this.statusKind&&t===this.statusMsg||(this.statusKind=e,this.statusMsg=t,this.statusBox?.remove(),this.statusBox=null,this.root.classList.toggle(`havik-has-status`,!!e),!e))return;let n=this.doc.createElement(`div`);if(n.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,n.append(e)}if(e===`preplay`){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn havik-status__btn--play`,e.setAttribute(`aria-label`,`Play`),e.innerHTML=Q(`play`),e.addEventListener(`click`,()=>void this.player.play()),n.append(e)}else{let r=this.doc.createElement(`div`);if(r.className=`havik-status__msg`,r.textContent=t??``,n.append(r),e===`error`&&this.lastError&&!kt.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Q(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),n.append(e)}}this.root.append(n),this.statusBox=n,this.show()}syncVolume(){let e=this.video,t=e.muted||e.volume===0;this.setIcon(this.muteBtn,t?`volumeMute`:`volumeHigh`),this.muteBtn.setAttribute(`aria-label`,t?`Unmute`:`Mute`);let n=t?0:e.volume;this.volSlider.value=String(n),this.setVolumeFill(n)}setVolumeFill(e){this.volSlider.style.setProperty(`--havik-vol`,String(Math.min(1,Math.max(0,e))))}seekableRange(){let e=this.video,t,n;if(e.seekable&&e.seekable.length>0)t=e.seekable.start(0),n=e.seekable.end(e.seekable.length-1);else if(Number.isFinite(e.duration)&&e.duration>0)t=0,n=e.duration;else return null;let r=this.player.getStats();return r.isLive!==!1&&r.targetLatencySeconds&&r.targetLatencySeconds>0&&(n=Math.max(t,n-r.targetLatencySeconds)),n>t?{start:t,end:n}:null}syncProgress(){if(this.scrubbing)return;let e=this.seekableRange();if(!e){this.seekPlayed.style.width=`100%`;return}let t=e.end-e.start,n=Math.min(1,Math.max(0,(this.video.currentTime-e.start)/t));this.seekPlayed.style.width=`${(n*100).toFixed(2)}%`,this.seekThumb.style.left=`${(n*100).toFixed(2)}%`,this.seek.setAttribute(`aria-valuenow`,String(Math.round(n*100)));let r=this.video.buffered;if(r&&r.length>0){let n=r.end(r.length-1),i=Math.min(1,Math.max(0,(n-e.start)/t));this.seekBuffered.style.width=`${(i*100).toFixed(2)}%`}!this.player.getStats().isLive&&Number.isFinite(this.video.duration)&&(this.time.textContent=`${Mt(this.video.currentTime)} / ${Mt(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1;this.live.style.display=t?``:`none`,this.time.style.display=t?`none`:``,this.live.classList.toggle(`is-live`,e.atLiveEdge!==!1&&t)}onSeekDown(e){let t=this.seekableRange();if(!t)return;e.preventDefault(),this.scrubbing=!0;let n=e=>this.seekToPointer(e,t),r=()=>{this.scrubbing=!1,this.doc.removeEventListener(`pointermove`,n),this.doc.removeEventListener(`pointerup`,r)};this.doc.addEventListener(`pointermove`,n),this.doc.addEventListener(`pointerup`,r),this.seekToPointer(e,t)}seekToPointer(e,t){let n=this.seek.getBoundingClientRect(),r=n.width>0?Math.min(1,Math.max(0,(e.clientX-n.left)/n.width)):0;this.seekPlayed.style.width=`${(r*100).toFixed(2)}%`,this.seekThumb.style.left=`${(r*100).toFixed(2)}%`,this.video.currentTime=t.start+r*(t.end-t.start)}onSeekKey(e){e.key===`ArrowLeft`?(this.nudge(-5),e.preventDefault()):e.key===`ArrowRight`&&(this.nudge(5),e.preventDefault())}nudge(e){let t=this.seekableRange();t&&(this.video.currentTime=Math.min(t.end,Math.max(t.start,this.video.currentTime+e)))}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e,this.renderMenu(e),this.menu.hidden=!1,this.show()}closeMenu(){this.openMenu=null,this.menu.hidden=!0,this.menu.replaceChildren()}renderMenu(e){e===`quality`?this.renderQualityMenu():e===`audio`?this.renderAudioMenu():this.renderCcMenu()}menuItem(e,t,n){let r=this.doc.createElement(`button`);r.type=`button`,r.className=`havik-menu__item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,t?`true`:`false`);let i=this.doc.createElement(`span`);return i.textContent=e,r.append(i),r.addEventListener(`click`,()=>{n(),this.closeMenu()}),r}renderQualityMenu(){let e=this.player.getQualityLevels(),t=this.player.getCurrentQuality(),n=this.doc.createElement(`div`);n.className=`havik-menu__title`,n.textContent=`Quality`,this.menu.replaceChildren(n,this.menuItem(`Auto`,t===-1,()=>this.player.setQuality(`auto`)));for(let n of e)this.menu.append(this.menuItem(Nt(n),t===n.index,()=>this.player.setQuality(n.index)))}renderAudioMenu(){let e=this.player.getAudioTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Audio`,this.menu.replaceChildren(t);for(let t of e)this.menu.append(this.menuItem(Pt(t),t.default,()=>this.player.setAudioTrack(t.id)))}renderCcMenu(){let e=this.player.getTextTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Subtitles`,this.menu.replaceChildren(t,this.menuItem(`Off`,!1,()=>this.player.setTextTrack(-1)));for(let t of e)this.menu.append(this.menuItem(Ft(t),!1,()=>this.player.setTextTrack(t.id)))}onTracksChanged(){this.openMenu&&this.renderMenu(this.openMenu)}refreshTracks(){let e=this.player.getQualityLevels(),t=this.player.getAudioTracks(),n=this.player.getTextTracks();this.qualityBtn.style.display=e.length>1?``:`none`,this.audioBtn.style.display=t.length>1?``:`none`,this.ccBtn.style.display=n.length>0?``:`none`,this.onTracksChanged()}pipSupported(){return`pictureInPictureEnabled`in this.doc&&typeof this.video.requestPictureInPicture==`function`}async togglePip(){this.doc.pictureInPictureElement===this.video?await this.player.exitPictureInPicture():await this.player.enterPictureInPicture()}syncPip(e){this.pipBtn.setAttribute(`aria-pressed`,e?`true`:`false`)}async toggleFullscreen(){try{C(this.video,this.root)?await T(this.video,this.root):await w(this.video,this.root)}catch{}}syncFullscreen(){let e=C(this.video,this.root);this.setIcon(this.fsBtn,e?`fullscreenExit`:`fullscreen`),this.fsBtn.setAttribute(`aria-label`,e?`Exit fullscreen`:`Fullscreen`)}poke(){this.show(),this.scheduleHide()}show(){this.root.classList.remove(`havik-hide`)}scheduleHide(e=this.autoHideMs){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{!this.video.paused&&!this.video.ended&&!this.openMenu&&!this.statusBox&&this.root.classList.add(`havik-hide`)},e)}onDocPointer(e){this.openMenu&&!this.menu.contains(e.target)&&([this.qualityBtn,this.audioBtn,this.ccBtn].some(t=>t.contains(e.target))||this.closeMenu())}onKey(e){let t=e.target;if(!(t&&t!==this.root&&t!==this.seek&&t.tagName===`INPUT`)){switch(e.key){case` `:case`k`:this.togglePlay();break;case`m`:this.player.setMuted(!this.video.muted);break;case`f`:this.toggleFullscreen();break;case`c`:this.ccBtn.style.display!==`none`&&this.toggleMenu(`cc`);break;case`l`:this.player.seekToLive();break;case`ArrowUp`:this.player.setVolume(Math.min(1,this.video.volume+.1));break;case`ArrowDown`:this.player.setVolume(Math.max(0,this.video.volume-.1));break;case`ArrowLeft`:this.nudge(-5);break;case`ArrowRight`:this.nudge(5);break;default:return}this.poke(),e.preventDefault()}}setIcon(e,t){e.innerHTML=Q(t)}destroy(){this.hideTimer&&clearTimeout(this.hideTimer);for(let e of this.offFns)try{e()}catch{}this.offFns.length=0,this.closeMenu(),this.statusBox?.remove();for(let e of[this.overlay,this.gradient,this.bar,this.menu])e.remove();this.root.classList.remove(`havik-player`,`havik-hide`,`havik-has-status`)}};function Mt(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=Math.floor(e%60),n=Math.floor(e/60%60),r=Math.floor(e/3600),i=r>0?String(n).padStart(2,`0`):String(n),a=String(t).padStart(2,`0`);return r>0?`${r}:${i}:${a}`:`${i}:${a}`}function Nt(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function Pt(e){return e.name||e.lang||`Track ${e.id}`}function Ft(e){return e.name||e.lang||`Track ${e.id}`}var It=6e3,Lt=45e3,Rt=2e3,zt=3,Bt=2e3,Vt=48e4;async function Ht(e){if(!e.video||typeof e.video.play!=`function`)throw new l(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);if(!e.baseUrl)throw new l(`INTERNAL`,0,`createPlayer: baseUrl is required`);if(!e.matchUrn)throw new l(`INVALID_URN`,0,`createPlayer: matchUrn is required`);if(!e.credential)throw new l(`INTERNAL`,0,`createPlayer: credential is required`);let t=new Ut(e);return await t.start(),t}var Ut=class{opts;abort=new AbortController;listeners={};engine=null;controlBar=null;container=null;detachMedia;detachPip;statsTimer;refreshTimer;_state=`idle`;_descriptor=null;destroyed=!1;loadGen=0;liveStateSub=null;endedHandled=!1;_endedReason=null;rejoinTimer=null;armingSub=null;armSseTimer=null;armFallbackCtrl=null;_lastError=null;analyticsSession=null;detachMediaListeners;playRequested=!1;pendingStartLoad=!1;constructor(e){this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}get endedReason(){return this._endedReason}async start(){this.opts.muted&&(this.opts.video.muted=!0),this.opts.poster&&(this.opts.video.poster=this.opts.poster),this.mountControls(),this.attachPipListeners(),this.setState(`loading`);let e=++this.loadGen,t=this.resolveOptions();try{let n=await v(t);if(await this.onResolved(n,e),e===this.loadGen&&this._state===`error`&&this._lastError){let e=this._lastError;throw this.destroy(),e}}catch(t){if(this.opts.waitForLive&&t instanceof l&&p(t.code)){this.setState(`waiting`),this.beginArming(e,t.liveStartsAtMs);return}throw t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal,apiHeaders:this.opts.apiHeaders}}beginArming(e,t,n=!1){let r=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??D(this.opts.baseUrl);r?this.armWithSse(e,r,t,n):this.beginArmingByPolling(e)}beginArmingByPolling(e){y({...this.resolveOptions(),signal:this.abort.signal,waitForLive:this.buildWaitConfig(e)}).then(t=>{if(!(this.destroyed||this.abort.signal.aborted||e!==this.loadGen))return this.onResolved(t,e)}).catch(t=>{this.destroyed||this.abort.signal.aborted||e!==this.loadGen||this.fail(t instanceof l?t:new l(`INTERNAL`,0,String(t)))})}armWithSse(e,t,n,r=!1){let i=!1,a=!1,o=new AbortController;this.armFallbackCtrl=o,this.setState(`waiting`);let s=this.opts.waitForLive,c=s&&s!==!0?s.kickoffAt:void 0,u=typeof c==`number`?c:typeof c==`string`?Date.parse(c):NaN,d=n??(Number.isFinite(u)?u:void 0);setTimeout(()=>{i||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:r?`unavailable`:`tooEarly`,retryInMs:Lt,attempt:1,elapsedMs:0,...!r&&d!==void 0&&d>Date.now()?{ttkMs:d-Date.now()}:{}})},0);let f=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,m=async t=>{if(!(i||f())){i=!0,this.closeArming(),o.abort();try{await this.onResolved(t,e)}catch(e){if(f())return;this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e)))}}},h=()=>{i||a||f()||(a=!0,y({...this.resolveOptions(),signal:o.signal,waitForLive:this.buildWaitConfig(e)}).then(e=>m(e)).catch(e=>{i||f()||o.signal.aborted||(i=!0,this.closeArming(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))}))},g=()=>{i||f()||v(this.resolveOptions()).then(e=>m(e)).catch(e=>{if(!(i||f())){if(e instanceof l&&p(e.code)){h();return}i=!0,this.closeArming(),o.abort(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e)))}})},_=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!i&&!f()&&h()},e)};_(It),this.armingSub=E({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(Lt),onState:e=>{i||f()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*Rt)},onError:()=>h()})}closeArming(){this.armSseTimer&&=(clearTimeout(this.armSseTimer),null),this.armFallbackCtrl?.abort(),this.armFallbackCtrl=null,this.armingSub?.close(),this.armingSub=null}buildWaitConfig(e){let t=this.opts.waitForLive&&this.opts.waitForLive!==!0?this.opts.waitForLive:{};return{...t,onState:n=>{this.destroyed||e!==this.loadGen||(this.setState(`waiting`),this.emit(`waiting`,n),t.onState?.(n))}}}async onResolved(e,t){if(this.destroyed||t!==this.loadGen)return;this._descriptor=e,this.endedHandled=!1,this._endedReason=null;let n=await m(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.opts.autoplay===!1&&!this.playRequested,i=this.createEngine(e,n,r),a=Be(this.opts.video,e=>{this._state!==`ended`&&this._state!==`error`&&this.setState(e)});if(await i.load(),this.destroyed||t!==this.loadGen){a(),i.destroy();return}if(this._state===`error`){a(),i.destroy();return}this.engine=i,this.detachMedia=a,this.opts.maxBitrate!=null&&i.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t),this.startAnalytics(e,i),r&&(this.pendingStartLoad=!0,this.setState(`paused`),i.name===`native`&&setTimeout(()=>{this.destroyed||t!==this.loadGen||this.engine!==i||(this.analyticsSession?.noteReady(),this.emit(`ready`))},0))}startAnalytics(e,t){if(this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.opts.analytics===!1)return;let n=e.analytics?.sid;if(!n)return;let r=(typeof this.opts.analytics==`object`?this.opts.analytics.endpoint:void 0)??_t(this.opts.baseUrl);if(!r)return;let i=this.opts.video,a=new vt({endpoint:r,sid:n,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:wt,environment:St(i),sample:()=>{let e=this.engine?.getStats()??I,t=i.buffered.length?Math.max(0,i.buffered.end(i.buffered.length-1)-i.currentTime):0;return{...e,bufferedMs:Math.round(t*1e3),state:this._state,positionMs:Math.round(i.currentTime*1e3),playbackRate:i.playbackRate}}});this.analyticsSession=a;let o=()=>a.noteSeek(),s=()=>a.noteVolume(i.muted,i.volume);i.addEventListener(`seeking`,o),i.addEventListener(`volumechange`,s),this.detachMediaListeners=()=>{i.removeEventListener(`seeking`,o),i.removeEventListener(`volumechange`,s)},a.start(),a.seedVolume(i.muted,i.volume),a.notePresentation(this.currentPresentation()),Ct().then(e=>a.noteEnvironment(e)),this.opts.autoplay===!1&&a.noteAutoplay(`AUTOPLAY_RESULT_NOT_ATTEMPTED`)}currentPresentation(){let e=this.opts.video;if(typeof document<`u`&&document.pictureInPictureElement===e)return`pip`;let t=typeof document<`u`?document.fullscreenElement:null;return e.webkitDisplayingFullscreen===!0||t&&(t===e||t.contains(e))?`fullscreen`:`inline`}createEngine(e,t,n=!1){let r={...this.opts.hlsConfig};this.opts.startLevel!=null&&(r.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(r.liveSyncDuration=this.opts.liveLatencyTarget);let i={video:this.opts.video,descriptor:e,credential:t,deviceId:A(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,debug:this.opts.debug,deferLoad:n,hlsConfig:r,emit:e=>this.onEngineEvent(e)},a=this.opts.engine??`auto`;if(a===`native`)return new V(i);if(a===`hls`)return new U(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&z(this.opts.video)&&B())return new V(i);if(Ue())return new U(i);if(z(this.opts.video))return new V(i);throw new l(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`ready`:this.analyticsSession?.noteReady(),this.emit(`ready`),(this.opts.autoplay!==!1||this.playRequested)&&this.play();break;case`lowLatencyDetected`:this._descriptor&&(this._descriptor.isLowLatency=e.value);break;case`qualitychange`:this.emit(`qualitychange`,e.index);break;case`audiotrackchange`:this.emit(`audiotrackchange`,e.id);break;case`texttrackchange`:this.emit(`texttrackchange`,e.id);break;case`ended`:this.onStreamEnded();break;case`error`:this.analyticsSession?.noteError(e.error.code,e.error.message,e.fatal,e.error.httpStatus??0,Math.round(this.opts.video.currentTime*1e3),e.detail),e.fatal?this.fail(e.error):this.emit(`warning`,e.error)}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??D(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=E({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`gone`?this.onStreamEnded(!0,t.reason??`match_ended`):t.state===`ended`?this.onStreamEnded(!1,t.reason):t.state===`live`&&this.endedHandled&&this.scheduleRejoin(e))},onAlive:()=>{n=0,r=!1},onError:()=>{this.destroyed||e!==this.loadGen||r||this.endedHandled||(n+=1,n>=zt&&(r=!0,this.emit(`warning`,new l(`NETWORK`,0,`live-state events unreachable at ${t} after ${n} attempts — end-of-stream detection degraded to the HLS staleness watchdog. Check the events host, the api-key's allowed origins, and CSP connect-src.`))))}})}closeLiveState(){this.liveStateSub?.close(),this.liveStateSub=null}onStreamEnded(e=!1,t){if(!this.destroyed){if((e||!this.rejoinEnabled())&&(this.cancelRejoin(),this.closeLiveState()),this.endedHandled){t===`match_ended`&&this._endedReason!==`match_ended`&&(this._endedReason=t,this.emit(`ended`,t));return}this.endedHandled=!0,this._endedReason=t??null,this.stopRefresh(),this.pendingStartLoad=!1,this.engine?.stop(),this.setState(`ended`)}}rejoinEnabled(){return this.opts.rejoinOnLive!==!1&&this.opts.liveStateEvents!==!1}scheduleRejoin(e){this.rejoinEnabled()&&!this.rejoinTimer&&(this.rejoinTimer=setTimeout(()=>{this.rejoinTimer=null,!(this.destroyed||e!==this.loadGen||this._state!==`ended`)&&this.rejoin()},Math.random()*Rt))}cancelRejoin(){this.rejoinTimer&&=(clearTimeout(this.rejoinTimer),null)}rejoin(){let e=++this.loadGen;this.teardownPlayback(),this.setState(`waiting`),this.beginArming(e,void 0,!0)}teardownPlayback(){this.stopStats(),this.stopRefresh(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null,this.pendingStartLoad=!1}mountControls(){let e=this.opts.controls??`custom`,t=this.opts.video;if(e===`native`){t.controls=!0;return}if(e===`none`){t.controls=!1;return}t.controls=!1;let n=(t.ownerDocument??document).createElement(`div`),r=t.parentNode;r&&r.insertBefore(n,t),n.appendChild(t),X(n,this.opts.theme),this.container=n,this.controlBar=At({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,interruptedMessage:this.opts.interruptedMessage,errorMessage:this.opts.errorMessage})}unmountControls(){this.controlBar?.destroy(),this.controlBar=null;let e=this.container;e&&(e.parentNode?(e.parentNode.insertBefore(this.opts.video,e),e.remove()):this.opts.video.parentNode===e&&e.removeChild(this.opts.video)),this.container=null}attachPipListeners(){let e=this.opts.video,t=()=>this.analyticsSession?.notePresentation(this.currentPresentation()),n=()=>{t(),this.emit(`pipchange`,!0)},r=()=>{t(),this.emit(`pipchange`,!1)};e.addEventListener(`enterpictureinpicture`,n),e.addEventListener(`leavepictureinpicture`,r);let i=typeof document<`u`?document:void 0;i?.addEventListener(`fullscreenchange`,t),i?.addEventListener(`webkitfullscreenchange`,t),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,n),e.removeEventListener(`leavepictureinpicture`,r),i?.removeEventListener(`fullscreenchange`,t),i?.removeEventListener(`webkitfullscreenchange`,t)}}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??Bt);this.statsTimer=setInterval(()=>{if(!this.engine)return;let e=this.engine.getStats();(e.bytesLoaded??0)>0&&this.analyticsSession?.noteFirstBytes(),this.emit(`stats`,e)},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}scheduleLicenseRefresh(){this.stopRefresh();let e=this.opts.licenseRefreshMs??Vt;e&&this._descriptor?.drmEnabled&&(this.refreshTimer=setInterval(()=>void this.refreshLicense(),e))}stopRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=void 0}async refreshLicense(){let e=this.engine;if(!this.destroyed&&e)try{let t=await v(this.resolveOptions());if(this.destroyed||this.engine!==e)return;let n=t.drm?.widevine?.licenseUrl,r=t.drm?.fairplay?.licenseUrl;(n||r)&&(e.setLicenseUrls({widevine:n,fairplay:r}),this._descriptor=t)}catch(e){e instanceof l&&!p(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e))}}async play(){if(this.destroyed)return;let e=!this.playRequested;this.playRequested=!0;let t=this.pendingStartLoad&&this._state!==`ended`&&this._state!==`error`;this.opts.autoplay===!1&&this.analyticsSession?.notePlayIntent(),t&&(this.pendingStartLoad=!1,this.setState(`loading`),this.engine?.startLoad());try{await this.opts.video.play(),e&&this.analyticsSession?.noteAutoplay(this.opts.video.muted?`AUTOPLAY_RESULT_ALLOWED_MUTED`:`AUTOPLAY_RESULT_ALLOWED`)}catch(n){n instanceof DOMException&&n.name===`NotAllowedError`&&(this.analyticsSession?.noteAutoplay(`AUTOPLAY_RESULT_BLOCKED`),e&&(this.playRequested=!1),t&&!this.destroyed&&this._state===`loading`&&this.setState(`paused`),this.emit(`autoplayblocked`))}}pause(){this.destroyed||this.opts.video.pause()}setMuted(e){this.destroyed||(this.opts.video.muted=e)}setVolume(e){this.destroyed||(this.opts.video.volume=Math.min(1,Math.max(0,e)))}getStats(){return this.engine?.getStats()??I}getQualityLevels(){return this.engine?.getQualityLevels()??[]}getCurrentQuality(){return this.engine?.getCurrentQuality()??-1}setQuality(e){this.destroyed||this.engine?.setQuality(e===`auto`?-1:e)}setMaxBitrate(e){this.destroyed||this.engine?.setMaxBitrate(e)}getAudioTracks(){return this.engine?.getAudioTracks()??[]}setAudioTrack(e){this.destroyed||this.engine?.setAudioTrack(e)}getTextTracks(){return this.engine?.getTextTracks()??[]}setTextTrack(e){this.destroyed||this.engine?.setTextTrack(e)}seekToLive(){this.destroyed||this.engine?.seekToLive()}async enterPictureInPicture(){if(this.destroyed)return;let e=this.opts.video;typeof e.requestPictureInPicture==`function`&&await e.requestPictureInPicture()}async exitPictureInPicture(){let e=document;e.pictureInPictureElement===this.opts.video&&typeof e.exitPictureInPicture==`function`&&await e.exitPictureInPicture()}async enterFullscreen(){return!this.destroyed&&w(this.opts.video,this.container??void 0)}async exitFullscreen(){await T(this.opts.video,this.container??void 0)}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.teardownPlayback();try{let t=await y({...this.resolveOptions(),waitForLive:this.opts.waitForLive?this.buildWaitConfig(e):void 0});if(await this.onResolved(t,e),e===this.loadGen&&this._state===`error`&&this._lastError)throw this._lastError}catch(t){if(this.destroyed||this.abort.signal.aborted||e!==this.loadGen)return;throw t!==this._lastError&&this.fail(t instanceof l?t:new l(`INTERNAL`,0,String(t))),t}}on(e,t){let n=this.listeners[e]??=new Set;return n.add(t),()=>n.delete(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadGen+=1,this.abort.abort(),this.stopStats(),this.stopRefresh(),this.unmountControls(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.detachPip?.(),this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.engine?.destroy(),this.engine=null,this.setState(`idle`),this.clearListeners())}clearListeners(){for(let e of Object.keys(this.listeners))this.listeners[e]?.clear()}fail(e){this._lastError=e,this.setState(`error`),this.analyticsSession?.noteFatal(),this.emit(`error`,e)}setState(e){if(e===this._state)return;let t=this._state;if(this._state=e,this.analyticsSession){let n=this.opts.video;this.analyticsSession.noteStateChange(t,e,Math.round(n.currentTime*1e3),this.engine?.getStats().levelHeight),e===`ended`&&this.analyticsSession.noteEnded()}switch(this.emit(`statechange`,e),e){case`playing`:this.emit(`playing`);break;case`buffering`:this.emit(`buffering`);break;case`paused`:this.emit(`paused`);break;case`ended`:this.emit(`ended`,this._endedReason??void 0)}}emit(e,t){this.listeners[e]?.forEach(e=>{try{e(t)}catch{}})}};function $(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function Wt(e){if(!e.container||typeof e.container.appendChild!=`function`)throw Error(`mountEmbed: opts.container must be a DOM element`);if(!e.src)throw Error(`mountEmbed: opts.src is required`);if(!e.baseUrl||!e.matchUrn)throw Error(`mountEmbed: opts.baseUrl and opts.matchUrn are required`);let t=new URL(e.src,location.href),n=e.allowedFrameOrigin??t.origin;t.searchParams.set(`baseUrl`,e.baseUrl),t.searchParams.set(`matchUrn`,e.matchUrn),t.searchParams.set(`parentOrigin`,location.origin),e.muted!=null&&t.searchParams.set(`muted`,String(e.muted)),e.apiKey&&(t.searchParams.set(`apiKey`,e.apiKey),console.warn(`havik-player: passing apiKey to mountEmbed places it in the iframe URL — DEV/DEMO only. In production inject it server-side into window.HAVIK_EMBED_CONFIG on the embed page.`));let r=document.createElement(`iframe`);r.src=t.toString(),r.allow=`autoplay; encrypted-media; fullscreen`,r.setAttribute(`allowfullscreen`,``),r.referrerPolicy=`no-referrer`,r.setAttribute(`sandbox`,e.sandbox??`allow-scripts allow-same-origin allow-presentation`),r.style.cssText=`border:0;width:100%;height:100%;display:block`,e.container.appendChild(r);let i=new Set,a=t=>{if(t.source!==r.contentWindow||t.origin!==n||!$(t.data))return;let a=t.data;a.type===`oddin:ready`&&a.protocol!==1&&console.warn(`havik-player: embed protocol v${a.protocol} != host v1. Pin the embed page version to the SDK version to avoid skew.`),e.onEvent?.(a),i.forEach(e=>e(a))};window.addEventListener(`message`,a);let o=e=>r.contentWindow?.postMessage(e,n);return{iframe:r,play:()=>o({type:`oddin:play`}),pause:()=>o({type:`oddin:pause`}),setMuted:e=>o({type:`oddin:setMuted`,muted:e}),setVolume:e=>o({type:`oddin:setVolume`,volume:e}),setQuality:e=>o({type:`oddin:setQuality`,index:e}),setMaxBitrate:e=>o({type:`oddin:setMaxBitrate`,bitrate:e}),setAudioTrack:e=>o({type:`oddin:setAudioTrack`,id:e}),setTextTrack:e=>o({type:`oddin:setTextTrack`,id:e}),seekToLive:()=>o({type:`oddin:seekToLive`}),enterPip:()=>o({type:`oddin:enterPip`}),exitPip:()=>o({type:`oddin:exitPip`}),retry:()=>o({type:`oddin:retry`}),load:e=>o({type:`oddin:load`,matchUrn:e}),on:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{o({type:`oddin:destroy`}),window.removeEventListener(`message`,a),r.remove()}}}var Gt=/^[A-Za-z0-9:_.-]{1,128}$/;function Kt(){let e=window.HAVIK_EMBED_CONFIG;if(e)return{baseUrl:e.baseUrl??``,matchUrn:e.matchUrn??``,apiKey:e.apiKey??``,parentOrigin:e.parentOrigin,autoplay:e.autoplay??!0,muted:e.muted??!0,waitForLive:e.waitForLive??!0};let t=new URLSearchParams(location.search);return{baseUrl:t.get(`baseUrl`)??``,matchUrn:t.get(`matchUrn`)??``,apiKey:t.get(`apiKey`)??``,parentOrigin:t.get(`parentOrigin`)??void 0,autoplay:!0,muted:t.get(`muted`)!==`false`,waitForLive:!0}}async function qt(){let e=Kt();Yt();let t=document.createElement(`video`);t.setAttribute(`playsinline`,``),t.muted=e.muted??!0,t.style.cssText=`width:100%;height:100%;object-fit:contain;background:#000;aspect-ratio:auto`,document.body.appendChild(t);let n=e.parentOrigin&&e.parentOrigin!==`null`?e.parentOrigin:null;n||console.warn(`havik-player: embed has no parentOrigin — the postMessage bridge is disabled (no events posted, no commands accepted). mountEmbed sets parentOrigin automatically.`);let r=e=>{if(n)try{window.parent?.postMessage(e,n)}catch{}};if(!e.baseUrl||!e.matchUrn||!e.apiKey){r({type:`oddin:error`,code:`INTERNAL`,message:`embed missing baseUrl/matchUrn/apiKey`});return}let i=null,a=e=>{e.on(`statechange`,e=>r({type:`oddin:state`,state:e})),e.on(`ready`,()=>r({type:`oddin:tracks`,quality:e.getQualityLevels(),audio:e.getAudioTracks(),text:e.getTextTracks()})),e.on(`waiting`,e=>r({type:`oddin:waiting`,retryInMs:e.retryInMs,attempt:e.attempt,phase:e.phase})),e.on(`qualitychange`,e=>r({type:`oddin:qualitychange`,index:e})),e.on(`audiotrackchange`,e=>r({type:`oddin:audiotrackchange`,id:e})),e.on(`texttrackchange`,e=>r({type:`oddin:texttrackchange`,id:e})),e.on(`stats`,e=>r({type:`oddin:stats`,droppedFrames:e.droppedFrames,latencySeconds:e.latencySeconds,bandwidthKbps:e.bandwidthKbps,levelHeight:e.levelHeight,lowLatency:e.lowLatency,isLive:e.isLive,atLiveEdge:e.atLiveEdge})),e.on(`error`,e=>r({type:`oddin:error`,code:e.code,message:e.message})),e.on(`autoplayblocked`,()=>{r({type:`oddin:autoplayblocked`}),Jt(t,e)})},o=async n=>{i?.destroy(),i=null;try{let r=await Ht({video:t,baseUrl:e.baseUrl,matchUrn:n,credential:{apiKey:e.apiKey},autoplay:e.autoplay,muted:e.muted,waitForLive:e.waitForLive});i=r;let o=t.parentElement;o?.classList.contains(`havik-player`)&&(o.style.cssText=`position:absolute;inset:0;width:100%;height:100%;aspect-ratio:auto`),a(r)}catch(e){let t=e instanceof l?e.code:`INTERNAL`,n=e instanceof Error?e.message:String(e);r({type:`oddin:error`,code:t,message:n})}},s=()=>{window.removeEventListener(`message`,u),window.removeEventListener(`pagehide`,s),i?.destroy(),i=null},c=e=>{switch(e.type){case`oddin:play`:i?.play();break;case`oddin:pause`:i?.pause();break;case`oddin:setMuted`:typeof e.muted==`boolean`&&i?.setMuted(e.muted);break;case`oddin:setVolume`:typeof e.volume==`number`&&Number.isFinite(e.volume)&&i?.setVolume(e.volume);break;case`oddin:setQuality`:typeof e.index==`number`&&i?.setQuality(e.index);break;case`oddin:setMaxBitrate`:(e.bitrate===null||typeof e.bitrate==`number`&&Number.isFinite(e.bitrate))&&i?.setMaxBitrate(e.bitrate);break;case`oddin:setAudioTrack`:typeof e.id==`number`&&i?.setAudioTrack(e.id);break;case`oddin:setTextTrack`:typeof e.id==`number`&&i?.setTextTrack(e.id);break;case`oddin:seekToLive`:i?.seekToLive();break;case`oddin:enterPip`:i?.enterPictureInPicture();break;case`oddin:exitPip`:i?.exitPictureInPicture();break;case`oddin:retry`:i?.retry();break;case`oddin:load`:typeof e.matchUrn==`string`&&Gt.test(e.matchUrn)&&o(e.matchUrn);break;case`oddin:destroy`:s()}},u=e=>{n&&e.origin===n&&$(e.data)&&c(e.data)};n&&window.addEventListener(`message`,u),window.addEventListener(`pagehide`,s,{once:!0}),await o(e.matchUrn),r({type:`oddin:ready`,protocol:1})}function Jt(e,t){if(document.getElementById(`havik-tap`))return;let n=document.createElement(`button`);n.id=`havik-tap`,n.textContent=`▶ Tap to play`,n.style.cssText=`position:fixed;inset:0;width:100%;height:100%;border:0;background:rgba(0,0,0,.55);color:#fff;font:600 18px system-ui,sans-serif;cursor:pointer;z-index:9`,n.addEventListener(`click`,()=>{n.remove(),t.play()}),document.body.appendChild(n)}function Yt(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}exports.ODDIN_THEME=J,exports.PlaybackError=l,exports.applyTheme=X,exports.bootEmbed=qt,exports.clearDeviceId=we,exports.createPlayer=Ht,exports.deriveEventsBaseUrl=D,exports.detectDrmSupport=Fe,exports.enterVideoFullscreen=w,exports.exitVideoFullscreen=T,exports.fetchCatalog=_e,exports.fetchTournament=ye,exports.flattenMatches=xe,exports.getDeviceId=A,exports.isLowLatencyManifest=Le,exports.isOddinMessage=$,exports.licenseRequestHeaders=Ee,exports.mountEmbed=Wt,exports.pollToLive=pe,exports.resolveStream=y,exports.subscribeLiveState=E,exports.videoFullscreenActive=C,exports.watchStatus=Se;
128
128
  //# sourceMappingURL=index.cjs.map