@oddin-gg/havik-player 1.6.2 → 1.7.0

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
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,v=3e4,y=600*1e3,b=300*1e3,x=1e3,S={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function C(e){let t=e===!0||e===!1?{}:e,n=Math.max(x,t.floorMs??ee),r=Math.max(n,t.ceilMs??v),i=Math.max(0,t.imminentMs??y),a=Math.max(r,t.sanityFloorMs??b);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:te(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function te(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 ne(e,t,n){return Math.min(n,Math.max(t,e))}function re(e){return Math.round(e*(1+.15*Math.random()))}function ie(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:ne(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 ae(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 w(e,t,n){let r=C(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=ie(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=re(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:S[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await ae(d,n)}}}async function T(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 oe(t);return ce(await t.json(),e.matchUrn)}function E(e){let t=()=>T(e);return e.waitForLive?w(t,e.waitForLive,e.signal):t()}async function oe(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 se=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`]);function D(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 ce(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:D(`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:D(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:D(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:D(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))se.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}async function le(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:ue(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function ue(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 de(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:fe(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function fe(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 pe(e){return e.tournaments.flatMap(e=>e.matches)}function me(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 O(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 k(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var A=`havik.player.deviceId`,j;function M(){if(j)return j;try{let e=globalThis.localStorage?.getItem(A);if(e)return j=e,e}catch{}let e=P();j=e;try{globalThis.localStorage?.setItem(A,e)}catch{}return e}function N(){j=void 0;try{globalThis.localStorage?.removeItem(A)}catch{}}function P(){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 F(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??M(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var I=5e3,L=`video/mp4; codecs="avc1.42E01E"`,R=`audio/mp4; codecs="mp4a.40.2"`,z={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function he(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:L,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:R,robustness:``,encryptionScheme:`cbcs`}]}]:[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:L,robustness:`SW_SECURE_DECODE`,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:R,robustness:`SW_SECURE_CRYPTO`,encryptionScheme:`cbcs`}]}]}function B(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 ge(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??I,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=z[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 B((await B(i(n,he(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 _e=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function ve(e){return _e.test(e)}var ye={droppedFrames:0};function V(e){return e.getVideoPlaybackQuality?.()?.droppedVideoFrames??0}function be(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function H(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}var U=class{name=`native`;deps;onLoaded;onError;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}n({type:`error`,error:new l(`INTERNAL`,0,`the native HLS fallback engine does not drive FairPlay EME; relying on OS-trusted passthrough`),fatal:!1})}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()}setLicenseUrls(e){}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:V(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);try{e.pause()}catch{}e.removeAttribute(`src`);try{e.load()}catch{}}};function xe(){return c.default.isSupported()}var Se=3,Ce=5,we=3,Te=3e4,Ee=12e3,De=3e3,W=6e3,Oe=2,ke=9,Ae=.5;function je(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Oe;let t=Math.max(12,e.liveSyncDuration+ke);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Me(e,e.liveSyncDuration)}function Me(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 Ne=class{name=`hls`;hls=null;deps;licenseUrl;fairplayLicenseUrl;fairplayCertUrl;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,this.fairplayLicenseUrl=e.descriptor.drm?.fairplay?.licenseUrl,this.fairplayCertUrl=e.descriptor.drm?.fairplay?.certificateUrl}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=H(n),a=!!e.drm?.widevine?.licenseUrl&&!i,o=!!(e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&i);if(e.drmEnabled&&!a&&!o){r({type:`error`,error:new l(`INTERNAL`,0,`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+Ae||(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=!!(this.fairplayLicenseUrl&&this.fairplayCertUrl&&H(e)),f={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}}:{},...d?{"com.apple.fps":{licenseUrl:this.fairplayLicenseUrl,serverCertificateUrl:this.fairplayCertUrl,generateRequest(e,t,n){if(t)return{initDataType:e,initData:t};let r=n.decryptdata?.uri;if(r?.startsWith(`skd://`)){let e=r.slice(6).split(`:`)[0].toLowerCase(),t=e?`skd://${e}`:r;return{initDataType:`skd`,initData:new TextEncoder().encode(t).buffer}}return{initDataType:e,initData:t}}}}:{}},drmSystemOptions:d?{videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`}:{videoRobustness:`SW_SECURE_DECODE`,audioRobustness:`SW_SECURE_CRYPTO`,videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`},...d?{requestMediaKeySystemAccessFunc:(e,t)=>{let n=e===`com.apple.fps`?t.map(e=>({...e,initDataTypes:[...new Set([...e.initDataTypes??[],`skd`])]})):t;return navigator.requestMediaKeySystemAccess(e,n)}}:{},licenseXhrSetup:(e,a)=>{let o=a.includes(`/license/fairplay`)?this.fairplayLicenseUrl??a:this.licenseUrl??a;e.open(`POST`,o,!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};if(d){let e=f.xhrSetup,t=()=>this.fairplayCertUrl;f.xhrSetup=(r,i)=>{let a=e?.(r,i),o=()=>{i===t()&&(r.readyState===XMLHttpRequest.UNSENT&&r.open(`GET`,i,!0),r.setRequestHeader(`x-api-key`,n.apiKey))};return a&&typeof a.then==`function`?a.then(()=>o()):(o(),a)}}je(f);let p=new c.default(f);this.hls=p,p.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l({type:`ready`})}),p.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},Te))}),p.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}))}),p.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.endWatchdog=setInterval(()=>this.checkEndStale(),De),p.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>l({type:`qualitychange`,index:t.level})),p.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),p.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),p.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),p.loadSource(t.manifestUrl),p.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),e.fairplay&&(this.fairplayLicenseUrl=e.fairplay)}getStats(){let e=this.hls,t={droppedFrames:V(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>W&&this.suspendChasing(),e>Ee&&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>=we)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<Ce){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<Se){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`,Pe=`
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 k(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var A=`havik.player.deviceId`,j;function M(){if(j)return j;try{let e=globalThis.localStorage?.getItem(A);if(e)return j=e,e}catch{}let e=P();j=e;try{globalThis.localStorage?.setItem(A,e)}catch{}return e}function N(){j=void 0;try{globalThis.localStorage?.removeItem(A)}catch{}}function P(){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 F(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??M(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var I=5e3,L=`video/mp4; codecs="avc1.42E01E"`,R=`audio/mp4; codecs="mp4a.40.2"`,z={widevine:[`com.widevine.alpha`],fairplay:[`com.apple.fps`]};function he(e){return e===`fairplay`?[{initDataTypes:[`sinf`,`skd`,`cenc`],videoCapabilities:[{contentType:L,robustness:``,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:R,robustness:``,encryptionScheme:`cbcs`}]}]:[{initDataTypes:[`cenc`],videoCapabilities:[{contentType:L,robustness:`SW_SECURE_DECODE`,encryptionScheme:`cbcs`}],audioCapabilities:[{contentType:R,robustness:`SW_SECURE_CRYPTO`,encryptionScheme:`cbcs`}]}]}function B(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 ge(e={}){let t=e.systems??[`widevine`,`fairplay`],n=e.timeoutMs??I,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=z[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 B((await B(i(n,he(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 _e=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function ve(e){return _e.test(e)}var ye={droppedFrames:0};function V(e){return e.getVideoPlaybackQuality?.()?.droppedVideoFrames??0}function be(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function H(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}var U=class{name=`native`;deps;onLoaded;onError;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}n({type:`error`,error:new l(`INTERNAL`,0,`the native HLS fallback engine does not drive FairPlay EME; relying on OS-trusted passthrough`),fatal:!1})}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()}setLicenseUrls(e){}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:V(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);try{e.pause()}catch{}e.removeAttribute(`src`);try{e.load()}catch{}}};function xe(){return c.default.isSupported()}var Se=3,Ce=5,we=3,Te=3e4,Ee=12e3,De=3e3,W=6e3,Oe=2,ke=9,Ae=.5;function je(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Oe;let t=Math.max(12,e.liveSyncDuration+ke);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),Me(e,e.liveSyncDuration)}function Me(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 Ne=class{name=`hls`;hls=null;deps;licenseUrl;fairplayLicenseUrl;fairplayCertUrl;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,this.fairplayLicenseUrl=e.descriptor.drm?.fairplay?.licenseUrl,this.fairplayCertUrl=e.descriptor.drm?.fairplay?.certificateUrl}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=H(n),a=!!e.drm?.widevine?.licenseUrl&&!i,o=!!(e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&i);if(e.drmEnabled&&!a&&!o){r({type:`error`,error:new l(`INTERNAL`,0,`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+Ae||(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=!!(this.fairplayLicenseUrl&&this.fairplayCertUrl&&H(e)),f={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}}:{},...d?{"com.apple.fps":{licenseUrl:this.fairplayLicenseUrl,serverCertificateUrl:this.fairplayCertUrl,generateRequest(e,t,n){if(t)return{initDataType:e,initData:t};let r=n.decryptdata?.uri;return r?.startsWith(`skd://`)?{initDataType:`skd`,initData:new TextEncoder().encode(r).buffer}:{initDataType:e,initData:t}}}}:{}},drmSystemOptions:d?{videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`}:{videoRobustness:`SW_SECURE_DECODE`,audioRobustness:`SW_SECURE_CRYPTO`,videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`},...d?{requestMediaKeySystemAccessFunc:(e,t)=>{let n=e===`com.apple.fps`?t.map(e=>({...e,initDataTypes:[...new Set([...e.initDataTypes??[],`skd`])]})):t;return navigator.requestMediaKeySystemAccess(e,n)}}:{},licenseXhrSetup:(e,a)=>{let o=a.includes(`/license/fairplay`)?this.fairplayLicenseUrl??a:this.licenseUrl??a;e.open(`POST`,o,!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};if(d){let e=f.xhrSetup,t=()=>this.fairplayCertUrl;f.xhrSetup=(r,i)=>{let a=e?.(r,i),o=()=>{i===t()&&(r.readyState===XMLHttpRequest.UNSENT&&r.open(`GET`,i,!0),r.setRequestHeader(`x-api-key`,n.apiKey))};return a&&typeof a.then==`function`?a.then(()=>o()):(o(),a)}}je(f);let p=new c.default(f);this.hls=p,p.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l({type:`ready`})}),p.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},Te))}),p.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}))}),p.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.endWatchdog=setInterval(()=>this.checkEndStale(),De),p.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>l({type:`qualitychange`,index:t.level})),p.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>l({type:`audiotrackchange`,id:t.id})),p.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>l({type:`texttrackchange`,id:t.id})),p.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),p.loadSource(t.manifestUrl),p.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),e.fairplay&&(this.fairplayLicenseUrl=e.fairplay)}getStats(){let e=this.hls,t={droppedFrames:V(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>W&&this.suspendChasing(),e>Ee&&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>=we)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<Ce){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<Se){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`,Pe=`
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}