@oddin-gg/havik-player 1.8.1 → 1.8.3

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,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,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`}}var d=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function f(e){return d.has(e)}async function p(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 m(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 h(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 g(e,t){let n=await p(t.credential),r=t.headers??new Headers;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: ${_(e)}`,{cause:e})}}function _(e){return e instanceof Error?e.message:String(e)}var ee=1e3,te=3e4,v=600*1e3,y=300*1e3,b=1e3,x={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function S(e){let t=e===!0||e===!1?{}:e,n=Math.max(b,t.floorMs??ee),r=Math.max(n,t.ceilMs??te),i=Math.max(0,t.imminentMs??v),a=Math.max(r,t.sanityFloorMs??y);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:ne(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function ne(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 re(e,t,n){return Math.min(n,Math.max(t,e))}function ie(e){return Math.round(e*(1+.15*Math.random()))}function ae(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:re(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 oe(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 C(e,t,n){let r=S(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)||!f(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=ae(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=ie(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:x[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await oe(d,n)}}}async function w(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new l(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await g(m(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal});if(!t.ok)throw await se(t);return le(await t.json(),e.matchUrn)}function T(e){let t=()=>w(e);return e.waitForLive?C(t,e.waitForLive,e.signal):t()}async function se(e){let t=h(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 ce=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`]);function E(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 le(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:E(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:E(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:E(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:E(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))ce.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}async function ue(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=m(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let a=await g(r,{credential:e.credential,signal:e.signal,headers:i});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:de(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function de(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 fe(e){let t=m(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await g(t,{credential:e.credential,signal:e.signal,headers:n});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:pe(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function pe(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 me(e){return e.tournaments.flatMap(e=>e.matches)}function he(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=m(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let o=await g(t,{credential:e.credential,signal:n.signal,headers:r});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 D(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,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,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`}}var d=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function f(e){return d.has(e)}async function p(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 m(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 h(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 g(e,t){let n=await p(t.credential),r=t.headers??new Headers;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: ${_(e)}`,{cause:e})}}function _(e){return e instanceof Error?e.message:String(e)}var ee=1e3,te=3e4,ne=600*1e3,v=300*1e3,y=1e3,b={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function re(e){let t=e===!0||e===!1?{}:e,n=Math.max(y,t.floorMs??ee),r=Math.max(n,t.ceilMs??te),i=Math.max(0,t.imminentMs??ne),a=Math.max(r,t.sanityFloorMs??v);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:ie(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function ie(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 ae(e,t,n){return Math.min(n,Math.max(t,e))}function oe(e){return Math.round(e*(1+.15*Math.random()))}function se(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:ae(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 ce(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 x(e,t,n){let r=re(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)||!f(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=se(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=oe(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:b[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await ce(d,n)}}}async function S(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new l(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await g(m(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal});if(!t.ok)throw await w(t);return ue(await t.json(),e.matchUrn)}function C(e){let t=()=>S(e);return e.waitForLive?x(t,e.waitForLive,e.signal):t()}async function w(e){let t=h(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 le=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`]);function T(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 ue(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:T(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:T(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:T(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:T(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))le.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}async function de(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=m(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let a=await g(r,{credential:e.credential,signal:e.signal,headers:i});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:fe(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function fe(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 pe(e){let t=m(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await g(t,{credential:e.credential,signal:e.signal,headers:n});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:me(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function me(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 he(e){return e.tournaments.flatMap(e=>e.matches)}function ge(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=m(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let o=await g(t,{credential:e.credential,signal:n.signal,headers:r});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(`
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 p(e.credential);if(i)return;let a=m(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 O(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var k=`havik.player.deviceId`,A;function j(){if(A)return A;try{let e=globalThis.localStorage?.getItem(k);if(e)return A=e,e}catch{}let e=N();A=e;try{globalThis.localStorage?.setItem(k,e)}catch{}return e}function M(){A=void 0;try{globalThis.localStorage?.removeItem(k)}catch{}}function N(){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 P(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??j(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var F=5e3,I=`video/mp4; codecs="avc1.42E01E"`,L=`audio/mp4; codecs="mp4a.40.2"`,R={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function ge(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:I,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:L,robustness:``,encryptionScheme:`cbcs`}]}]:[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:I,robustness:`SW_SECURE_DECODE`,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:L,robustness:`SW_SECURE_CRYPTO`,encryptionScheme:`cbcs`}]}]}function z(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 _e(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??F,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=R[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 z((await z(i(n,ge(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 ve=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function ye(e){return ve.test(e)}var be={droppedFrames:0};function B(e){return e.getVideoPlaybackQuality?.()?.droppedVideoFrames??0}function xe(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 Se(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 V(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}var H=class{name=`native`;deps;onLoaded;onError;onEncrypted;fairplayLicenseUrl;keySession=null;fairplayArmed=!1;fairplayKeyIV;constructor(e){this.deps=e}async load(){let{video:e,descriptor:t,emit:n}=this.deps;if(t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new l(`INTERNAL`,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()}this.onLoaded=()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=t.manifestUrl,e.load()}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(t===403?`FORBIDDEN`:`INTERNAL`,t,e),fatal:n});this.onEncrypted=a=>{let c=a;!c.initData||this.fairplayArmed||(this.fairplayArmed=!0,this.fairplayKeyIV=Se(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)throw Error(`certificate ${l.status}`);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={droppedFrames:B(e)};return e.duration===1/0&&(t.isLive=!0,e.seekable.length>0&&(t.atLiveEdge=e.currentTime>=e.seekable.end(e.seekable.length-1)-2)),t}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`);try{e.load()}catch{}}};function Ce(){return c.default.isSupported()}var we=3,Te=5,Ee=3,De=3e4,Oe=12e3,ke=3e3,U=6e3,Ae=2,je=9,Me=.5;function Ne(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Ae;let t=Math.max(12,e.liveSyncDuration+je);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Pe(e,e.liveSyncDuration)}function Pe(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 W=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;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;chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;constructor(e){this.deps=e,this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=V(n),a=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!a){r({type:`error`,error:new l(`INTERNAL`,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)}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+Me||(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,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:!0,...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`},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)}}:{},...s};Ne(d);let f=new c.default(d);this.hls=f,f.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l({type:`ready`})}),f.on(c.default.Events.FRAG_BUFFERED,()=>{(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.recoveryResetTimer=null},De))}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>{if(this.detectedLowLatency)return;let n=t.details;(n?.partList?.length||(n?.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=setInterval(()=>this.checkEndStale(),ke),f.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>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)return;if(e==null){t.autoLevelCapping=-1;return}let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),t.autoLevelCapping=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={droppedFrames:B(this.deps.video),lowLatency:this.detectedLowLatency};if(e){typeof e.latency==`number`&&(t.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(t.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(t.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let n=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;n&&(t.levelHeight=n.height),typeof n?.details?.live==`boolean`&&(t.isLive=n.details.live,typeof e.liveSyncPosition==`number`&&(t.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return t}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>U&&this.suspendChasing(),e>Oe&&this.emitEnded(`stalled`)}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);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(this.clearRecoveryReset(),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>=Ee)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{if(this.licenseRetryTimer=null,this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during license retry`,e)}this.hls=null,this.startHls()}},n),!0}onError(e){if(!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});return}if(e.type===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<Te){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});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});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``;return new l(n===401?`UNAUTHORIZED`:n===403||t===`DRM`?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}},G={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`},K={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 q(e,t){let n={...G,...t};for(let t of Object.keys(K))e.style.setProperty(K[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var J=`havik-player-styles`,Fe=`
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 p(e.credential);if(i)return;let a=m(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=M();k=e;try{globalThis.localStorage?.setItem(O,e)}catch{}return e}function j(){k=void 0;try{globalThis.localStorage?.removeItem(O)}catch{}}function M(){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 N(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 P=5e3,F=`video/mp4; codecs="avc1.42E01E"`,I=`audio/mp4; codecs="mp4a.40.2"`,L={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function _e(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:F,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:I,robustness:``,encryptionScheme:`cbcs`}]}]:[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:F,robustness:`SW_SECURE_DECODE`,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:I,robustness:`SW_SECURE_CRYPTO`,encryptionScheme:`cbcs`}]}]}function R(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 ve(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??P,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=L[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 R((await R(i(n,_e(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 ye=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function be(e){return ye.test(e)}var xe={droppedFrames:0};function z(e){return e.getVideoPlaybackQuality?.()?.droppedVideoFrames??0}function Se(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 Ce(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 B(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function V(){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 H=class{name=`native`;deps;onLoaded;onError;onEncrypted;fairplayLicenseUrl;keySession=null;fairplayArmed=!1;fairplayKeyIV;constructor(e){this.deps=e}async load(){let{video:e,descriptor:t,emit:n}=this.deps;if(t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new l(`INTERNAL`,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()}this.onLoaded=()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=t.manifestUrl,e.load()}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(t===403?`FORBIDDEN`:`INTERNAL`,t,e),fatal:n});this.onEncrypted=a=>{let c=a;!c.initData||this.fairplayArmed||(this.fairplayArmed=!0,this.fairplayKeyIV=Ce(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)throw Error(`certificate ${l.status}`);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={droppedFrames:z(e)};return e.duration===1/0&&(t.isLive=!0,e.seekable.length>0&&(t.atLiveEdge=e.currentTime>=e.seekable.end(e.seekable.length-1)-2)),t}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`);try{e.load()}catch{}}};function we(){return c.default.isSupported()}var Te=3,Ee=5,De=3,Oe=3e4,ke=12e3,U=3e3,Ae=6e3,je=2,Me=9,Ne=.5;function Pe(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=je;let t=Math.max(12,e.liveSyncDuration+Me);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Fe(e,e.liveSyncDuration)}function Fe(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 W=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;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;chaseSuspended=!1;savedLiveMaxLatency;savedMaxSyncRate;constructor(e){this.deps=e,this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=B(n)&&V(),a=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!a){r({type:`error`,error:new l(`INTERNAL`,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)}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+Ne||(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,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:!0,...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`},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)}}:{},...s};Pe(d);let f=new c.default(d);this.hls=f,f.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l({type:`ready`})}),f.on(c.default.Events.FRAG_BUFFERED,()=>{(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.recoveryResetTimer=null},Oe))}),f.on(c.default.Events.LEVEL_LOADED,(e,t)=>{if(this.detectedLowLatency)return;let n=t.details;(n?.partList?.length||(n?.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=setInterval(()=>this.checkEndStale(),U),f.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>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)return;if(e==null){t.autoLevelCapping=-1;return}let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),t.autoLevelCapping=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={droppedFrames:z(this.deps.video),lowLatency:this.detectedLowLatency};if(e){typeof e.latency==`number`&&(t.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(t.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(t.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let n=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;n&&(t.levelHeight=n.height),typeof n?.details?.live==`boolean`&&(t.isLive=n.details.live,typeof e.liveSyncPosition==`number`&&(t.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return t}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>Ae&&this.suspendChasing(),e>ke&&this.emitEnded(`stalled`)}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);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(this.clearRecoveryReset(),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>=De)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{if(this.licenseRetryTimer=null,this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during license retry`,e)}this.hls=null,this.startHls()}},n),!0}onError(e){if(!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});return}if(e.type===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<Ee){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});return}if(e.type===c.default.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<Te){this.mediaRecoveries+=1,t.recoverMediaError();return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``;return new l(n===401?`UNAUTHORIZED`:n===403||t===`DRM`?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}},G={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`},K={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 q(e,t){let n={...G,...t};for(let t of Object.keys(K))e.style.setProperty(K[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var J=`havik-player-styles`,Ie=`
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}
@@ -54,6 +54,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
54
54
 
55
55
  .havik-watermark{position:absolute;top:12px;right:14px;height:22px;opacity:.85;pointer-events:none;
56
56
  content:'';background:var(--havik-logo) center/contain no-repeat;width:90px}
57
+ /* A status card carries its own logo — the corner watermark would duplicate it. */
58
+ .havik-player.havik-has-status .havik-watermark{display:none}
57
59
 
58
60
  .havik-bar{position:absolute;left:0;right:0;bottom:0;padding:0 12px 8px;
59
61
  opacity:1;transition:opacity .25s;z-index:2}
@@ -122,5 +124,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
122
124
  .havik-menu__item:hover{background:var(--havik-surface-muted,#2a2c36)}
123
125
  .havik-menu__item[aria-checked="true"]{color:var(--havik-accent,#E1B600);font-weight:600}
124
126
  .havik-menu__item[aria-checked="true"]::after{content:'✓'}
125
- `;function Ie(e=document){if(e.getElementById(J))return;let t=e.createElement(`style`);t.id=J,t.textContent=Fe,e.head.appendChild(t)}var Le={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 Y(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Le[e]}</svg>`}var Re=3e3,ze=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`]);function Be(e){return new Ve(e)}var Ve=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;hasPlayed=!1;lastError=null;logoUrl;statusOverlays;endedMessage;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??Re,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.endedMessage=e.endedMessage??`This stream has ended`,this.errorMessage=e.errorMessage,Ie(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=Y(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Y(`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=Y(`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(`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.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)}renderStatus(e){if(e===this.statusKind||(this.statusKind=e,this.statusBox?.remove(),this.statusBox=null,!e))return;let t=this.doc.createElement(`div`);if(t.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,t.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=Y(`play`),e.addEventListener(`click`,()=>void this.player.play()),t.append(e)}else{let n=this.doc.createElement(`div`);if(n.className=`havik-status__msg`,n.textContent=e===`ended`?this.endedMessage:e===`waiting`?`Starting soon…`:this.errorMessage??this.lastError?.message??`Playback unavailable`,t.append(n),e===`error`&&this.lastError&&!ze.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Y(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),t.append(e)}}this.root.append(t),this.statusBox=t,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=`${X(this.video.currentTime)} / ${X(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(He(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(Ue(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(We(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(){let e=this.root,t=this.doc;try{t.fullscreenElement?await t.exitFullscreen?.():await e.requestFullscreen?.()}catch{}}syncFullscreen(){let e=this.doc.fullscreenElement===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=Y(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`)}};function X(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 He(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function Ue(e){return e.name||e.lang||`Track ${e.id}`}function We(e){return e.name||e.lang||`Track ${e.id}`}var Ge=6e3,Z=45e3,Ke=2e3,qe=3,Je=2e3,Ye=480*1e3;async function Q(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 Xe(e);return await t.start(),t}var Xe=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;armingSub=null;armSseTimer=null;armFallbackCtrl=null;_lastError=null;constructor(e){this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}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 w(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&&f(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}}beginArming(e,t){let n=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??O(this.opts.baseUrl);n?this.armWithSse(e,n,t):this.beginArmingByPolling(e)}beginArmingByPolling(e){T({...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){let r=!1,i=!1,a=new AbortController;this.armFallbackCtrl=a,this.setState(`waiting`);let o=this.opts.waitForLive,s=o&&o!==!0?o.kickoffAt:void 0,c=typeof s==`number`?s:typeof s==`string`?Date.parse(s):NaN,u=n??(Number.isFinite(c)?c:void 0);setTimeout(()=>{r||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:`tooEarly`,retryInMs:Z,attempt:1,elapsedMs:0,...u!==void 0&&u>Date.now()?{ttkMs:u-Date.now()}:{}})},0);let d=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,p=async t=>{if(!(r||d())){r=!0,this.closeArming(),a.abort();try{await this.onResolved(t,e)}catch(e){if(d())return;this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e)))}}},m=()=>{r||i||d()||(i=!0,T({...this.resolveOptions(),signal:a.signal,waitForLive:this.buildWaitConfig(e)}).then(e=>p(e)).catch(e=>{r||d()||a.signal.aborted||(r=!0,this.closeArming(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))}))},h=()=>{r||d()||w(this.resolveOptions()).then(e=>p(e)).catch(e=>{r||d()||e instanceof l&&f(e.code)||(r=!0,this.closeArming(),a.abort(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))})},g=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!r&&!d()&&m()},e)};g(Ge),this.armingSub=D({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>g(Z),onState:e=>{r||d()||(e.state===`live`||e.state===`gone`)&&setTimeout(h,Math.random()*Ke)},onError:()=>m()})}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;let n=await p(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.createEngine(e,n),i=xe(this.opts.video,e=>{this._state===`ended`||this._state===`error`||this.setState(e)});if(await r.load(),this.destroyed||t!==this.loadGen){i(),r.destroy();return}if(this._state===`error`){i(),r.destroy();return}this.engine=r,this.detachMedia=i,this.opts.maxBitrate!=null&&r.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t)}createEngine(e,t){let n={...this.opts.hlsConfig};this.opts.startLevel!=null&&(n.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(n.liveSyncDuration=this.opts.liveLatencyTarget);let r={video:this.opts.video,descriptor:e,credential:t,deviceId:j(),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,hlsConfig:n,emit:e=>this.onEngineEvent(e)},i=this.opts.engine??`auto`;if(i===`native`)return new H(r);if(i===`hls`)return new W(r);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&V(this.opts.video))return new H(r);if(Ce())return new W(r);if(V(this.opts.video))return new H(r);throw new l(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`ready`:this.emit(`ready`),this.opts.autoplay!==!1&&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`:e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??O(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=D({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`ended`||t.state===`gone`)&&this.onStreamEnded()},onAlive:()=>{n=0,r=!1},onError:()=>{this.destroyed||e!==this.loadGen||r||(n+=1,n>=qe&&(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(){this.destroyed||this.endedHandled||(this.endedHandled=!0,this.closeLiveState(),this.stopRefresh(),this.engine?.stop(),this.setState(`ended`))}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),q(n,this.opts.theme),this.container=n,this.controlBar=Be({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,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.emit(`pipchange`,!0),n=()=>this.emit(`pipchange`,!1);e.addEventListener(`enterpictureinpicture`,t),e.addEventListener(`leavepictureinpicture`,n),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,t),e.removeEventListener(`leavepictureinpicture`,n)}}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??Je);this.statsTimer=setInterval(()=>{this.engine&&this.emit(`stats`,this.engine.getStats())},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}scheduleLicenseRefresh(){this.stopRefresh();let e=this.opts.licenseRefreshMs??Ye;!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 w(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&&!f(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e))}}async play(){if(!this.destroyed)try{await this.opts.video.play()}catch(e){e instanceof DOMException&&e.name===`NotAllowedError`&&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()??be}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()}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.stopStats(),this.stopRefresh(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null;try{let t=await T({...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.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.detachPip?.(),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.emit(`error`,e)}setState(e){if(e!==this._state)switch(this._state=e,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`);break;default:break}}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 Ze(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 Qe=/^[A-Za-z0-9:_.-]{1,128}$/;function $e(){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 et(){let e=$e();nt();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`}),tt(t,e)})},o=async n=>{i?.destroy(),i=null;try{let r=await Q({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`&&Qe.test(e.matchUrn)&&o(e.matchUrn);break;case`oddin:destroy`:s();break}},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 tt(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 nt(){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=G,exports.PlaybackError=l,exports.applyTheme=q,exports.bootEmbed=et,exports.clearDeviceId=M,exports.createPlayer=Q,exports.deriveEventsBaseUrl=O,exports.detectDrmSupport=_e,exports.fetchCatalog=ue,exports.fetchTournament=fe,exports.flattenMatches=me,exports.getDeviceId=j,exports.isLowLatencyManifest=ye,exports.isOddinMessage=$,exports.licenseRequestHeaders=P,exports.mountEmbed=Ze,exports.pollToLive=C,exports.resolveStream=T,exports.subscribeLiveState=D,exports.watchStatus=he;
127
+ `;function Le(e=document){if(e.getElementById(J))return;let t=e.createElement(`style`);t.id=J,t.textContent=Ie,e.head.appendChild(t)}var Re={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 Y(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Re[e]}</svg>`}var ze=3e3,Be=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`]);function Ve(e){return new He(e)}var He=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;hasPlayed=!1;lastError=null;logoUrl;statusOverlays;endedMessage;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??ze,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.endedMessage=e.endedMessage??`This stream has ended`,this.errorMessage=e.errorMessage,Le(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=Y(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Y(`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=Y(`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(`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.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)}renderStatus(e){if(e===this.statusKind||(this.statusKind=e,this.statusBox?.remove(),this.statusBox=null,this.root.classList.toggle(`havik-has-status`,!!e),!e))return;let t=this.doc.createElement(`div`);if(t.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,t.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=Y(`play`),e.addEventListener(`click`,()=>void this.player.play()),t.append(e)}else{let n=this.doc.createElement(`div`);if(n.className=`havik-status__msg`,n.textContent=e===`ended`?this.endedMessage:e===`waiting`?`Starting soon…`:this.errorMessage??this.lastError?.message??`Playback unavailable`,t.append(n),e===`error`&&this.lastError&&!Be.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Y(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),t.append(e)}}this.root.append(t),this.statusBox=t,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=`${X(this.video.currentTime)} / ${X(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(Ue(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(We(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(Ge(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(){let e=this.root,t=this.doc;try{t.fullscreenElement?await t.exitFullscreen?.():await e.requestFullscreen?.()}catch{}}syncFullscreen(){let e=this.doc.fullscreenElement===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=Y(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 X(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 Ue(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function We(e){return e.name||e.lang||`Track ${e.id}`}function Ge(e){return e.name||e.lang||`Track ${e.id}`}var Ke=6e3,Z=45e3,qe=2e3,Je=3,Ye=2e3,Xe=480*1e3;async function Q(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 Ze(e);return await t.start(),t}var Ze=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;armingSub=null;armSseTimer=null;armFallbackCtrl=null;_lastError=null;constructor(e){this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}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 S(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&&f(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}}beginArming(e,t){let n=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??D(this.opts.baseUrl);n?this.armWithSse(e,n,t):this.beginArmingByPolling(e)}beginArmingByPolling(e){C({...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){let r=!1,i=!1,a=new AbortController;this.armFallbackCtrl=a,this.setState(`waiting`);let o=this.opts.waitForLive,s=o&&o!==!0?o.kickoffAt:void 0,c=typeof s==`number`?s:typeof s==`string`?Date.parse(s):NaN,u=n??(Number.isFinite(c)?c:void 0);setTimeout(()=>{r||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:`tooEarly`,retryInMs:Z,attempt:1,elapsedMs:0,...u!==void 0&&u>Date.now()?{ttkMs:u-Date.now()}:{}})},0);let d=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,p=async t=>{if(!(r||d())){r=!0,this.closeArming(),a.abort();try{await this.onResolved(t,e)}catch(e){if(d())return;this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e)))}}},m=()=>{r||i||d()||(i=!0,C({...this.resolveOptions(),signal:a.signal,waitForLive:this.buildWaitConfig(e)}).then(e=>p(e)).catch(e=>{r||d()||a.signal.aborted||(r=!0,this.closeArming(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))}))},h=()=>{r||d()||S(this.resolveOptions()).then(e=>p(e)).catch(e=>{r||d()||e instanceof l&&f(e.code)||(r=!0,this.closeArming(),a.abort(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))})},g=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!r&&!d()&&m()},e)};g(Ke),this.armingSub=E({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>g(Z),onState:e=>{r||d()||(e.state===`live`||e.state===`gone`)&&setTimeout(h,Math.random()*qe)},onError:()=>m()})}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;let n=await p(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.createEngine(e,n),i=Se(this.opts.video,e=>{this._state===`ended`||this._state===`error`||this.setState(e)});if(await r.load(),this.destroyed||t!==this.loadGen){i(),r.destroy();return}if(this._state===`error`){i(),r.destroy();return}this.engine=r,this.detachMedia=i,this.opts.maxBitrate!=null&&r.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t)}createEngine(e,t){let n={...this.opts.hlsConfig};this.opts.startLevel!=null&&(n.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(n.liveSyncDuration=this.opts.liveLatencyTarget);let r={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,hlsConfig:n,emit:e=>this.onEngineEvent(e)},i=this.opts.engine??`auto`;if(i===`native`)return new H(r);if(i===`hls`)return new W(r);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&B(this.opts.video)&&V())return new H(r);if(we())return new W(r);if(B(this.opts.video))return new H(r);throw new l(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`ready`:this.emit(`ready`),this.opts.autoplay!==!1&&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`:e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}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===`ended`||t.state===`gone`)&&this.onStreamEnded()},onAlive:()=>{n=0,r=!1},onError:()=>{this.destroyed||e!==this.loadGen||r||(n+=1,n>=Je&&(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(){this.destroyed||this.endedHandled||(this.endedHandled=!0,this.closeLiveState(),this.stopRefresh(),this.engine?.stop(),this.setState(`ended`))}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),q(n,this.opts.theme),this.container=n,this.controlBar=Ve({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,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.emit(`pipchange`,!0),n=()=>this.emit(`pipchange`,!1);e.addEventListener(`enterpictureinpicture`,t),e.addEventListener(`leavepictureinpicture`,n),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,t),e.removeEventListener(`leavepictureinpicture`,n)}}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??Ye);this.statsTimer=setInterval(()=>{this.engine&&this.emit(`stats`,this.engine.getStats())},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}scheduleLicenseRefresh(){this.stopRefresh();let e=this.opts.licenseRefreshMs??Xe;!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 S(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&&!f(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e))}}async play(){if(!this.destroyed)try{await this.opts.video.play()}catch(e){e instanceof DOMException&&e.name===`NotAllowedError`&&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()??xe}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()}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.stopStats(),this.stopRefresh(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null;try{let t=await C({...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.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.detachPip?.(),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.emit(`error`,e)}setState(e){if(e!==this._state)switch(this._state=e,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`);break;default:break}}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 Qe(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 $e=/^[A-Za-z0-9:_.-]{1,128}$/;function et(){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 tt(){let e=et();rt();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`}),nt(t,e)})},o=async n=>{i?.destroy(),i=null;try{let r=await Q({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`&&$e.test(e.matchUrn)&&o(e.matchUrn);break;case`oddin:destroy`:s();break}},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 nt(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 rt(){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=G,exports.PlaybackError=l,exports.applyTheme=q,exports.bootEmbed=tt,exports.clearDeviceId=j,exports.createPlayer=Q,exports.deriveEventsBaseUrl=D,exports.detectDrmSupport=ve,exports.fetchCatalog=de,exports.fetchTournament=pe,exports.flattenMatches=he,exports.getDeviceId=A,exports.isLowLatencyManifest=be,exports.isOddinMessage=$,exports.licenseRequestHeaders=N,exports.mountEmbed=Qe,exports.pollToLive=x,exports.resolveStream=C,exports.subscribeLiveState=E,exports.watchStatus=ge;
126
128
  //# sourceMappingURL=index.cjs.map