nixamp 0.26.3 → 0.26.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function t(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function n(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var r=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function i(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&r.has(e.slice(n+1).toLowerCase())}function a(){let e=document.getElementById(`sr-status`);if(!e)return;let t=[`note`,`account-note`,`remote-state`,`transcript-audio-note`,`notify-note`,`notify-phone-note`,`persona-note`],n=new Map,r,i=``;for(let a of t){let t=document.getElementById(a);t&&(n.set(a,t.textContent?.trim()??``),new MutationObserver(()=>{let o=t.textContent?.trim()??``;n.get(a)!==o&&(n.set(a,o),o&&!t.closest(`[hidden], [data-closed], [data-collapsed]`)&&(i=o,clearTimeout(r),r=setTimeout(()=>{e.textContent!==i&&(e.textContent=i)},200)))}).observe(t,{childList:!0,characterData:!0,subtree:!0}))}}var o=new WeakMap;function s(e,...t){if(!e.contains(document.activeElement)){o.delete(e),e.replaceChildren(...t);return}let n=o.has(e);if(o.set(e,t),n)return;let r=()=>{let t=o.get(e);if(t){if(e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}o.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}function c(e){if(!/\.(?:mp4|m4v|mkv|webm|mov|avi|mp3|m4a|flac|ogg|opus|wav|aac)$/i.test(e))return e;let t=(e.split(/[\\/]/).pop()??e).replace(/\.[^.]+$/,``);return t.replace(/^0\d+[_ .-]+(?:\d+[_ .-]+)?/,``).replace(/_+/g,` `).trim()||t}function l(e){if(/^(?:[\\/]|[A-Za-z]:)/.test(e))return[];let t=e.split(/[\\/]/).filter(Boolean);return t.some(e=>e===`..`)?[]:t.filter(e=>e!==`.`).map(e=>e.replace(/_+/g,` `))}function u(e,t,n=`Live`){let r=e[t];if(!r){let e=c(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${c(r.title)}`:c(r.title),a=l(r.folder??``),o=l(r.group??``).join(` › `),s=[...o?[o]:[],...a],u=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,d=e.map((e,t)=>({one:e,at:t})).filter(({one:e})=>(e.group??``)===(r.group??``)&&(e.folder??``)===(r.folder??``)&&(s.length>0||e.album===r.album));return{title:i,context:u,position:`Playlist · ${d.findIndex(({at:e})=>e===t)+1} of ${d.length}`,fullTitle:u?`${u} › ${i}`:i}}var d=`modulepreload`,f=function(e){return`/`+e},p={},m=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=f(t,n),t=s(t),t in p)return;p[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:d,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},h=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],g=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function ee(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of g)if(t.test(e.mimeType))return n}let t=_(e.src);for(let[e,n]of h)if(e.test(t))return n;return`unknown`}function _(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function te(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function ne(e,t){let n=ee(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function v(e,t){let n=t.capabilities??te(),r=ne({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await m(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-BJCEkhkX.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await m(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-DLNvQAAS.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await m(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var re=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),ie=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function ae(e){let t=e.lastIndexOf(`.`);return t>0&&ie.has(e.slice(t+1).toLowerCase())}function oe(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&re.has(e.slice(n+1).toLowerCase())}function se(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ce(e){return e.filter(e=>oe(e.name,e.type)).sort((e,t)=>se(y(e),y(t))).map(e=>({title:n(e.name),artist:``,album:le(y(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0,...ae(e.name)?{kind:`mpegts`}:{}}))}function y(e){return e.webkitRelativePath||e.name}function le(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function ue(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var b=2048;function x(e){if(e.startsWith(`blob:`)||e.startsWith(`data:`))return!0;try{let t=globalThis.location?.origin;return t?new URL(e,t).origin===t:!1}catch{return!1}}function de(e,t){return e||t===`hls`||t===`mpegts`}var fe=class{elements;handlers;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;wired=new WeakSet;active;frequencies=new Uint8Array;analysable=!0;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video]){t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&this.handlers.onError(S(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get needsInteraction(){return this.playBlocked}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(!this.context)try{this.context=new t({sampleRate:48e3})}catch{this.context=new t}if(this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=b,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.analyser.connect(this.output),this.output.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}audioInput(){if(!this.analysable)throw Error(`This source blocks audio access, so its audio cannot be translated here.`);if(this.ensureGraph(this.active),!this.context||!this.analyser)throw Error(`This browser cannot capture player audio.`);return{context:this.context,node:this.analyser}}translatedAudio(e){this.output&&(this.output.gain.value=+!e)}get mediaKey(){return this.active.currentSrc||this.active.src}get loaded(){return!!(this.active.currentSrc||this.active.src)}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:ee({src:e.url})),r=de(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||x(e.url)||(this.handlers.readable?.(e.url)??!1);r.crossOrigin=i?`anonymous`:null,r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await v(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}let a=this.active.currentSrc||this.active.src||e.url;this.analysable=i||a.startsWith(`blob:`)||x(a),t&&await this.play()}async play(){this.analysable&&this.ensureGraph(this.active),this.playBlocked=!1;try{await this.active.play()}catch(e){if(e instanceof Error&&e.name===`NotAllowedError`){this.playBlocked=!0,this.handlers.onBusy?.(!1),this.handlers.onState(!1);return}this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){this.playBlocked=!1,this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function S(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function pe(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function me(e,t){return{...t,tracks:t.tracks??e.tracks}}function he(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function ge(e,t,n=``){let r=`${e===``?``:he(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function _e(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=/^\/api\/channels\/([^/]+)\/?$/.exec(t.pathname),r=/^\/api\/media\/(\d+)\/?$/.exec(t.pathname),i=/^\/api\/live\/?$/.test(t.pathname);if(!n&&!r&&!i)return null;let a=t.searchParams.get(`k`)??``,o=a?`${t.origin}/view/${a}`:t.origin,s=`live`;if(r&&(s=`track:${r[1]}`),n)try{s=`channel:${decodeURIComponent(n[1]??``)}`}catch{s=`channel:${n[1]??``}`}return{view:o,what:s}}function ve(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:he(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var C=null;function w(e){if(!e&&C!==null)return C;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(C=n),n}catch{return!1}}function ye(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return ge(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function be(e){if(typeof e!=`object`||!e)return null;let t=e,n=pe(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}function xe(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var Se=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return xe(this.base,e)}url(e){let t=ge(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=ve(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(ge(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=be(Ce(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(ge(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=be(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=w()){return ye(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function Ce(e){try{return JSON.parse(e)}catch{return null}}async function we(e,t,n=``){try{let r=await fetch(ge(e,`/api/state`,n),{signal:t});return r.ok?be(await r.json()):null}catch{return null}}function Te(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function Ee(e,t=``,n){let r;try{r=await fetch(ge(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function De(e,t,n=``){try{let r=await fetch(ge(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function Oe(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var ke=.14,T=.02;function Ae(e,t){let n=[];for(let r=0;r<=e;r++){let i=r/e,a=Math.round(1*(t/1)**i),o=n[n.length-1];n.push(o===void 0?a:Math.max(a,o+1))}return n}function je(e,t){let n=[];for(let r=0;r+1<t.length;r++){let i=Math.min(t[r],e.length),a=Math.min(Math.max(t[r+1],i+1),e.length),o=0,s=0;for(let t=i;t<a;t++)o+=e[t],s++;n.push(s===0?0:o/s/255)}return n}function Me(e,t,n=ke){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Ne(e,t,n=T){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function Pe(e,t,n,r,i){let{width:a,height:o}=t;if(a<=0||o<=0||n.length===0)return;e.clearRect(0,0,a,o);let s=a/n.length,c=Math.max(1,s*.72),l=Math.max(2,o*.012);e.fillStyle=i.bar,n.forEach((t,n)=>{let r=Math.max(1,t*(o-l*2));e.fillRect(n*s+(s-c)/2,o-r,c,r)}),e.fillStyle=i.peak,r.forEach((t,n)=>{let r=o-Math.max(1,t*(o-l*2))-l*2;e.fillRect(n*s+(s-c)/2,Math.max(0,r),c,l)})}function E(e,t){return{name:String(e?.name??e?.displayName??e?.abbreviation??``),score:typeof e?.score==`number`?e.score:typeof t==`number`?t:null,logo:typeof e?.logoUrl==`string`&&/^https?:\/\//.test(e.logoUrl)?e.logoUrl:``}}function Fe(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function D(e,t={}){if(!e)return``;let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t.now??new Date,i=t.timeZone?{timeZone:t.timeZone}:{},a=n.toLocaleDateString(t.locale,i)===r.toLocaleDateString(t.locale,i);return n.toLocaleString(t.locale,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function Ie(e,t={}){let n=e.data,r=E(n.away,n.awayScore),i=E(n.home,n.homeScore),a=Fe(e),o=typeof n.statusDetail==`string`?n.statusDetail.trim():``,s;if(a===`in`)s=o?`LIVE · ${o}`:`LIVE`;else if(a===`post`)s=`FINAL`;else{let n=D(e.published_at,t);s=n?`Kicks off ${n}`:o||`Upcoming`}let c=[],l=n.league,u=String(l?.abbreviation??l?.name??``);u&&c.push(u),typeof n.broadcast==`string`&&n.broadcast.trim()&&c.push(n.broadcast.trim());let d=a!==`pre`,f=e=>d&&e.score!==null?` ${e.score}`:``;return{away:r,home:i,state:a,status:s,chips:c,text:`${r.name}${f(r)} – ${i.name}${f(i)}`}}var Le=`nixamp.tv`,Re=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function ze(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?Be(r):/\bSilk\b/.test(e)&&n===0?!0:Re.test(e):Be(i)}function Be(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Ve(e){return e?12:100}function He(e,t,n){let r=Math.max(1,Math.ceil(e/n)),i=Math.min(Math.max(0,t),r-1),a=i*n;return{page:i,from:a,to:Math.min(e,a+n),pages:r}}var Ue=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,O=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,k=/\.m3u8(\?.*)?$/i,We=/\.(m3u|pls)(\?.*)?$/i;function Ge(e){try{let t=new URL(e);return O.test(t.pathname+t.search)}catch{return!1}}function Ke(e){try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}}),r=(n.pop()??``).replace(/\.(m3u|pls)$/i,``);return(/^(playlist|index|list|all|episodes|feed)?$/i.test(r)?n.pop()??``:r).replace(/[-_]+/g,` `).trim()||t.hostname}catch{return`Playlist`}}function qe(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||Ke(t),r=[],i=(e,n)=>{if(r.length>=1e3)return;let i;try{i=new URL(e.trim(),t)}catch{return}if(i.protocol!==`https:`&&i.protocol!==`http:`)return;let a=i.pathname+i.search;if(!Ue.test(a)&&!O.test(a))return;let o=decodeURIComponent(i.pathname.split(`/`).filter(Boolean).pop()??i.hostname);r.push({url:i.toString(),title:n||o})},a=!1;try{a=/\.pls$/i.test(new URL(t).pathname)}catch{a=!1}if(a){let t=new Map,a=new Map;for(let n of e.split(/\r?\n/)){let e=/^(File|Title)(\d+)\s*=\s*(.*)$/i.exec(n.trim());e&&(/^file$/i.test(e[1]??``)?t:a).set(e[2]??``,e[3]??``)}for(let[e,n]of[...t.entries()].sort((e,t)=>Number(e[0])-Number(t[0])))i(n,(a.get(e)??``).trim());return{title:n,entries:r}}let o=``;for(let t of e.split(/\r?\n/)){let e=t.trim();if(e!==``){if(e.startsWith(`#`)){let t=/^#EXTINF:\s*-?[\d.]+\s*(?:,(.*))?$/i.exec(e);t&&(o=(t[1]??``).trim());continue}i(e,o),o=``}}return{title:n,entries:r}}function Je(e){let t=e.hostname.replace(/^www\.|^m\.|^music\./,``),n=e=>e&&/^[A-Za-z0-9_-]{11}$/.test(e)?e:``;if(t===`youtu.be`)return n(e.pathname.slice(1).split(`/`)[0]??null);if(t!==`youtube.com`&&t!==`youtube-nocookie.com`)return``;if(e.pathname===`/watch`)return n(e.searchParams.get(`v`));let r=/^\/(?:shorts|live|embed|v)\/([^/?]+)/.exec(e.pathname);return r?n(r[1]??null):``}function Ye(e,t=!1){let n;try{n=new URL(e.trim())}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;let r=Je(n);if(r){let e=n.searchParams.get(`t`);return{kind:`embed`,site:`youtube`,src:`https://www.youtube-nocookie.com/embed/${r}?autoplay=1&playsinline=1&rel=0${e&&/^\d+$/.test(e)?`&start=${e}`:``}`,label:`YouTube · ${r}`}}let i=n.hostname.replace(/^www\.|^player\./,``),a=i===`vimeo.com`?/^\/(?:video\/)?(\d+)/.exec(n.pathname)?.[1]:void 0;if(a)return{kind:`embed`,site:`vimeo`,src:`https://player.vimeo.com/video/${a}?autoplay=1&playsinline=1`,label:`Vimeo · ${a}`};if(i===`soundcloud.com`&&n.pathname.split(`/`).filter(Boolean).length>=2)return{kind:`embed`,site:`soundcloud`,src:`https://w.soundcloud.com/player/?url=${encodeURIComponent(n.toString())}&auto_play=true&visual=false`,label:`SoundCloud · ${n.pathname.split(`/`).filter(Boolean).slice(0,2).join(` / `)}`};let o=n.pathname+n.search,s=decodeURIComponent(n.pathname.split(`/`).filter(Boolean).pop()??n.hostname);return We.test(o)?{kind:`list`,url:n.toString(),label:Ke(n.toString())}:Ue.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:O.test(o)||k.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var Xe=`nixamp.panels`;function Ze(){return{order:[],placement:{},collapsed:[],closed:[]}}var Qe=/^[a-z][a-z0-9-]{0,63}$/,$e=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function et(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&Qe.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function tt(e){if(!e)return Ze();let t;try{t=JSON.parse(e)}catch{return Ze()}if(!t||typeof t!=`object`||Array.isArray(t))return Ze();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))Qe.test(e)&&typeof t==`string`&&$e.test(t)&&(r[e]=t);return{order:et(n.order),placement:r,collapsed:et(n.collapsed),closed:et(n.closed)}}function nt(e){return JSON.stringify(e)}function rt(e,t){let n=new Set(e),r=t.filter(e=>n.has(e)),i=new Set(r);return e.forEach((t,n)=>{if(i.has(t))return;let a=0;for(let t=n-1;t>=0;t--){let n=r.indexOf(e[t]);if(n>=0){a=n+1;break}}r.splice(a,0,t),i.add(t)}),r}function it(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}var at=16e3,ot=3e4;function st(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function ct(e,t=at){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function lt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var ut=`nixamp.captions`,dt=`nixamp.captions.native-v2.language`,ft=[{code:``,label:`Original (auto-detect)`},{code:`en`,label:`English`},{code:`de`,label:`Deutsch`},{code:`sv`,label:`Svenska`},{code:`es`,label:`Español`},{code:`fr`,label:`Français`},{code:`it`,label:`Italiano`},{code:`nl`,label:`Nederlands`},{code:`da`,label:`Dansk`},{code:`fi`,label:`Suomi`},{code:`ru`,label:`Русский`},{code:`uk`,label:`Українська`},{code:`cs`,label:`Čeština`},{code:`hu`,label:`Magyar`},{code:`zh`,label:`中文`},{code:`ar`,label:`العربية`},{code:`hi`,label:`हिन्दी`},{code:`vi`,label:`Tiếng Việt`},{code:`id`,label:`Bahasa Indonesia`}];function pt(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return ft.some(e=>e.code===t)?t:``}catch{return``}}function mt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function ht(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function gt(e,t,n){let r=[],i=[];for(let a of e)(a.at<=t-n?r:i).push(a);return r.sort((e,t)=>e.at-t.at),{ready:r,still:i}}function _t(e,t,n,r=1500){let i=t-n;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.at<=i&&i<=n.until+r)return n;if(n.until+r<i)break}return null}function vt(e){try{return e(ut)!==`off`}catch{return!0}}function yt(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var bt=12e3,xt=class{options;context=null;gain=null;enabled=!1;generation=0;running=null;controller=null;next=[];sources=new Set;scheduledUntil=0;seen=new Set;constructor(e){this.options=e}async enable(){this.enabled=!0;try{this.context??=this.options.audioContext?.()??new AudioContext,this.gain||(this.gain=this.context.createGain(),this.gain.connect(this.context.destination)),await this.context.resume(),this.enabled&&this.options.status(`Waiting for the next translated line…`)}catch{this.fail(`Audio could not start. Enable translated audio again to retry.`)}}disable(){this.enabled=!1,this.reset()}reset(){this.generation++,this.controller?.abort(),this.controller=null,this.next=[],this.running=null,this.seen.clear();for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.scheduledUntil=0,this.options.active(!1)}setVolume(){this.gain&&(this.gain.gain.value=Math.max(0,Math.min(1,this.options.volume())))}push(e,t,n){this.pushBatch([{line:e,url:t,lag:n}])}pushBatch(e){if(!this.enabled||!this.options.playing())return;let t=e.slice(0,12).filter(({line:e,lag:t})=>{let n=`${e.channel}|${e.at}|${e.language}|${e.speaker??``}`;return this.seen.has(n)||this.stale(e,t)?!1:(this.seen.add(n),this.seen.size>200&&this.seen.delete(this.seen.values().next().value),!0)});t.length&&(this.next=t,this.running===null&&this.run(this.generation))}stale(e,t){return(this.options.now?.()??Date.now())-t-e.until>bt}fail(e){this.disable(),this.options.status(`${e} Original audio restored.`),this.options.failed()}async run(e){this.running=e;try{for(;this.next.length&&this.enabled&&e===this.generation;){let t=this.next.shift();if(this.stale(t.line,t.lag)||!this.options.playing())continue;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),12e3);try{let r=new Headers(t.init?.headers);if(new Headers(await this.options.authorization?.(n.signal,t.line)).forEach((e,t)=>r.set(t,e)),e!==this.generation)return;let i=await(this.options.fetcher??fetch)(t.url,{...t.init,signal:n.signal,headers:r});if(e!==this.generation){await i.body?.cancel();return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error||`Translated audio is unavailable.`)}if(!i.body||!i.headers.get(`content-type`)?.startsWith(`audio/pcm`))throw Error(`The server returned no voice audio.`);let a=i.body.getReader(),o=new Uint8Array,s=0;try{for(;;){let{done:t,value:n}=await a.read();if(e!==this.generation){await a.cancel();return}if(t)break;let r=new Uint8Array(o.length+n.length);r.set(o),r.set(n,o.length);let i=r.length-r.length%2;o=r.slice(i),i&&(this.schedule(r.subarray(0,i)),s+=i)}}finally{a.releaseLock()}if(!s||o.length)throw Error(`The voice audio was interrupted.`)}finally{clearTimeout(r)}for(;e===this.generation&&this.context&&this.scheduledUntil-this.context.currentTime>.15;)if(await new Promise(e=>setTimeout(e,50)),!this.options.playing()){this.reset();return}}}catch(t){e===this.generation&&this.fail(t instanceof Error?t.message:`Translated audio stopped.`)}finally{this.running===e&&(this.running=null)}}schedule(e){let t=this.context;if(!t||!this.gain||!this.enabled)return;if(t.state!==`running`)throw Error(`Audio playback was suspended.`);let n=e.length/2,r=Math.max(t.currentTime+.03,this.scheduledUntil);if(r-t.currentTime+n/16e3>10)throw Error(`Translated audio fell too far behind.`);let i=t.createBuffer(1,n,16e3),a=i.getChannelData(0),o=new DataView(e.buffer,e.byteOffset,e.length);for(let e=0;e<n;e++)a[e]=o.getInt16(e*2,!0)/32768;let s=t.createBufferSource();s.buffer=i,s.connect(this.gain),this.setVolume(),this.sources.add(s),s.onended=()=>{this.sources.delete(s),s.disconnect()},s.start(r),this.scheduledUntil=r+i.duration,this.options.active(!0),this.options.status(`Playing translated audio · a few seconds behind the video`)}},St=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,A=new WeakMap,Ct=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t){this.stop();let n=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(A.has(e)||A.set(e,e.audioWorklet.addModule(St).catch(t=>{throw A.delete(e),t})),await A.get(e),n!==this.generation)return;let r=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=r;let i=e.createGain();i.gain.value=0,t.connect(r),r.connect(i),i.connect(e.destination);let a=new Float32Array(e.sampleRate*5),o=0,s=new Float32Array,c=Date.now();r.port.onmessage=t=>{if(n!==this.generation)return;let r=0,i=t.data;for(;r<i.length;){let t=Math.min(a.length-o,i.length-r);if(a.set(i.subarray(r,r+t),o),o+=t,r+=t,o!==a.length)continue;let n=new Float32Array(8e4),l=e.sampleRate/16e3;for(let e=0;e<n.length;e++){let t=Math.floor(e*l),r=Math.max(t+1,Math.floor((e+1)*l)),i=0;for(let e=t;e<r;e++)i+=a[e]??0;n[e]=i/(r-t)}c+=5e3,Math.abs(Date.now()-c)>1500&&(c=Date.now(),s=new Float32Array);let u=new Float32Array(s.length+n.length);u.set(s),u.set(n,s.length),this.take({samples:u,at:c-u.length/16,until:c,freshAt:c-5e3}),s=u.slice(-16e4),o=0}},this.disconnect=()=>{r.port.onmessage=null,r.port.close(),t.disconnect(r),r.disconnect(),i.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},wt=class e{failed;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;static loaded=new WeakMap;constructor(e){this.failed=e}async start(t,n){this.stop();let r=this.generation;try{if(t.sampleRate!==48e3)throw Error(`Unsupported background sample rate`);let i=e.loaded.get(t);if(i||(i=t.audioWorklet.addModule(new URL(`data:text/javascript;base64,LyogQXVkaW8gdHJhbnNwb3J0IG9ubHk6IG5ldXJhbCBpbmZlcmVuY2UgcnVucyBpbiBhIGRlZGljYXRlZCB3b3JrZXIuIE5ldmVyCiAqIGJ5cGFzcyB0byB0aGUgb3JpZ2luYWwgaW5wdXQgb24gYW4gZXJyb3I6IHRoYXQgd291bGQgcmVzdG9yZSBmb3JlaWduIHNwZWVjaC4gKi8KY2xhc3MgQmFja2dyb3VuZFRyYW5zcG9ydCBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7CiAgY29uc3RydWN0b3IoKSB7CiAgICBzdXBlcigpOwogICAgdGhpcy5jaGFubmVsID0gbnVsbDsgdGhpcy5hbGl2ZSA9IHRydWU7IHRoaXMucmVhZHkgPSBmYWxzZTsKICAgIHRoaXMuaW5wdXRzID0gW25ldyBGbG9hdDMyQXJyYXkoNTEyKSwgbmV3IEZsb2F0MzJBcnJheSg1MTIpXTsKICAgIHRoaXMud3JpdHRlbiA9IDA7IHRoaXMuaWQgPSAwOyB0aGlzLmluZmxpZ2h0ID0gMDsKICAgIHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnJlYWQgPSAwOwogICAgdGhpcy5wb3J0Lm9ubWVzc2FnZSA9IGV2ZW50ID0+IHsKICAgICAgaWYgKGV2ZW50LmRhdGEuc3RvcCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMuY2hhbm5lbD8uY2xvc2UoKTsgcmV0dXJuOyB9CiAgICAgIHRoaXMuY2hhbm5lbCA9IGV2ZW50LmRhdGEucG9ydDsKICAgICAgdGhpcy5jaGFubmVsLm9ubWVzc2FnZSA9IHJlc3VsdCA9PiB7CiAgICAgICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm47CiAgICAgICAgdGhpcy5pbmZsaWdodC0tOwogICAgICAgIGlmICh0aGlzLnF1ZXVlLmxlbmd0aCA+PSA0KSB7IHRoaXMuZmFpbCgpOyByZXR1cm47IH0KICAgICAgICB0aGlzLnF1ZXVlLnB1c2gocmVzdWx0LmRhdGEuY2hhbm5lbHMpOwogICAgICAgIGlmICh0aGlzLnF1ZXVlLmxlbmd0aCA+PSAyKSB0aGlzLnJlYWR5ID0gdHJ1ZTsKICAgICAgfTsKICAgICAgdGhpcy5jaGFubmVsLnN0YXJ0KCk7CiAgICB9OwogIH0KICBmYWlsKCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyBlcnJvcjogdHJ1ZSB9KTsgfQogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzKSB7CiAgICBjb25zdCBvdXQgPSBvdXRwdXRzWzBdOwogICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm4gZmFsc2U7CiAgICBjb25zdCBpbnB1dCA9IGlucHV0c1swXTsKICAgIGlmICghaW5wdXQ/LlswXSB8fCAhdGhpcy5jaGFubmVsKSByZXR1cm4gdHJ1ZTsKICAgIGNvbnN0IGNvdW50ID0gaW5wdXRbMF0ubGVuZ3RoOwogICAgZm9yIChsZXQgY2hhbm5lbCA9IDA7IGNoYW5uZWwgPCAyOyBjaGFubmVsKyspIHRoaXMuaW5wdXRzW2NoYW5uZWxdLnNldChpbnB1dFtjaGFubmVsXSA/PyBpbnB1dFswXSwgdGhpcy53cml0dGVuKTsKICAgIHRoaXMud3JpdHRlbiArPSBjb3VudDsKICAgIGlmICh0aGlzLndyaXR0ZW4gPT09IDUxMikgewogICAgICBpZiAodGhpcy5pbmZsaWdodCA+PSA0KSB7IHRoaXMuZmFpbCgpOyByZXR1cm4gZmFsc2U7IH0KICAgICAgY29uc3QgY2hhbm5lbHMgPSB0aGlzLmlucHV0czsgdGhpcy5pbmZsaWdodCsrOwogICAgICB0aGlzLmNoYW5uZWwucG9zdE1lc3NhZ2UoeyBpZDogdGhpcy5pZCsrLCBjaGFubmVscyB9LCBjaGFubmVscy5tYXAob25lID0+IG9uZS5idWZmZXIpKTsKICAgICAgdGhpcy5pbnB1dHMgPSBbbmV3IEZsb2F0MzJBcnJheSg1MTIpLCBuZXcgRmxvYXQzMkFycmF5KDUxMildOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgaWYgKCF0aGlzLnJlYWR5KSByZXR1cm4gdHJ1ZTsKICAgIGlmICghdGhpcy5vdXRwdXQgfHwgdGhpcy5yZWFkID09PSA1MTIpIHsgdGhpcy5vdXRwdXQgPSB0aGlzLnF1ZXVlLnNoaWZ0KCkgPz8gbnVsbDsgdGhpcy5yZWFkID0gMDsgfQogICAgaWYgKCF0aGlzLm91dHB1dCkgeyB0aGlzLnJlYWR5ID0gZmFsc2U7IHJldHVybiB0cnVlOyB9CiAgICBmb3IgKGxldCBjaGFubmVsID0gMDsgY2hhbm5lbCA8IG91dC5sZW5ndGg7IGNoYW5uZWwrKykgb3V0W2NoYW5uZWxdLnNldCh0aGlzLm91dHB1dFtjaGFubmVsXS5zdWJhcnJheSh0aGlzLnJlYWQsIHRoaXMucmVhZCArIGNvdW50KSk7CiAgICB0aGlzLnJlYWQgKz0gY291bnQ7CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1iYWNrZ3JvdW5kIiwgQmFja2dyb3VuZFRyYW5zcG9ydCk7Cg==`,``+import.meta.url)),e.loaded.set(t,i),i.catch(()=>e.loaded.delete(t))),await i,r!==this.generation)return!1;let a=new Worker(new URL(`/assets/background.worker-D9ejvk_o.js`,``+import.meta.url),{type:`module`});this.worker=a;let o=new MessageChannel;if(this.pendingPort=o.port1,await new Promise((e,t)=>{let n=!1,r=r=>{n||(n=!0,clearTimeout(i),this.cancelStart=null,r?t(r):e())},i=setTimeout(()=>r(Error(`Background model did not load`)),8e3);this.cancelStart=()=>r(Error(`Background loading cancelled`)),a.onerror=()=>r(Error(`Background worker failed`)),a.onmessage=e=>r(e.data.ready?void 0:Error(`Background model unavailable`)),a.postMessage({port:o.port2},[o.port2])}),r!==this.generation)return!1;let s=()=>{r===this.generation&&(this.stop(),this.failed())};a.onerror=s,a.onmessage=e=>{e.data.error&&s()};let c=new AudioWorkletNode(t,`nixamp-background`,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});this.node=c,c.onprocessorerror=s,c.port.onmessage=e=>{e.data.error&&s()},c.port.postMessage({port:o.port1},[o.port1]),this.pendingPort=null;let l=t.createGain();return this.gain=l,l.gain.value=+!!this.on,this.input=n,c.connect(l),l.connect(t.destination),n.connect(c),!0}catch{r===this.generation&&(this.stop(),this.failed())}return!1}active(e){this.on=e,this.gain&&(this.gain.gain.value=+!!e)}stop(){if(this.generation++,this.on=!1,this.cancelStart?.(),this.cancelStart=null,this.pendingPort?.close(),this.pendingPort=null,this.node){this.node.port.postMessage({stop:!0});try{this.input?.disconnect(this.node)}catch{}this.node.disconnect(),this.node.port.close()}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},Tt=class{random;previous=[];sequence=0;speakers=new Map;constructor(e=Math.random){this.random=e}reset(){this.previous=[],this.sequence=0,this.speakers.clear()}reconcile(e,t,n){let r=new Map,i=new Set,a=[],o=new Map;for(let n of e)for(let e of this.previous){let r=Math.min(t+n.end*1e3,e.end)-Math.max(t+n.start*1e3,e.start);if(r>120){let t=`${n.speaker}|${e.speaker}`;o.set(t,(o.get(t)??0)+r)}}for(let[e,t]of o){let[n,r]=e.split(`|`);a.push({local:n,global:r,overlap:t})}for(let e of a.sort((e,t)=>t.overlap-e.overlap)){let t=this.speakers.get(e.global);t&&!r.has(e.local)&&!i.has(e.global)&&(r.set(e.local,t),i.add(e.global))}for(let t of e){let e=r.get(t.speaker);if(!e){let i=new Set([...this.speakers.values()].map(e=>e.voice)),a=n.filter(e=>!i.has(e.id)),o=a.length?a:n,s=o[Math.floor(this.random()*o.length)];e={id:`speaker-${++this.sequence}`,profile:t.profile,voice:s?.id??`auto`},this.speakers.set(e.id,e),r.set(t.speaker,e)}}this.previous=e.map(e=>({start:t+e.start*1e3,end:t+e.end*1e3,speaker:r.get(e.speaker).id}));let s=new Set(this.previous.map(e=>e.speaker));for(let e of this.speakers.keys())this.speakers.size>64&&!s.has(e)&&this.speakers.delete(e);return r}},Et=class{options;tracker=new Tt;generation=0;pending=null;running=null;controller=null;constructor(e){this.options=e}reset(){this.generation++,this.controller?.abort(),this.pending=null,this.running=null,this.tracker.reset()}push(e){this.pending=e,this.running===null&&this.run(this.generation)}async json(e,t,n){let r=await(this.options.fetcher??fetch)(e,{...t,signal:n}),i=await r.json();if(!r.ok)throw Error(i.error||`Audio translation is unavailable.`);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;if(this.pending=null,Date.now()-t.until>12e3)continue;let n=new AbortController;this.controller=n;let r=AbortSignal.any([n.signal,AbortSignal.timeout(12e3)]),i=this.options.speakers(),a=this.options.language(),o=await this.json(i?`/api/v1/speech/speakers`:`/api/v1/speech/transcribe?live=1`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Uint8Array(ct(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices());for(let n of o.turns??[]){let r=n.words.filter(e=>t.at+(e.start+e.end)*500>=t.freshAt);if(!r.length)continue;let i=e.get(n.speaker);c.push({channel:this.options.channel(),at:t.at+r[0].start*1e3,until:t.at+r.at(-1).end*1e3,text:r.map(e=>e.text).join(` `).trim(),language:s,speaker:i.id,voiceProfile:n.profile})}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(c.length){if(a&&s!==a){if(!s)throw Error(`The audio language could not be detected. Waiting for clearer speech.`);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:c.map(e=>e.text),from:s,to:a})},r);c=c.map((t,n)=>({...t,original:t.text,sourceLanguage:s,language:a,text:e.texts[n]??``}))}if(e!==this.generation)return;if(Date.now()-t.until>12e3)throw Error(`Translation fell behind. Try again after the language model has warmed up.`);this.options.lines(c.filter(e=>e.text.trim()!==``&&e.text.length<=600)),this.options.status(a?`${s} → ${a} · live translation`:`Original audio language: ${s||`detecting…`}`)}}}catch(t){e===this.generation&&(this.reset(),this.options.failed(),this.options.status(t instanceof Error?t.message:`Live translation stopped.`))}finally{this.running===e&&(this.running=null)}}},Dt=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,Ot=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,kt=/\s+(?:vs\.?|v\.?|at|@)\s+/i,j=/^(?:the|a|an|live|tonight|recorded|filmed|concert|home|dinner|breakfast|lunch|midnight|night|one night|death|murder|meet me|panic|sunset|sunrise)\b/i;function M(e){let t=e.replace(Ot,``).replace(Ot,``).trim().split(kt);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!j.test(t)})}function At(e){let t=String(e??``).trim();return t===``?!1:M(t.replace(Dt,``))||M(t)}var jt=`nixamp.remote`,Mt=`nixamp.defaultServer`,Nt=`nixamp.volume`,Pt=`nixamp.listenHere`,Ft=1e4,It=!1;function N(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function Lt(){let n=null;try{n=localStorage.getItem(Le)}catch{}let r=ze(navigator.userAgent,location.search,navigator.maxTouchPoints,n);if(document.body.classList.toggle(`tv`,r),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Le,r?`1`:`0`)}catch{}let i=document.getElementById(`tv-toggle`);i&&(i.textContent=r?`TV mode: on`:`TV mode`,i.title=r?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,i.addEventListener(`click`,()=>{try{localStorage.setItem(Le,r?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let a=Ve(r),o={status:N(`status`),source:N(`source`),install:N(`install`),video:N(`video`),audio:N(`audio`),title:N(`title-line`),album:N(`album-line`),meta:N(`meta-line`),metaBlurb:N(`meta-blurb`),liveLine:N(`live-line`),downloadNow:N(`download-now`),wayInHere:N(`way-in-here`),embed:N(`embed`),embedFrame:N(`embed-frame`),linkForm:N(`link-form`),linkUrl:N(`link-url`),linkServer:N(`link-server`),linkGoLive:N(`link-go-live`),goLiveNow:N(`go-live-now`),elapsed:N(`elapsed`),total:N(`total`),seek:N(`seek`),fullscreen:N(`fullscreen`),copyNow:N(`copy-now`),canvas:N(`spectrum`),glyphs:N(`glyphs`),levels:N(`levels`),playlist:N(`playlist`),playlistPager:N(`playlist-pager`),crumbs:N(`crumbs`),filter:N(`filter`),playlistTitle:N(`playlist-panel`),note:N(`note`),linkNote:N(`link-note`),logList:N(`log-list`),files:N(`files`),folder:N(`folder`),remoteUrl:N(`remote-url`),remoteForm:N(`remote-form`),remoteState:N(`remote-state`),disconnect:N(`disconnect`),browse:N(`browse`),panelsToggle:N(`panels-toggle`),panelsPanel:N(`panels-panel`),panelsList:N(`panels-list`),panelsReset:N(`panels-reset`),accountForm:N(`account-form`),accountEmail:N(`account-email`),accountPassword:N(`account-password`),accountSubmit:N(`account-submit`),accountToggle:N(`account-toggle`),accountProviders:N(`account-providers`),accountPanel:N(`account-panel`),accountElsewhere:N(`account-elsewhere`),welcome:N(`welcome`),welcomeCreate:N(`welcome-create`),welcomeBrowse:N(`welcome-browse`),welcomeHide:N(`welcome-hide`),accountSignOut:N(`account-signout`),accountNote:N(`account-note`),personaForm:N(`persona-form`),personaHandle:N(`persona-handle`),personaVoice:N(`persona-voice`),personaProfile:N(`persona-profile`),personaNote:N(`persona-note`),adminPanel:N(`admin-panel`),adminNote:N(`admin-note`),adminSaid:N(`admin-said`),adminConnections:N(`admin-connections`),publishPanel:N(`publish-panel`),publishNote:N(`publish-note`),publishList:N(`publish-list`),adminRestream:N(`admin-restream`),adminReplace:N(`admin-replace`),adminSource:N(`admin-source`),adminName:N(`admin-name`),adminAdd:N(`admin-add`),homeNote:N(`home-note`),loadHome:N(`load-home`),directory:N(`directory`),recentNote:N(`recent-note`),recentList:N(`recent-list`),followingNote:N(`following-note`),followingList:N(`following-list`),serversPanel:N(`servers-panel`),serversNote:N(`servers-note`),serversList:N(`servers-list`),favoritesPanel:N(`favorites-panel`),favoritesNote:N(`favorites-note`),favoritesList:N(`favorites-list`),favHere:N(`fav-here`),partiesPanel:N(`parties-panel`),partiesNote:N(`parties-note`),partiesList:N(`parties-list`),partyForm:N(`party-form`),partyCode:N(`party-code`),partyJoin:N(`party-join`),connectionsNote:N(`connections-note`),connectionsList:N(`connections-list`),catalogsPanel:N(`catalogs-panel`),catalogsNote:N(`catalogs-note`),catalogsForm:N(`catalogs-form`),catalogSource:N(`catalog-source`),catalogName:N(`catalog-name`),catalogsList:N(`catalogs-list`),catalogsCrumbs:N(`catalogs-crumbs`),catalogsFilter:N(`catalogs-filter`),catalogsEntries:N(`catalogs-entries`),notifyPanel:N(`notify-panel`),notifyNote:N(`notify-note`),notifyWeb:N(`notify-web`),notifyEmail:N(`notify-email`),notifySms:N(`notify-sms`),notifyPhone:N(`notify-phone`),notifyPhoneForm:N(`notify-phone-form`),notifyPhoneNote:N(`notify-phone-note`),directoryNote:N(`directory-note`),directoryList:N(`directory-list`),onairPanel:N(`onair-panel`),onairNote:N(`onair-note`),onairList:N(`onair-list`),sharePanel:N(`share-panel`),trollboxPanel:N(`trollbox-panel`),trollboxNote:N(`trollbox-note`),trollboxList:N(`trollbox-list`),trollboxForm:N(`trollbox-form`),trollboxInput:N(`trollbox-input`),trollboxMic:N(`trollbox-mic`),trollboxEdit:N(`trollbox-edit`),trollboxEditLabel:N(`trollbox-edit-label`),transcriptPanel:N(`transcript-panel`),transcriptNote:N(`transcript-note`),transcriptOn:N(`transcript-on`),transcriptLanguage:N(`transcript-language`),transcriptAudio:N(`transcript-audio`),transcriptVoiceSettings:N(`transcript-voice-settings`),transcriptBackground:N(`transcript-background`),transcriptAudioNote:N(`transcript-audio-note`),transcriptSpeakers:N(`transcript-speakers`),transcriptList:N(`transcript-list`),subtitle:N(`subtitle`),shareNote:N(`share-note`),shareLink:N(`share-link`),shareCopy:N(`share-copy`),sharePhone:N(`share-phone`),shareSend:N(`share-send`),liveControls:N(`live-controls`),goLive:N(`go-live`),stopLive:N(`stop-live`),shareTo:N(`share-to`),listenOnly:N(`listen-only`),listenHere:N(`listen-here`),volume:N(`volume`),prev:N(`prev`),playPause:N(`play-pause`),transport:N(`transport`),stop:N(`stop`),next:N(`next`),shareNow:N(`share-now`)},l={party:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 21 4-12 8 8Z"/><path d="m7 9 8 8M12 7l1-3M16 10l4-1M16 5l2-2M20 14l1 1M8 4l-1-1"/><circle cx="21" cy="4" r=".5" fill="currentColor"/></svg>`,rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`},d=(e,t)=>{e.innerHTML=l[t]},f=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,p=`local`,m=``,h=[],g=``,ee=!0,_=``;function te(e){try{return new URL(e).origin}catch{return e}}let ne=!1,v=``,re=0,ie=new Map,ae=e=>ie.get(H(e))??null;function oe(e,t){let n=n=>{ne=n,v=``,o.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),o.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,d(r,`eye`),r.title=`Viewer: browse and watch. Changes nothing on the server.`,r.setAttribute(`aria-label`,`View ${e.name}`),r.addEventListener(`click`,()=>n(!0));let i=document.createElement(`button`);return i.type=`button`,i.className=`icon way-in`,d(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:G?`Admin: you do not administer this server.`:`Admin: sign in as this server's owner to administer it.`,i.setAttribute(`aria-label`,`Administer ${e.name}`),i.addEventListener(`click`,()=>n(!1)),[r,i]}let se=``,y=[],le=0,b=pe(),x=`idle`,de=``,S=`Pick files, or connect to a nixamp running somewhere else.`,he=!1,C=-1,w=null;function ye(e){return e?/^https?:\/\//i.test(e)?e:I.url(e):``}let be=0,xe=0,Ce=!1,ke=()=>!F.needsInteraction&&(xe>0||Ce);async function T(e){xe+=1,z();try{return await e()}finally{--xe,z()}}let E=null,D=null,Re=``,Be=null,Ue=``,O=null,k=null,We=0;function Ke(){o.embed.hidden||(o.embedFrame.src=`about:blank`),o.embed.hidden=!0}let Je=null,Qe=``,$e=null;function et(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Qe=i,$e&&clearTimeout($e),$e=null,!r){if(Je?.key===i)return;Je=null}if(p!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(I.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Qe!==i)return;Je={key:i,match:r.match??null},z();let a=Je.match;a?.kind===`fixture`&&Fe(a)!==`post`&&($e=setTimeout(()=>{$e=null,!(Qe!==i||F.source===``&&!w)&&et(e,t,n,!0)},6e4))}).catch(()=>void 0)}let bt=!1,St=``,A=``,Tt=null,Dt=``,Ot=``,kt=``,j=Array(24).fill(0),M=Array(24).fill(0),Lt=[],P=()=>p===`remote`&&!o.listenHere.checked,Rt=()=>p===`remote`&&!o.adminPanel.hidden,zt=!1,Bt=()=>Rt()||p===`remote`&&zt;function Vt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:o.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function Ht(){if(p!==`remote`||O)return null;if(E?.catalog&&E.entry)return{kind:`entry`,catalog:E.catalog,entry:E.entry};if(w)return{kind:`channel`,id:w.id,name:w.name};let e=b.tracks[L()];return e&&(F.source!==``||P())?{kind:`track`,index:L(),name:t(e)}:null}async function Ut(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;S=`Putting ${n} on the air…`,z();try{let r=``,i=``,a=!0;{let t=e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(I.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){S=s.error??`${n} would not go on the air.`,z();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(Rt()&&(bt?await fetch(I.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await La(!0)),await ga(),$(),i!==``&&w?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await wa({id:i,name:n,video:a},!0,t)}let o=ja(r),s=St?` Call ${A||`the line`} and key ${St} to talk about it.`:``;o===``?S=`${n} is on the air and you are watching it.${s}`:(await Aa(o,t,`✓`),S=`${n} is on the air and you are watching it. Link copied.${s}`),z()}catch{S=`could not reach the server`,z()}finally{t.disabled=!1}}function Wt(e,t=`Join party`){d(e,t===`Join party`?`party`:`live`),e.append(document.createTextNode(` ${t}`)),e.title=t===`Join party`?`Join live`:t}Wt(o.partyJoin);function Gt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,d(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),Ut(e(),n)}),n}let F=new fe({audio:o.audio,video:o.video},{readable:e=>I.owns(e),onTime:(e,t)=>{let n=y[le];p===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),z()},onEnded:()=>{Ta()||On()||p===`remote`&&C<0&&!P()||an(1)},onState:()=>z(),onBusy:e=>{Ce!==e&&(Ce=e,z())},onError:e=>{if(!Ta()&&!(We!==0&&Date.now()-We<2e3)){if(k&&e===`this browser cannot play that format`){let e=k.url;if(k=null,We=Date.now(),Bt()){S=`That site will not let a page play it directly; going live with it on ${m||`the server`} instead.`,z(),o.linkUrl.value=e,Mn();return}S=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,z();return}S=e,z(),xa()}}}),I=new Se({onSnapshot:e=>{let t=e.tracks!==void 0||b.index!==e.index;if(b=me(b,e),v.startsWith(`track:`)&&b.tracks.length>0){let e=Number(v.slice(6));if(v=``,Number.isInteger(e)&&e>=0&&e<b.tracks.length){let t=re;nn(e).then(()=>{t>0&&(F.seek(t),setTimeout(()=>F.seek(t),600))})}}P()&&(j=e.bars.length>0?e.bars:j,M=Ne(M,j)),z(),t&&D&&ba(D)},onStatus:(e,t)=>{x=e,de=t??``,z()}}),Kt=()=>p===`remote`?b.tracks.length:y.length,L=()=>p===`remote`?P()||C<0?b.index:Math.min(C,Math.max(0,b.tracks.length-1)):le,qt=()=>{let e=D?.server.nowPlaying||`Live`;return(!Be||Be.tracks!==b.tracks||Be.index!==b.index||Be.fallback!==e)&&(Be={tracks:b.tracks,index:b.index,fallback:e,value:u(b.tracks,b.index,e)}),Be.value},Jt=()=>p===`remote`&&!w&&E?.kind===`live`,Yt=()=>Jt()?qt().fullTitle:R(),R=()=>{if(w)return w.name;if(O)return O.label;if(Jt())return qt().title;let e=p===`remote`?b.tracks[L()]:y[L()];return e?t(e):`Nothing loaded.`},Xt=()=>{if(w)return`live on this server`;if(O)return`playing here, in this browser`;if(Jt()){let{context:e,position:t}=qt();return[e,t,`live on ${m||`this server`}`].filter(Boolean).join(` · `)}return(p===`remote`?b.tracks[L()]:y[L()])?.album||`—`};function Zt(){if(p!==`remote`||w===null&&E?.kind!==`live`){o.liveLine.hidden=!0,o.liveLine.replaceChildren(),delete o.liveLine.dataset.drawn;return}let e=m||`this server`,t=w?w.name:qt().fullTitle,n=[w?`Live on ${e}: `:`Live from ${e}, now playing: `,Ra(t)],r=w?D?.channels.find(e=>e.id===w?.id)?.code??``:bt?St:``;r&&n.push(`. To talk about it, call `,Ra(A||`the line`),` and key `,Ra(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);o.liveLine.dataset.drawn!==i&&(o.liveLine.dataset.drawn=i,o.liveLine.hidden=!1,o.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let Qt=()=>P()?b.tracks[L()]?.duration??0:F.duration,$t=()=>P()?b.position:F.position,en=()=>P()?b.playing:F.playing;async function tn(e){if(p===`remote`){if(P()){await I.send({type:`play`,index:e});return}await nn(e);return}let t=y[e];t&&(le=e,w=null,E={kind:`file`},await T(()=>F.load(t,!0)),Cn(t.video),wn(),z())}async function nn(e){let t=b.tracks[e];t&&(C=e,w=null,E={kind:`file`},et(t.title,`auto`),await T(()=>F.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:I.media(e,0),video:t.video===!0,objectUrl:!1},!0)),Cn(t.video===!0),wn())}async function rn(){if(F.needsInteraction){await F.play(),z();return}if(P()){await I.send({type:`toggle`});return}Kt()!==0&&(F.playing?F.pause():F.position>0?await F.play():await tn(L()),z())}async function an(e){let t=Kt();if(t!==0){if(P()){await I.send({type:e>0?`next`:`prev`});return}await tn((L()+e+t)%t)}}async function on(){if(Ke(),O=null,k=null,P()){await I.send({type:`stop`});return}w=null,E=null,F.stop(),j=Array(24).fill(0),M=[...j],z()}let sn=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,cn=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],ln=``;function un(){let t=[],n=``,r=null,i=w?D?.channels.find(e=>e.id===w?.id):void 0;w&&i?.ended&&Ue!==w.id&&(Ue=w.id,or(`${w.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let a=F.source===``&&!w&&!(P()&&b.tracks[L()]);if(!a){w&&i?.ended?t.push(`ENDED`):w?t.push(E?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):E?.kind===`vod`?t.push(`ON DEMAND`):E?.kind===`live`?t.push(`LIVE`):p===`remote`&&P()?t.push(`ON THE SERVER`):t.push(`FILE`),!o.video.hidden&&o.video.videoWidth>0?t.push(`${o.video.videoWidth}×${o.video.videoHeight}`):o.video.hidden?t.push(`audio`):t.push(`video`),i?(t.push(i.via===`pull`?`${i.listeners} watching`:`${i.listeners} listening · over ${i.via}`),i.startedAt>0&&t.push(`on air ${e(Math.max(0,(Date.now()-i.startedAt)/1e3))}`),i.redials&&t.push(`redialled ${i.redials}×`),Rt()&&i.error&&t.push(i.error)):p===`remote`&&!w?(b.tracks[L()]&&Kt()>0&&t.push(`${Jt()?`library track`:`track`} ${L()+1} of ${Kt()}`),P()&&D&&t.push(`${D.server.playing?`playing`:`stopped`} on ${m||`the server`}`)):p===`local`&&Kt()>0&&t.push(`track ${L()+1} of ${Kt()}`),E?.catalog!==void 0&&(E.kind===`channel`?w!==null:E.kind===`vod`&&F.source!==``)&&E?.catalog&&(t.push(E.entry?.group?`${E.catalog.name} › ${E.entry.group}`:E.catalog.name),n=E.entry?.logo??``),n===``&&w&&(n=ye(i?.art??w.art));let a=Je?.key===Qe?Je.match:null;if(a?.kind===`fixture`)r=Ie(a),t.unshift(r.status,...r.chips);else if(a){a.image&&(n=a.image);let e=a.data;if(a.kind===`title`){a.year&&t.push(String(a.year));let n=typeof e.rating==`number`?e.rating:null;n&&t.push(`★ ${n.toFixed(1)}`);let r=Array.isArray(e.genres)?e.genres.slice(0,2).map(String):[];r.length&&t.push(r.join(` · `));let i=typeof e.runtimeMin==`number`?e.runtimeMin:0;i&&t.push(`${i} min`)}else if(a.kind===`channel`){let n=typeof e.country==`string`?e.country:``,r=Array.isArray(e.categories)?e.categories.slice(0,2).map(String):[],i=typeof e.network==`string`?e.network:``;n&&t.push(n),r.length&&t.push(r.join(` · `)),i&&t.push(i)}}if(w&&E?.link){let e=``;try{e=new URL(E.link.url).hostname.replace(/^www\./,``)}catch{}t.push(E.link.extractor&&E.link.extractor!==`direct`&&E.link.extractor!==`generic`?`${E.link.extractor} · ${e}`:e||`link`)}bt&&St&&P()&&!w&&E?.kind!==`live`&&t.push(A?`☎ ${A} · key ${St}`:`☎ code ${St}`)}let s=Je?.key===Qe?Je.match:null,c=!a&&!r&&s?.summary?s.summary:``,l=`${n}|${r?`${r.away.logo}|${r.home.logo}|${r.text}`:``}|${t.join(`|`)}|${c}`;if(l===ln)return;ln=l,o.meta.hidden=t.length===0,o.metaBlurb.textContent=c,o.metaBlurb.hidden=c===``;let u=[];if(r){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let n=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,n.push(i),r?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),n.push(t)}if(e.logo!==``){let r=document.createElement(`img`);r.className=`meta-team-logo`,r.alt=``,r.src=e.logo,r.addEventListener(`error`,()=>{r.hidden=!0}),t?n.unshift(r):n.push(r)}return n},n=document.createElement(`span`);n.className=`meta-dash`,n.textContent=`–`,e.replaceChildren(...t(r.away,!0),n,...t(r.home,!1)),u.push(e)}if(n!==``&&/^(https?:\/\/|\/api\/)/.test(n)){let e=document.createElement(`img`);e.className=s?.kind===`title`&&n===s.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=n,e.addEventListener(`error`,()=>{e.hidden=!0}),u.push(e)}for(let e of t){let t=document.createElement(`span`);t.className=r?.state===`in`&&e===r.status?`meta-chip chip-live`:`meta-chip`,t.textContent=e,u.push(t)}o.meta.replaceChildren(...u)}function z(){let t=Kt(),n=en(),r=ke();o.status.textContent=r?`LOADING`:n?`▶ PLAYING`:`■ STOPPED`,o.status.dataset.playing=r?`loading`:String(n),o.title.textContent=R(),o.title.classList.toggle(`with-context`,Jt()),o.album.classList.toggle(`with-context`,Jt()),(Jt()||w)&&wn(),Zt(),un(),o.goLiveNow.hidden=!Bt()||Ht()===null;let i=n?`${Yt()} · ${f}`:f;document.title!==i&&(document.title=i),o.copyNow.hidden=F.source===``,o.shareNow.hidden=ci()===``,Hr(),ei(),o.downloadNow.hidden=!(w&&E?.link?.download),An(),o.album.textContent=Xt();let a=$t(),s=Qt();o.elapsed.textContent=e(a),o.total.textContent=s>0?e(s):`--:--`,he||(o.seek.value=String(s>0?Math.round(a/s*1e3):0),o.seek.disabled=s<=0||P()),o.playPause.textContent=n?`❚❚`:`▶`,o.playPause.setAttribute(`aria-label`,n?`Pause`:`Play`),o.seek.setAttribute(`aria-valuetext`,`${e(F.position)} of ${e(F.duration)}`),o.volume.setAttribute(`aria-valuetext`,`${o.volume.value} percent`),o.playlistTitle.dataset.title=p===`remote`?`Files on ${m||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,o.source.textContent=p===`remote`?`connected · ${m||I.address.replace(/^https?:\/\//,``)||`—`}`:y.length>0?`local · ${y.length} files`:`no source`,Sn(),o.remoteState.textContent=p===`remote`?`${x}${de?` — ${de}`:``}`:`not connected`,o.remoteState.dataset.status=p===`remote`?x:`idle`,o.disconnect.hidden=p!==`remote`;let c=F.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:p===`remote`&&b.note!==``?b.note:S;o.note.textContent=c,o.note.hidden=c===``,o.linkNote.textContent=c,o.linkNote.hidden=c===``,or(c),_n(),o.glyphs.textContent=j.map(cn).join(``);let[l,u]=P()?b.levels:F.levels();o.levels.textContent=sn(l,u)}let dn=``,B=``,fn=0;function pn(e){B=e,fn=0,dn=``,_n()}function mn(e,t,n,r,i){if(o.playlistPager.hidden=n<=1,n<=1){o.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{fn=t,dn=``,_n()}),i},s=document.createElement(`span`);s.className=`pager-where`,s.textContent=`${r+1}–${i} of ${e.toLocaleString()}`,o.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),s,a(`Next ›`,t+1,`The page after this one`))}function hn(e){if(o.crumbs.hidden=!e,!e)return;let t=B===``?[]:B.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>pn(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),o.crumbs.replaceChildren(...r)}function gn(e,t){let n=document.createElement(`li`);n.className=`folder`;let r=document.createElement(`span`);r.className=`name`,r.textContent=`${e}/`;let i=document.createElement(`span`);i.className=`count`,i.textContent=`${t} file${t===1?``:`s`}`,n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),a.append(r,i),n.replaceChildren(a),a.addEventListener(`click`,t=>{t.stopPropagation(),pn(B===``?e:`${B}/${e}`)}),n}function _n(){let n=p===`remote`?b.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):y.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=o.filter.value.trim().toLowerCase(),i=n.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>r===``||`${e.folder}/${e.name}`.toLowerCase().includes(r)),c=e=>r!==``||B===``||e===B||e.startsWith(`${B}/`),l=e=>r!==``||e===B,u=e=>{let t=B===``?e:e.slice(B.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of i){if(!c(e.folder)||l(e.folder))continue;let t=u(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let m=i.filter(e=>l(e.folder)&&c(e.folder)),h=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),g=He(h.length+m.length,fn,a);fn=g.page;let ee=h.slice(g.from,g.to),_=m.slice(Math.max(0,g.from-h.length),Math.max(0,g.to-h.length)),te=`${p}:${B}:${r}:${g.page}/${a}:${h.join(`,`)}:${m.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(te!==dn){dn=te,hn(r===``&&(h.length>0||B!==``)),mn(h.length+m.length,g.page,g.pages,g.from,g.to);let t=[];for(let[e,n]of ee)t.push(gn(e,n));let n=``,i=m.some(e=>e.group!==``);for(let r of _){r.group!==n&&(i||r.group!==``)&&(n=r.group,t.push(vn(r.group)));let a=document.createElement(`li`);a.className=`row`,a.dataset.index=String(r.index);let o=document.createElement(`span`);o.className=`n`,o.textContent=String(r.index+1).padStart(2,` `);let s=document.createElement(`span`);s.className=`name`,s.textContent=r.name;let c=document.createElement(`span`);c.className=`time`,c.textContent=r.seconds>0?e(r.seconds):`--:--`;let l=document.createElement(`button`);if(l.type=`button`,l.className=`row-main`,l.setAttribute(`aria-label`,`Play ${r.name}${r.seconds>0?`, ${e(r.seconds)}`:``}`),l.append(o,s,c),a.append(l),p===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,d(e,`copy`),e.title=`Copy a link that plays this here, from where it is`,e.setAttribute(`aria-label`,`Copy a link that plays ${r.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),Aa(ja(`track:${r.index}`,C===r.index?F.position:0),e,`✓`)}),a.append(e),Bt()&&a.append(Gt(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}t.push(a)}s(o.playlist,...t)}let ne=L(),v=en();for(let e of Array.from(o.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===ne;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&v),r?t.setAttribute(`aria-current`,`true`):t.removeAttribute(`aria-current`)}}function vn(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!o.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,t=>{t.stopPropagation(),yn(e)}),t.append(n)}return t}async function yn(e){try{let t=await fetch(I.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();V(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{V(`could not reach the server`)}}function bn(){let t=o.canvas,n=Math.min(2,globalThis.devicePixelRatio||1),r=Math.round(t.clientWidth*n),i=Math.round(t.clientHeight*n);r>0&&i>0&&(t.width!==r||t.height!==i)&&(t.width=r,t.height=i);let a=t.getContext(`2d`);if(P())M=Ne(M,j);else{let e=F.read();e.length>0&&(Lt.length!==25&&(Lt=Ae(24,e.length)),j=Me(j,je(e,Lt)),M=Ne(M,j))}if(a){let e=getComputedStyle(document.documentElement);Pe(a,{width:t.width,height:t.height},j,M,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(en()){o.glyphs.textContent=j.map(cn).join(``);let[t,n]=P()?b.levels:F.levels();o.levels.textContent=sn(t,n),o.elapsed.textContent=e($t());let r=Qt();!he&&r>0&&(o.seek.value=String(Math.round($t()/r*1e3)))}requestAnimationFrame(bn)}let xn=``;function Sn(){if(p!==`remote`){o.wayInHere.hidden=!0,xn=``;return}let e=Rt()&&!ne,t=se||I.address,n=e?null:ae(I.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===xn)return;xn=r;let[i,a]=oe({name:m||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,o.wayInHere.replaceChildren(i,a),o.wayInHere.hidden=!1}function Cn(e){o.video.hidden=!e,o.fullscreen.hidden=!e,Ke(),O=null,k=null}function wn(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=w?ye(D?.channels.find(e=>e.id===w?.id)?.art??w.art):``,t=JSON.stringify([R(),Xt(),e]);t!==Re&&(Re=t,navigator.mediaSession.metadata=new MediaMetadata({title:R(),album:Xt(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void rn()),navigator.mediaSession.setActionHandler(`pause`,()=>void rn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void an(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void an(-1)))}o.filter.addEventListener(`input`,()=>{fn=0,dn=``,_n()}),o.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),o.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&tn(n)}),o.fullscreen.addEventListener(`click`,()=>{let e=o.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),o.prev.addEventListener(`click`,()=>void an(-1)),o.next.addEventListener(`click`,()=>void an(1)),o.stop.addEventListener(`click`,()=>void on()),o.playPause.addEventListener(`click`,()=>void rn());async function Tn(e){let t=Ye(e,Vt());if(!t){if(!Bt()){S=p===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,z();return}await kn(e);return}if(w=null,F.stop(),t.kind===`embed`){E={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},Cn(!1),o.embedFrame.src=t.src,o.embed.hidden=!1,O={url:e,label:t.label,kind:`embed`},S=`Playing ${t.label} here, in this browser.`,z();return}if(t.kind===`list`){await En(e,t.label);return}E={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await T(()=>F.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),Cn(t.video),O={url:e,label:t.label,kind:`direct`},S=`Playing ${t.label} here, in this browser.`,z()}async function En(e,t){S=`Reading ${t}…`,z();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){S=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,z();return}let r=qe(n,e);if(r.entries.length===0){S=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,z();return}k={url:e,title:r.title||t,entries:r.entries,at:0},await Dn()}async function Dn(){let e=k,t=e?.entries[e.at];if(!e||!t)return;let n=Ge(t.url);E={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await T(()=>F.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),k!==null&&(Cn(n),O={url:e.url,label:e.title,kind:`direct`},k=e,S=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,z())}function On(){let e=k;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Dn(),!0)}async function kn(e){if(p!==`remote`){S=`Pick a server to go live on, or connect to one, to put a link on the air.`,z();return}S=`Asking ${m||`the server`} to fetch ${e}…`,z(),await T(async()=>{let t,n={};try{t=await fetch(I.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{S=`could not reach the server`;return}if(!t.ok||!n.channel){S=n.error??`that link would not play.`;return}try{await fetch(I.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await wa({id:n.channel,name:n.name||e,video:n.video!==!1,art:n.art},!0,{kind:`channel`,link:{url:e,extractor:n.extractor??``,download:n.download===!0,live:n.live===!0,video:n.video!==!1}}),(n.entries??0)>1&&(S=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),z()}o.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.linkUrl.value.trim();t!==``&&Tn(t)});function An(){let e=p===`remote`?I.address:``,t=h.filter(t=>te(t.url)!==te(e)),n=JSON.stringify({here:e,name:m,carries:ee,others:t});if(n===g||document.activeElement===o.linkServer)return;g=n;let r=[];if(e!==``&&ee){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${m||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}o.linkServer.replaceChildren(...r),o.linkServer.value=e!==``&&!ee&&t[0]?t[0].url:``,o.linkServer.hidden=t.length===0}async function jn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;h=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),An()}catch{}}async function Mn(){let e=o.linkUrl.value.trim()||O?.url||``;if(e===``){S=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,z();return}let t=o.linkServer.value;if(t!==``&&(p!==`remote`||te(t)!==te(I.address))){let n=h.find(e=>e.url===t)?.name??t;_=e,S=`Connecting to ${n} to go live with it…`,z(),Nn(t);return}if(p!==`remote`){S=h.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,z();return}if(!ee){S=`${m||`This server`} has no ffmpeg, so it cannot carry a link.`+(h.length>0?` Pick a server to go live on, beside the link.`:``),z();return}if(!Bt()){S=`Sign in to nixamp.com to go live here, or use the server's control link.`,z();return}await kn(e)}function Nn(e){let t=o.linkUrl.value.trim();ne=!0,v=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit(),o.linkUrl.value=t}o.linkGoLive.addEventListener(`click`,()=>{Mn()}),o.linkServer.addEventListener(`change`,()=>{let e=o.linkServer.value;e!==``&&Nn(e)}),o.downloadNow.addEventListener(`click`,()=>{let e=E?.link;if(!e||p!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(I.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),S=`Fetching it through the server; your browser will save it when it arrives.`,z()}),o.goLiveNow.addEventListener(`click`,()=>{let e=Ht();e&&Ut(e,o.goLiveNow)}),o.seek.addEventListener(`input`,()=>{he=!0}),o.seek.addEventListener(`change`,()=>{let e=Qt();e>0&&F.seek(Number(o.seek.value)/1e3*e),he=!1}),o.volume.addEventListener(`input`,()=>{let e=Number(o.volume.value)/100;F.volume=e;try{localStorage.setItem(Nt,String(e))}catch{}});let Pn=e=>{e.addEventListener(`change`,()=>{let t=ce(Array.from(e.files??[]));if(t.length===0){S=`Nothing playable in that selection.`,z();return}ue(y),y=t,le=0,p=`local`,I.close(),S=``,tn(0)})};Pn(o.files),Pn(o.folder),o.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.remoteUrl.value,{base:n,key:r}=ve(t);if(n===``){S=`That is not an address.`,z();return}(async()=>{x=`connecting`,z();let e=Oe(n);if(e){x=`error`,de=e,S=e,_=``,p=`local`,z();return}if(await De(n,void 0,r)===null){x=`error`;let e=Te(n);de=e?`needs the server's name`:`not answering`,S=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,_=``,p=`local`,z();return}let i=await Ee(n,r);if(i){x=`error`,de=i,S=i,_=``,p=`local`,z();return}p=`remote`,S=``;try{localStorage.setItem(jt,t.trim())}catch{}I.connect(t),$(),_i(),ya(!0),Kn(),ga(),z()})()});let Fn=``,In=null,Ln=async(e=!1)=>{o.directory.hidden=!1,e||(o.directoryNote.textContent=`Looking for live streams…`,s(o.directoryList)),In||=setInterval(()=>{!o.directory.hidden&&document.visibilityState===`visible`&&Ln(!0)},Ft);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],h=t.map(e=>({name:e.name,url:e.url})),An();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:G});if(e&&i===Fn)return;Fn=i,Yn(r.recent??[])}catch{e||(o.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(s(o.directoryList),t.length===0){o.directoryNote.textContent=`Nobody is streaming right now.`;return}o.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let a=[`${e.tracks.toLocaleString()} files to browse`];e.playing!==!1&&e.nowPlaying?a.push(`playing ${e.nowPlaying}`):a.push(`player idle`),e.code&&a.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=a.join(` · `),i.title=i.textContent,n.append(r,i);let s=e.admin??ae(e.url),c=(t,n=``)=>{ne=t,v=n,o.remoteUrl.value=t?e.url:s??e.url,o.directory.hidden=!0,o.remoteForm.requestSubmit()},l=document.createElement(`ul`);l.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let o=e.lineup?.find(e=>e.name===t);if(o?.art&&/^https?:\/\//i.test(o.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=o.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}o?.about&&(r.title=o.about);let s=document.createElement(`button`);s.type=`button`,s.className=`button`,Wt(s),s.title=`Join live: ${t} on ${e.name}`,s.addEventListener(`click`,()=>c(!0,`channel:${t}`)),n.append(r,s),l.append(n)}let[u,d]=oe({name:e.name,view:e.url,admin:s},()=>{o.directory.hidden=!0});if(t.append(n,u,d),G&&t.append(ir(e.url,e.name)),e.ownerId&&G&&e.ownerId!==G&&t.append(Ai(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&G&&e.ownerId===G){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));o.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{o.directoryNote.textContent=`could not reach the directory`}finally{await Ln()}})()}),t.append(n)}o.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!o.directory.hidden&&Ln(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),Ln()}let Rn=null,zn=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Bn=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,Vn=``,Hn=``,Un=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===Vn)return;Vn=t,o.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}o.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[zn(t.network),`network-${t.network}`],[Bn(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}o.adminConnections.append(e)}};function V(e){o.adminSaid.textContent=e,o.adminSaid.hidden=e===``}let Wn=async()=>{try{let e=await fetch(I.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;o.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,Un(t.connections??[]),Gn(t.publish??[],(t.channels??[]).map(e=>e.id)),Ia(t.home??``,t.root??``),$()}catch{o.adminNote.textContent=`lost touch with the server`}};function Gn(e,t){o.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Hn)return;if(Hn=n,e.length===0){s(o.publishList);return}let r=e.length-t.length;o.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,s(o.publishList,...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,o.textContent=`Copy`,o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let Kn=async()=>{if(p!==`remote`){o.adminPanel.hidden=!0,o.publishPanel.hidden=!0,Rn&&clearInterval(Rn),Rn=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(I.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;if(ne&&(e=!1),zt=i&&!e,o.adminPanel.hidden=!e,ha(e),_!==``){let e=_;_=``,Bt()?kn(e):(S=`Sign in to nixamp.com to go live here.`,z())}if(Rn&&clearInterval(Rn),Rn=null,$(),_i(),ga(),o.listenOnly.hidden=e,!e){o.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}o.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Wn(),Rn=setInterval(()=>void Wn(),2e3)};function qn(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;V(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(I.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),a=await i.json();if(!i.ok){V(a.error??`that did not work`);return}V(`${a.channel?.name||t||e} is on the air.`),o.adminSource.value=``,o.adminName.value=``,ga(),$()}catch{V(`could not reach the server`)}})()}o.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=o.adminSource.value.trim();t&&qn(t,o.adminName.value.trim())}),o.adminAdd.addEventListener(`click`,()=>{let e=o.adminSource.value.trim();if(!e)return;V(`Reading ${e}…`);let t=o.adminReplace.checked,n=o.adminName.value.trim();(async()=>{try{let r=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();V(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(o.adminSource.value=``,o.adminName.value=``,ga(),$())}catch{V(`could not reach the server`)}})()});let Jn=e=>{let t=Math.max(1,Math.round((Date.now()-e)/6e4));if(t<60)return`${t} minute${t===1?``:`s`} ago`;let n=Math.round(t/60);return`${n} hour${n===1?``:`s`} ago`},Yn=e=>{let t=[],n=G?e.filter(e=>e.ownerId&&e.ownerId!==G):[];if(o.recentNote.hidden=n.length===0,n.length===0){s(o.recentList);return}for(let e of n){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${Jn(e.endedAt)}`:`ended ${Jn(e.endedAt)}`,r.append(i,a),n.append(r,Ai(e.ownerId,e.name)),t.push(n)}s(o.recentList,...t)},Xn=e=>{let t=Math.max(0,Math.floor(e)),n=String(t%60).padStart(2,`0`),r=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(r).padStart(2,`0`)}:${n}`:`${r}:${n}`};function Zn(e){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.event.title||e.party.partyCode;let i=document.createElement(`span`);i.className=e.party.playing?`detail live`:`detail`,i.textContent=[e.party.playing?`▶ ${Xn(e.party.positionNow)}`:`❚❚ ${Xn(e.party.positionNow)}`,e.party.mediaTitle,e.party.origin,e.host?`yours`:``].filter(Boolean).join(` · `),n.append(r,i);let a=document.createElement(`a`);a.className=`button`,a.href=e.links.partyUrl||e.links.nixampUrl,a.rel=`noopener`,a.target=`_blank`,Wt(a),a.title=`Join live on the site hosting this party (opens in a new tab)`;let o=document.createElement(`a`);return o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.append(n,a,o),t}async function Qn(){if(!G){o.partiesPanel.hidden=!0;return}try{let e=await fetch(`/api/v1/watch-parties`);if(!e.ok){o.partiesPanel.hidden=!0;return}let t=(await e.json()).parties??[];o.partiesPanel.hidden=!1,o.partiesNote.textContent=t.length===0?`No parties happening right now. Join with an invite code.`:`Join a party on the site hosting the film, or open its room here.`,s(o.partiesList,...t.map(Zn))}catch{o.partiesPanel.hidden=!0}}o.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){S=n.error??`No party found with that invite code.`,z();return}o.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{S=`Could not look up that party. Try again.`,z()}})()});async function $n(){if(!G){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];o.connectionsNote.hidden=t.length===0,o.connectionsList.hidden=t.length===0,s(o.connectionsList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,a.textContent=`Disconnect`,a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await $n()})()}),t.append(n,a),t}))}catch{o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0}}let er=new Set,H=e=>{try{return new URL(e).origin}catch{return e}},tr=e=>[...er].some(t=>H(t)===H(e));async function nr(){if(!G){er=new Set,o.favoritesPanel.hidden=!0,ar();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){o.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];er=new Set(t.map(e=>e.url)),o.favoritesPanel.hidden=t.length===0,o.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,s(o.favoritesList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...oe({name:e.name||e.url,view:e.url,admin:ae(e.url)}),ir(e.url,e.name)),t}))}catch{o.favoritesPanel.hidden=!0}ar()}async function rr(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){S=n?`Could not save that favourite.`:`Could not remove that favourite.`,z();return}}catch{S=`could not reach nixamp.com`,z();return}if(n)er.add(e);else for(let t of[...er])H(t)===H(e)&&er.delete(t);await nr()}function ir(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=tr(e);n.textContent=t?`♥`:`♡`,n.dataset.on=t?`yes`:`no`,n.title=t?`Remove from favourites`:`Add to favourites`,n.setAttribute(`aria-label`,n.title)};return r(),n.addEventListener(`click`,n=>{n.stopPropagation();let i=[...er].find(t=>H(t)===H(e))??e;rr(tr(e)?i:e,t,!tr(e)).then(r)}),n}function ar(){let e=p===`remote`?I.shareLink:``;if(o.favHere.hidden=!(G&&e),o.favHere.hidden)return;let t=tr(e);o.favHere.textContent=t?`♥`:`♡`,o.favHere.dataset.on=t?`yes`:`no`,o.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,o.favHere.setAttribute(`aria-label`,o.favHere.title)}d(o.copyNow,`copy`),o.copyNow.addEventListener(`click`,()=>{Aa(F.source,o.copyNow,`✓`)});function or(e){if(e===``||e===kt)return;kt=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),n.textContent=r.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`});let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),o.logList.prepend(t);o.logList.children.length>100;)o.logList.lastElementChild?.remove()}let sr=3e3,U=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,cr=``,lr=``,ur=null,dr=!1,fr=new Set,pr=``,mr=null,hr=!1,gr=vt(e=>localStorage.getItem(e)),W=pt(e=>localStorage.getItem(e)),_r=new Set,vr=new Set,yr=null,br=``,xr=``,G=``,Sr=`listener-${crypto.randomUUID()}`,K=null,q=!1,Cr=``,wr=!1,Tr=0,Er=!1,Dr=!1;try{o.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let Or=new wt(()=>{Dr=!0,Er&&(o.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)}),J=new xt({playing:()=>F.playing,volume:()=>F.volume,active:e=>{Er=e,F.translatedAudio(e),Or.active(e&&o.transcriptBackground.checked)},status:e=>{o.transcriptAudioNote.textContent=e+(Dr&&Er?` · background unavailable`:``)},failed:()=>{xr=o.transcriptAudioNote.textContent||`Translated audio stopped.`,q=!1,o.transcriptAudio.checked=!1,jr()},authorization:async(e,t)=>{if(!G||U!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!K||K.channel!==t.channel||K.expires<Date.now()+2e4||K.remaining<t.text.length){let n=await fetch(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),r=await n.json();if(!n.ok||!r.token||!r.expires)throw Error(r.error||`Sign in to enable translated audio.`);K={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return K.remaining-=t.text.length,{authorization:`Bearer ${K.token}`}}}),kr=new Et({language:()=>W,speakers:()=>o.transcriptAudio.checked,voices:()=>yr?.voices??[],channel:()=>Sr,status:e=>{!wr&&!q&&(Cr=e),o.transcriptNote.textContent=e},failed:()=>{q=!1,o.transcriptAudio.checked=!1,J.disable(),jr()},lines:e=>{Ir=0,Lr.push(...e),ri(),Nr(),o.transcriptAudio.checked&&J.pushBatch(e.map(e=>({line:e,lag:0,url:`/api/v1/speech/synthesize`,init:{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:e.text,language:W,channel:Sr,speaker:e.speaker,voice:kr.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),Ar=new Ct(e=>{wr&&F.playing&&kr.push(e)});function jr(){Tr++,wr=!1,Ar.stop(),kr.reset(),Or.stop(),J.reset(),F.translatedAudio(!1),s(o.transcriptSpeakers)}async function Mr(){jr();let e=Tr;try{if(!G||U!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=F.audioInput();if(Dr=!1,o.transcriptAudio.checked&&o.transcriptBackground.checked&&Or.start(t.context,t.node).then(t=>{t&&e===Tr&&Or.active(Er&&o.transcriptBackground.checked)}),await Ar.start(t.context,t.node),e!==Tr)return;wr=!0,q=!0,Ir=0,zr??=setInterval(ri,250),o.transcriptNote.textContent=o.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==Tr)return;q=!1,o.transcriptAudio.checked=!1,J.disable(),jr(),Cr=t instanceof Error?t.message:`This audio could not be captured.`,o.transcriptNote.textContent=Cr}}function Nr(){let e=[...kr.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(o.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id,e.append(`Speaker ${t.id.split(`-`)[1]} `);let n=document.createElement(`select`);n.className=`transcript-language`,n.setAttribute(`aria-label`,`Voice for ${e.textContent?.trim()}`);for(let e of yr?.voices??[])n.append(new Option(e.name,e.id));n.value=t.voice,n.addEventListener(`change`,()=>{t.voice=n.value,J.reset()}),e.append(n),o.transcriptSpeakers.append(e)}o.transcriptVoiceSettings.hidden=!o.transcriptAudio.checked||!e.length;for(let e of o.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[o.audio,o.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{jr()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{q&&gr&&F.playing&&Mr()});e.addEventListener(`volumechange`,()=>{J.setVolume()})}let Pr=``,Fr=null,Ir=ht(6,!1),Lr=[],Rr=[],zr=null;function Br(){if(p!==`remote`)return null;let{base:e}=ve(Ma());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=w?w.id:E?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Vr(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${U}/api/v1/trollbox?${n.toString()}`}function Hr(){let e=Br(),t=e?`${e.server}|${e.channel}`:``;t!==cr&&(cr=t,lr=``,fr.clear(),o.trollboxList.replaceChildren(),ur&&clearTimeout(ur),ur=null,o.trollboxPanel.hidden=e===null,o.trollboxForm.hidden=!0,qr(!1),e&&(o.trollboxNote.textContent=`The room for ${R()||e.channel}. Loading…`,Wr()))}function Ur(e){let t=document.createElement(`li`);t.dataset.id=e.id;let n=document.createElement(`time`);n.className=`when`,n.dateTime=e.createdAt;let r=new Date(e.createdAt);n.textContent=Number.isNaN(r.getTime())?``:r.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`});let i=document.createElement(`span`);i.className=`who`,i.textContent=e.handle;let a=document.createElement(`span`);return a.className=`line`,a.textContent=e.body,t.append(n,i,a),t}async function Wr(){let e=Br(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===cr&&!dr){dr=!0;try{let n=await fetch(Vr(e,lr)),r=await n.json().catch(()=>({}));if(t!==cr)return;if(!n.ok){o.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!fr.has(e.id));for(let e of i)fr.add(e.id),o.trollboxList.append(Ur(e)),lr=e.createdAt;for(;o.trollboxList.children.length>200;)o.trollboxList.firstElementChild?.remove();let a=r.you??``,s=pr!==a;pr=a,s&&(K=null,ai()),o.trollboxForm.hidden=a===``,o.trollboxEditLabel.hidden=a===``||!Gr,a===``&&qr(!1),o.trollboxNote.textContent=a===``?U===``?`The room for ${R()||e.channel}. Sign in to say something.`:`The room for ${R()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${a} in the room for ${R()||e.channel}.`}catch{t===cr&&(o.trollboxNote.textContent=`The trollbox is not answering.`)}finally{dr=!1,t===cr&&(ur=setTimeout(()=>{document.visibilityState===`visible`?Wr():ur=setTimeout(()=>void Wr(),sr)},sr))}}}o.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Br(),n=o.trollboxInput.value.trim();t&&n!==``&&(o.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${U}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:n})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.message){o.trollboxNote.textContent=r.error??`that did not send`;return}o.trollboxInput.value=``,fr.has(r.message.id)||(fr.add(r.message.id),o.trollboxList.append(Ur(r.message)),lr=r.message.createdAt)}catch{o.trollboxNote.textContent=`The trollbox is not answering.`}finally{o.trollboxInput.disabled=!1}})())});let Gr=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Kr=Gr?st(e=>MediaRecorder.isTypeSupported(e)):``;o.trollboxMic.hidden=!Gr;function Y(e){o.trollboxNote.textContent=e,or(e)}function qr(e){let t=mr;if(!t)return;mr=null,clearTimeout(t.stop),clearInterval(t.tick),o.trollboxMic.setAttribute(`aria-pressed`,`false`),o.trollboxMic.textContent=`🎤`;let n=new Promise(e=>{t.recorder.addEventListener(`stop`,()=>e(),{once:!0})});t.recorder.state!==`inactive`&&t.recorder.stop();for(let e of t.stream.getTracks())e.stop();e&&n.then(()=>Yr(new Blob(t.chunks,{type:t.recorder.mimeType||Kr||`audio/webm`}),t.startedAt))}async function Jr(){if(mr||hr||pr===``||!Br())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){Y(e.name===`NotAllowedError`?`The microphone was refused. Allow it for nixamp.com and tap again.`:`No microphone could be opened here.`);return}let t;try{t=new MediaRecorder(e,Kr?{mimeType:Kr}:{})}catch{for(let t of e.getTracks())t.stop();Y(`This browser cannot record the microphone.`);return}let n=[];t.addEventListener(`dataavailable`,e=>{e.data.size>0&&n.push(e.data)});let r=Date.now();mr={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>qr(!0),ot),tick:setInterval(()=>{o.trollboxMic.textContent=lt(r,Date.now())},500)},t.start(250),o.trollboxMic.setAttribute(`aria-pressed`,`true`),o.trollboxMic.textContent=lt(r,r),Y(`Listening. Tap the mic again when you have said it (${Math.round(ot/1e3)} s at most).`)}async function Yr(e,t){let n=Br();if(n&&pr!==``){if(Date.now()-t<400||e.size===0){Y(`That was too short to hear. Tap, say it, then tap again.`);return}hr=!0,o.trollboxMic.disabled=!0,o.trollboxMic.textContent=`…`,Y(`Hearing you…`);try{let t=new AudioContext,r;try{r=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let i=new OfflineAudioContext(1,Math.max(1,Math.ceil(r.duration*at)),at),a=i.createBufferSource();a.buffer=r,a.connect(i.destination),a.start();let s=ct((await i.startRendering()).getChannelData(0),at),c=o.trollboxEdit.checked,l=new URLSearchParams(c?{}:{server:n.server,channel:n.channel}),u=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(u)&&l.set(`language`,u);let d=await fetch(`${U}/api/v1/speech/transcribe?${l.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([s.buffer],{type:`audio/wav`})}),f=await d.json().catch(()=>({}));if(!d.ok){Y(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){Y(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=o.trollboxInput.value.trimEnd();o.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),Y(`Heard: “${p}”. Send it, or fix it first.`);return}Br()&&!fr.has(f.message.id)&&(fr.add(f.message.id),o.trollboxList.append(Ur(f.message)),lr=f.message.createdAt),Y(`Said: “${f.message.body}”`)}catch{Y(`That recording could not be read here.`)}finally{hr=!1,o.trollboxMic.disabled=!1,o.trollboxMic.textContent=`🎤`}}}o.trollboxMic.addEventListener(`click`,()=>{mr?qr(!0):Jr()});try{o.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}o.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,o.trollboxEdit.checked?`on`:`off`)}catch{}Y(o.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Xr(){try{let e=await fetch(`${U}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){o.personaNote.textContent=t.error??`Could not read your profile.`;return}o.personaHandle.value=t.chosen?t.handle??``:``,o.personaHandle.placeholder=t.handle||`handle`,o.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,o.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;o.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${Zr(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${Zr(t.voice??``)}${n}.`}catch{o.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function Zr(e){return e===`female`?`in a woman's voice`:e===`male`?`in a man's voice`:e.includes(`.`)?`in the voice ${e}`:`in whichever voice your profile says, or one picked for you`}o.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.personaHandle.value.trim(),n={voice:o.personaVoice.value,profile:o.personaProfile.value.trim()};t!==``&&(n.handle=t),o.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${U}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){o.personaNote.textContent=t.error??`that did not save`;return}await Xr()}catch{o.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&mr&&qr(!0)});function Qr(){return p===`remote`&&w?{id:w.id,name:w.name,hls:w.video&&Vt()}:F.loaded||O?{id:Sr,name:R()||`This audio`,hls:!1}:null}function $r(){jr(),K=null,_r.clear(),vr.clear(),Fr?.close(),Fr=null,zr&&clearInterval(zr),zr=null,Lr=[],Rr=[],o.transcriptList.replaceChildren(),o.subtitle.hidden=!0,o.subtitle.textContent=``}function ei(){let e=Qr(),t=`${e?.id??``}|${F.mediaKey}|${gr}|${W}|${o.transcriptAudio.checked}|${q}|${G}`;if(t!==Pr){if(Pr=t,$r(),o.transcriptPanel.hidden=!1,o.transcriptOn.checked=gr&&(!!w||q||o.transcriptAudio.checked),o.transcriptLanguage.options.length===0)for(let e of ft)o.transcriptLanguage.append(new Option(e.label,e.code));if(o.transcriptLanguage.value=W,ai(),oi(),!e){o.transcriptNote.textContent=`Play something to see its captions.`;return}if(!gr){o.transcriptNote.textContent=`Captions are off.`;return}if(Cr){o.transcriptNote.textContent=Cr;return}o.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,o.transcriptAudio.checked||q?F.playing?Mr():o.transcriptNote.textContent=`Press Play to start listening.`:p===`remote`&&w?ti(e,t):o.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function ti(e,t){let n=6,r=W?`?language=${encodeURIComponent(W)}`:``;try{let i=await fetch(I.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),a=await i.json().catch(()=>({}));if(t!==Pr)return;if(!i.ok){o.transcriptNote.textContent=a.error??`This server is not captioning.`;return}if(a.recognitionRevision!==`native-v2`){G&&U===``?(q=!0,ei()):o.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=a.backlog??n}catch{t===Pr&&(o.transcriptNote.textContent=`The server did not answer about captions.`);return}Ir=ht(n,e.hls);let i=new EventSource(I.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));Fr=i;let a=(e,t=!1)=>{for(let n of e){if(!n||typeof n.text!=`string`||!Number.isFinite(n.at)||!Number.isFinite(n.until))continue;let e=`${n.at}|${n.language}`;_r.has(e)||(_r.add(e),_r.size>600&&_r.delete(_r.values().next().value),Lr.push(n),t&&o.transcriptAudio.checked&&vr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==Pr)return;let i=JSON.parse(r.data);Ir=ht(i.backlog??n,e.hls),a(i.lines??[]);let s=ft.find(e=>e.code===i.language)?.label??i.language,c=ft.find(e=>e.code===W)?.label??W;if(o.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:W?`${s||`Detected audio`} → ${c}`:`Original audio · ${s||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${U||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,o.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==Pr)return;let r=JSON.parse(n.data);a([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=ft.find(e=>e.code===i)?.label??i,c=ft.find(e=>e.code===W)?.label??W;o.transcriptNote.textContent=W?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===Pr&&i.readyState===EventSource.CLOSED&&(o.transcriptNote.textContent=`Captions stopped; the server went away.`)}),zr=setInterval(ri,250)}function ni(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),n.textContent=yt(e.at);let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text;let i=mt(e);if(i){let a=document.createElement(`span`);a.className=`lang`,a.textContent=i.trim(),e.original&&(r.title=e.original),t.append(n,a,r)}else t.append(n,r);return t}function ri(){let e=Date.now(),{ready:t,still:n}=gt(Lr,e,Ir);Lr=n;for(let e of t)if(Rr.push(e),o.transcriptList.append(ni(e)),vr.delete(e)&&o.transcriptAudio.checked&&W){let t=new URLSearchParams({at:String(e.at),language:W,voice:`auto`});J.push(e,I.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),Ir)}for(;Rr.length>200;)Rr.shift();for(;o.transcriptList.children.length>200;)o.transcriptList.firstElementChild?.remove();let r=_t(Rr,e,Ir),i=o.transcriptList.children,a=r?Rr.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let s=F.playing&&r!==null&&!o.video.hidden&&o.video.offsetHeight>0;o.subtitle.hidden=!s,s&&r&&(o.subtitle.textContent!==r.text&&(o.subtitle.textContent=r.text),o.subtitle.style.top=`${o.video.offsetTop+o.video.offsetHeight-o.subtitle.offsetHeight-10}px`)}o.transcriptOn.addEventListener(`change`,()=>{gr=o.transcriptOn.checked,q=gr&&(!w||o.transcriptAudio.checked),gr||(o.transcriptAudio.checked=!1,J.disable());try{localStorage.setItem(ut,gr?`on`:`off`)}catch{}ei()}),o.transcriptLanguage.addEventListener(`change`,()=>{Cr=``,xr=``,W=pt(()=>o.transcriptLanguage.value),!W&&o.transcriptAudio.checked&&(o.transcriptAudio.checked=!1,q=!1,J.disable());try{W?localStorage.setItem(dt,W):localStorage.removeItem(dt)}catch{}ei()});function ii(){if(W)return W;let e=navigator.language.split(`-`)[0]||`en`;return ft.some(t=>t.code===e)&&yr?.languages.includes(e)?e:`en`}function ai(){let e=G!==``&&U===``,t=e&&!!Qr()&&!!yr?.languages.includes(ii());o.transcriptAudio.disabled=!t,o.transcriptVoiceSettings.contains(document.activeElement)||(o.transcriptVoiceSettings.hidden=!o.transcriptAudio.checked||!o.transcriptSpeakers.children.length),t?o.transcriptAudio.checked||(o.transcriptAudioNote.textContent=xr||`Original audio.`):(o.transcriptAudio.checked=!1,J.disable(),o.transcriptAudioNote.textContent=e?Qr()?xr||(yr?`Audio translation is unavailable for this language.`:`Loading voices…`):`Play something to translate its audio.`:`Sign in to translate audio.`)}async function oi(){if(!G||U!==``)return;let e=`/api/v1/speech/voices`;if(br!==e){br=e,yr=null,xr=``,ai();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(br!==e)return;if(!t.ok)throw Error(n.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(n.voices)||!Array.isArray(n.languages))throw Error(`This server needs an update for translated audio.`);yr=n}catch(t){if(br!==e)return;xr=t instanceof Error?t.message:`Translated audio is unavailable.`}ai()}}o.transcriptBackground.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.backgroundSound`,o.transcriptBackground.checked?`on`:`off`)}catch{}if(Or.stop(),Dr=!1,o.transcriptBackground.checked&&o.transcriptAudio.checked&&F.playing){let e=Tr,t=F.audioInput();Or.start(t.context,t.node).then(t=>{t&&e===Tr&&Or.active(Er&&o.transcriptBackground.checked)})}}),o.transcriptAudio.addEventListener(`change`,()=>{if(Cr=``,xr=``,vr.clear(),o.transcriptAudio.checked){W=ii();try{localStorage.setItem(dt,W)}catch{}gr=!0,q=!0,J.enable()}else q=!1,J.disable();ei()});function si(){if(O)return O.url;if(p!==`remote`)return``;let{base:e,key:t}=ve(Ma());if(e===``)return``;if(w)return ge(e,`/api/channels/${encodeURIComponent(w.id)}`,t);if(E?.kind===`live`)return ge(e,`/api/live`,t);if(F.source===``)return``;try{let n=new URL(F.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function ci(){let e=si();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}o.shareNow.addEventListener(`click`,()=>{let e=ci();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${Yt()} on nixamp`,url:e}).catch(()=>void 0);return}Aa(e,o.shareNow,`Copied`)}),o.favHere.addEventListener(`click`,()=>{let e=Ma()||I.shareLink;if(!e)return;let t=[...er].find(t=>H(t)===H(e))??e;rr(tr(e)?t:e,m||I.address,!tr(e)).then(ar)});let li=r?a:200,ui=[],X=null,Z=null,di=``,fi=[],pi=0,mi=null,hi=0;function gi(e){if(!e)return`never`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));if(t<90)return`just now`;let n=Math.round(t/60);if(n<90)return`${n} min ago`;let r=Math.round(n/60);return r<36?`${r} h ago`:`${Math.round(r/24)} d ago`}async function _i(){if(p!==`remote`){o.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(I.url(`/api/catalogs`))}catch{o.catalogsPanel.hidden=!0;return}if(!e.ok){o.catalogsPanel.hidden=!0;return}ui=(await e.json().catch(()=>({}))).catalogs??[],X&&=ui.find(e=>e.id===X?.id)??null,X||(Z=null),o.catalogsPanel.hidden=!1,vi()}function vi(){let e=!o.adminPanel.hidden;o.catalogsForm.hidden=!e;let t=ui.reduce((e,t)=>e+t.live,0),n=ui.reduce((e,t)=>e+t.vod,0);o.catalogsNote.textContent=ui.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${ui.length} ${ui.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,yi();let r=X!==null&&Z!==null;if(o.catalogsList.hidden=r,o.catalogsFilter.hidden=!r,o.catalogsEntries.hidden=!r,r){wi();return}if(X){xi(X);return}s(o.catalogsList,...ui.map(t=>bi(t,e)))}function yi(){let e=X!==null;if(o.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>{X=null,Z=null,vi()},!1),n(),t(X?.name??``,()=>{Z=null,vi()},Z===null)];Z!==null&&r.push(n(),t(Z===``?`All groups`:Z,()=>void 0,!0)),o.catalogsCrumbs.replaceChildren(...r)}function bi(e,t){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);if(a.className=`detail`,a.textContent=[`${e.entries.toLocaleString()} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString()} live`,`${e.vod.toLocaleString()} on demand`,`refreshed ${gi(e.refreshedAt)}`].join(` · `),r.append(i,a),t&&e.error){let t=document.createElement(`span`);t.className=`detail`,t.textContent=e.error,r.append(t)}let o=document.createElement(`button`);if(o.type=`button`,o.className=`button`,o.textContent=`Browse`,o.addEventListener(`click`,()=>{X=e,Z=null,vi()}),n.append(r,o),t){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Refresh`,t.title=`Read the list again`,t.addEventListener(`click`,()=>{Ei(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Remove`,r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Di(e)}),n.append(t,r)}return n}async function xi(e){s(o.catalogsList);let t=[];try{let n=await T(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`)));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{S=`Could not read the groups in ${e.name}.`,z();return}if(X?.id!==e.id||Z!==null)return;let n=[Si(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>Si(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];s(o.catalogsList,...n)}function Si(e,t,n,r,i){let a=document.createElement(`li`),s=document.createElement(`span`);s.className=`server-label`;let c=document.createElement(`span`);c.className=`name`,c.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${n.toLocaleString()} · ${r.toLocaleString()} live · ${i.toLocaleString()} on demand`,s.append(c,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{Z=t,di=``,o.catalogsFilter.value=``,fi=[],pi=0,vi(),Ci(0)}),a.append(s,u),a}async function Ci(e){let t=X,n=Z;if(!t||n===null)return;let r=++hi,i=new URLSearchParams({group:n,q:di,offset:String(e),limit:String(li)}),a;try{let e=await T(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`)));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{S=`Could not read ${t.name}.`,z();return}r===hi&&(pi=a.total??0,fi=e===0?a.entries??[]:[...fi,...a.entries??[]],wi())}function wi(){let t=X;if(!t)return;let n=fi.map(n=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`name`,i.textContent=n.title;let a=document.createElement(`span`);if(a.className=n.live?`catalog-tag catalog-live`:`catalog-tag`,a.textContent=n.live?`LIVE`:n.duration>0?e(n.duration):`VOD`,r.append(i,a),!n.live){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,d(e,`copy`),e.title=`Copy this entry's URL`,e.setAttribute(`aria-label`,`Copy the URL of ${n.title}`),e.addEventListener(`click`,r=>{r.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(t.id)}/entries/${encodeURIComponent(n.id)}/stream`;Aa(I.url(i),e,`✓`)}),r.append(e)}return Bt()&&r.append(Gt(()=>({kind:`entry`,catalog:{id:t.id,name:t.name},entry:n}),n.title)),r.addEventListener(`click`,()=>{Ti(t,n,r)}),r});if(fi.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=di?`Nothing called "${di}" here.`:`Nothing in this group.`,e.append(t),n.push(e)}else if(fi.length<pi){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${fi.length.toLocaleString()} of ${pi.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),Ci(fi.length)}),e.append(t),n.push(e)}s(o.catalogsEntries,...n)}async function Ti(e,t,n){n?.classList.add(`loading`),S=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await T(async()=>{let n,i={};try{n=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{S=`could not reach the server`;return}if(!n.ok){S=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await wa({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){w=null,C=-1,E={kind:`vod`,...r},et(a,`title`),await F.load({title:a,artist:``,album:``,duration:0,url:I.url(i.url),video:!0,objectUrl:!1},!0),Cn(!0),S=`Playing ${a}.`;return}S=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),z()}}async function Ei(e){V(`Reading ${e.name} again…`);try{let t=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));V(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{V(`could not reach the server`)}_i()}async function Di(e){try{V((await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{V(`could not reach the server`)}X?.id===e.id&&(X=null,Z=null),_i()}o.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.catalogSource.value.trim(),n=o.catalogName.value.trim();t&&(async()=>{V(`Reading ${n||t}…`);try{let e=await fetch(I.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){V(r.error??`that did not work`);return}V(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString()} entries.`),o.catalogSource.value=``,o.catalogName.value=``}catch{V(`could not reach the server`)}_i()})()}),o.catalogsFilter.addEventListener(`input`,()=>{mi&&clearTimeout(mi),mi=setTimeout(()=>{mi=null,di=o.catalogsFilter.value.trim(),Ci(0)},250)});let Oi=async()=>{s(o.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){o.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ie=new Map(t.map(e=>[H(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),o.serversPanel.hidden=!1,o.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. Arriving signed in, this page connects to your default one, or the first that answers; a link you arrive with goes live there.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let a=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=oe({name:e.name,view:a,admin:a});De(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=Gi()===H(e.url),u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=l?`✓ Default`:`Make default`,u.title=l?`The server this page connects to when you arrive signed in. Press to go back to the first that answers.`:`Connect to this server whenever you arrive signed in`,u.addEventListener(`click`,()=>{Ki(l?``:H(e.url)),Oi()});let d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=`Forget`,d.addEventListener(`click`,()=>{(async()=>{d.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await Oi()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),o.serversList.append(t)}}catch{o.serversPanel.hidden=!0}},ki=async()=>{s(o.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){o.followingNote.hidden=!0;return}let t=(await e.json()).following??[];o.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let a=document.createElement(`button`);a.type=`button`,a.className=`ghost follow`,a.textContent=`Unfollow`,a.addEventListener(`click`,()=>{(async()=>{a.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),o.followingList.children.length===0&&(o.followingNote.hidden=!0)}finally{a.disabled=!1}})()}),t.append(n,a),o.followingList.append(t)}}catch{o.followingNote.hidden=!0}},Ai=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,n.textContent=`Follow`,n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{n.textContent=e?`Following`:`Follow`,n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),ki())}catch{}finally{n.disabled=!1}})()}),n},ji=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},Mi=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Ni=async()=>{if(!Mi())return o.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return o.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return o.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return o.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ji(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return o.notifyNote.textContent=`This device will be told.`,!0}catch{return o.notifyNote.textContent=`Could not set this device up.`,!1}},Pi=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},Fi=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();o.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(o.notifyPhone.value=n.phone)}catch{o.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Ii=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();o.notifyEmail.checked=t.wantsEmail!==!1,o.notifySms.checked=t.wantsSms===!0,o.notifyPhone.value=t.phone??``;let n=Mi()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;o.notifyWeb.checked=t.wantsWeb!==!1&&n,o.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};o.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(o.notifyWeb.checked){let e=await Ni();o.notifyWeb.checked=e,await Fi({wantsWeb:e});return}await Pi(),await Fi({wantsWeb:!1}),o.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),o.notifyEmail.addEventListener(`change`,()=>{Fi({wantsEmail:o.notifyEmail.checked})}),o.notifySms.addEventListener(`change`,()=>{(async()=>{if(o.notifySms.checked&&!o.notifyPhone.value.trim()){o.notifyPhoneNote.textContent=`Add a phone number first.`,o.notifySms.checked=!1;return}await Fi({wantsSms:o.notifySms.checked})})()}),o.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),Fi({phone:o.notifyPhone.value.trim()})});let Li=!1,Ri=!1,zi=`nixamp.welcome`,Bi=()=>{let e=!1;try{e=localStorage.getItem(zi)===`hidden`}catch{}o.welcome.hidden=!Ri||G!==``||e},Vi=e=>{let t=e!==null;br=``,K=null,t||(q=!1,o.transcriptAudio.checked=!1,J.disable(),jr()),ei(),o.notifyPanel.hidden=!t,t?(Ii(),ki(),Oi()):(o.serversPanel.hidden=!0,o.followingNote.hidden=!0,s(o.followingList),o.recentNote.hidden=!0,o.recentList.replaceChildren()),o.accountForm.hidden=t,o.accountProviders.hidden=t||o.accountProviders.childElementCount===0,o.accountSignOut.hidden=!t,o.personaForm.hidden=!t,o.personaNote.hidden=!t,t&&Xr(),o.accountNote.textContent=t?`Signed in as ${e}.`:Li?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,o.accountSubmit.textContent=Li?`Create account`:`Sign in`,o.accountToggle.textContent=Li?`I have one`:`Create one`,o.accountPassword.autocomplete=Li?`new-password`:`current-password`,Bi()},Hi=async()=>{let e=[];Ri=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Ri=!0,e=(await t.json()).providers??[])}catch{}o.accountProviders.replaceChildren(),o.accountProviders.hidden=e.length===0,o.accountPanel.hidden=!Ri,o.accountElsewhere.hidden=Ri,Bi();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,o.accountProviders.append(e)}},Ui=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();G=e.ok?t.account?.id??``:``,Vi(e.ok?t.account?.email??`you`:null)}catch{G=``,Vi(null)}if(I.session=``,G!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));I.session=e.ok&&typeof t.token==`string`?t.token:``}catch{I.session=``}p===`remote`&&Kn()}nr(),Qn(),$n(),qi();let e=await Wi();if(Ot!==``){let t=Ot;Ot=``,e?v=`golive:${t}`:Tn(t)}};async function Wi(){if(G===``||p===`remote`||Dt!==``)return!1;let e=[];try{let t=await fetch(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=Gi(),n=[...e].sort((e,n)=>Number(H(n.url)===t)-Number(H(e.url)===t));for(let e of n)if(await De(e.url,void 0,e.key)!==null)return p!==`remote`&&(ne=!1,v=``,o.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,S=`Connecting to ${e.name}, your server…`,z(),o.remoteForm.requestSubmit(),!0);return!1}function Gi(){try{return localStorage.getItem(Mt)??``}catch{return``}}function Ki(e){try{e===``?localStorage.removeItem(Mt):localStorage.setItem(Mt,e)}catch{}}function qi(){if(Dt===``)return;let e=Dt;Dt=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit()}o.accountToggle.addEventListener(`click`,()=>{Li=!Li,Vi(null)}),o.welcomeCreate.addEventListener(`click`,()=>{Li=!0,Vi(null),o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),o.accountEmail.focus({preventScroll:!0})}),o.welcomeBrowse.addEventListener(`click`,()=>{o.directory.hidden?o.browse.click():o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(zi,`hidden`)}catch{}o.welcome.hidden=!0}),o.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.accountEmail.value.trim(),n=o.accountPassword.value;(async()=>{o.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${Li?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){o.accountNote.textContent=r.error??`that did not work`;return}G=r.account?.id??``,o.accountPassword.value=``,Vi(r.account?.email??t),Kn(),qi()}catch{o.accountNote.textContent=`could not reach nixamp.com`}finally{o.accountSubmit.disabled=!1}})()}),o.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}G=``,Vi(null),I.close(),C=-1,p=`local`,x=`idle`,de=``,o.remoteUrl.value=``,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.catalogsPanel.hidden=!0,o.listenOnly.hidden=!0,ya(!1);try{localStorage.removeItem(jt)}catch{}S=`Signed out, and disconnected from the server.`,Kn(),z()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Dt=t,v=e.get(`play`)??``,re=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t,S=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(o.linkUrl.value=n,t!==``&&v===``?v=`link:${n}`:t===``&&(Ot=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=_e(r);t?(Dt=t.view,v=t.what,re=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t.view,S=`Opening the stream you were sent…`):(o.linkUrl.value=r,Ot=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Ji=[`zone-top`,`zone-main`],Yi=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Xi=e=>e.parentElement&&Ji.includes(e.parentElement.id)?e.parentElement:null,Zi=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Qi=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Yi(e)&&Xi(e)!==null),$i=e=>e.dataset.title??e.id,ea=new Map,ta=Qi().map((e,t)=>(ea.set(e.id,{zone:Xi(e)?.id??``,col:Zi(e),index:t}),e.id)),Q=Ze();try{Q=tt(localStorage.getItem(Xe))}catch{}let na=()=>Q.order.length>0||Object.keys(Q.placement).length>0;function ra(){Q.order=Qi().map(e=>e.id);try{localStorage.setItem(Xe,nt(Q))}catch{}}function ia(e,t,n){e.classList.remove(`col-a`,`col-b`),t.classList.contains(`split`)&&n!==``&&e.classList.add(`col-${n}`),t!==e.parentElement&&t.append(e)}function aa(){for(let e of Qi()){let t=Q.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Ji.includes(i.id)&&ia(e,i,r===`a`||r===`b`?r:``)}let e=rt(Qi().map(e=>e.id),Q.order);for(let t of Ji){let n=document.getElementById(t);if(!n)continue;let r=[...n.children].filter(Yi),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((t,n)=>e.indexOf(t.id)-e.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of Qi())e.toggleAttribute(`data-collapsed`,Q.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Q.closed.includes(e.id))}function oa(e,t){e.toggleAttribute(`data-collapsed`,t),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),Q.collapsed=it(Q.collapsed,e.id,t),ra(),pa()}function sa(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),t&&n&&o.panelsToggle.focus({preventScroll:!0}),Q.closed=it(Q.closed,e.id,t),ra(),pa()}function ca(e,t,n){let r=Xi(t);r&&e!==t&&(ia(e,r,Zi(t)),n?t.after(e):t.before(e),Q.placement[e.id]=`${r.id}:${Zi(t)}`,ra(),pa())}let la=null,ua=()=>{for(let e of Qi())e.classList.remove(`drop-before`,`drop-after`)},da=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon-btn`,r.textContent=e,r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,e=>{e.stopPropagation(),n()}),r};function fa(){for(let e of Qi()){let t=$i(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);if(n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n)),n.textContent!==t&&(n.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let r=document.createElement(`span`);r.className=`panel-tools`;let i=da(`≡`,`Move ${$i(e)}: Alt plus Up or Down, or drag`,()=>void 0);i.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=Qi().filter(t=>Xi(t)===Xi(e)&&Zi(t)===Zi(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(ca(e,r,t.key===`ArrowDown`),i.focus({preventScroll:!0}))}),i.classList.add(`grip`),i.draggable=!0,i.addEventListener(`dragstart`,t=>{la=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),i.addEventListener(`dragend`,()=>{la=null,e.classList.remove(`dragging`),ua()});let a=da(`▁`,`Shade ${$i(e)} to its title`,()=>oa(e,!e.hasAttribute(`data-collapsed`)));a.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let o=da(`✕`,`Hide ${$i(e)}; the Panels list turns it back on`,()=>sa(e,!0));r.append(i,a,o),e.prepend(r),e.addEventListener(`dragover`,t=>{if(!la||la===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;ua(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!la||la===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);ua(),ca(la,e,n)})}}function pa(){if(o.panelsPanel.hidden||o.panelsList.contains(document.activeElement))return;let e=Qi().filter(e=>e!==o.panelsPanel).map(e=>{let t=document.createElement(`li`),n=e.hasAttribute(`data-closed`);t.classList.toggle(`off`,n);let r=document.createElement(`label`),i=document.createElement(`input`);i.type=`checkbox`,i.checked=!n,i.setAttribute(`aria-label`,`${$i(e)} on`),i.addEventListener(`change`,()=>sa(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,a.textContent=$i(e),r.append(i,a);let o=document.createElement(`span`);return o.className=`detail`,o.textContent=n?`off`:e.hasAttribute(`data-collapsed`)?`shaded`:e.hidden?`nothing to show right now`:``,t.append(r,o),t});o.panelsList.replaceChildren(...e)}function ma(){Q=Ze();for(let e of ta){let t=document.getElementById(e),n=ea.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(ia(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Q.order=[...ta],aa(),Q=Ze();try{localStorage.removeItem(Xe)}catch{}pa()}function ha(e){if(!e||na())return;let t=Xi(o.adminPanel);if(!t)return;let n=[...t.children].filter(Yi).find(e=>Zi(e)===Zi(o.adminPanel));n&&n!==o.adminPanel&&n.before(o.adminPanel),o.adminPanel.removeAttribute(`data-collapsed`),o.adminPanel.removeAttribute(`data-closed`)}o.panelsToggle.addEventListener(`click`,()=>{let e=o.panelsPanel.hidden;o.panelsPanel.hidden=!e,o.panelsToggle.setAttribute(`aria-expanded`,String(e)),e&&(o.panelsPanel.hasAttribute(`data-closed`)&&sa(o.panelsPanel,!1),pa(),o.panelsPanel.scrollIntoView({behavior:`smooth`,block:`nearest`}))}),o.panelsReset.addEventListener(`click`,ma),new MutationObserver(()=>{fa(),pa()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),fa(),aa(),Hi(),Ui(),Kn(),jn(),o.browse.addEventListener(`click`,()=>{if(!o.directory.hidden){o.directory.hidden=!0;return}Ln(),o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.disconnect.addEventListener(`click`,()=>{I.close(),o.listenOnly.hidden=!0,C=-1,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.onairPanel.dataset.title=`Parties on this server`,o.catalogsPanel.hidden=!0,o.catalogsPanel.dataset.title=`Catalogs on this server`,m=``,se=``,ar(),ya(!1),p=`local`,x=`idle`,de=``,z()});async function ga(){if(p!==`remote`||I.shareLink===``){o.sharePanel.hidden=!0;return}o.sharePanel.hidden=!1;let e=Ma(),t=globalThis.location.origin;o.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,o.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,o.sharePhone.hidden=!0,o.shareSend.hidden=!0,o.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(I.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,se=r.url,o.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(bt=r.live,St=r.live?r.code:``,A=n,o.liveControls.hidden=o.adminPanel.hidden||!r.possible,o.goLive.hidden=r.live,o.stopLive.hidden=!r.live,o.sharePhone.hidden=!1,!r.live){o.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){o.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,o.shareSend.hidden=!1;return}o.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),Ra(n),document.createTextNode(` and key `),Ra(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),o.shareSend.hidden=!1}}let _a=``,va=null,ya=e=>{va&&clearInterval(va),va=null,e&&(va=setInterval(()=>void $(),6e3))};async function $(){if(p!==`remote`){o.onairPanel.hidden=!0;return}let e;try{let t=await fetch(I.url(`/api/streams`));if(!t.ok){o.onairPanel.hidden=!0;return}e=await t.json(),ee=e.server.carries!==!1,e.server.name&&e.server.name!==m&&(m=e.server.name,o.onairPanel.dataset.title=`Parties on ${m}`,o.catalogsPanel.dataset.title=`Catalogs on ${m}`,ar(),z())}catch{o.onairPanel.hidden=!0;return}o.onairPanel.hidden=!1,D=e,Na(e),z(),ba(e)}function ba(e){let t=qt(),n=`${o.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}:${t.fullTitle}:${t.position}`;if(n===_a)return;_a=n;let r=e.restreams??[],i=e.channels.length+r.length;o.onairNote.textContent=i===0?`One stream, from this server's own files.`:`${i+1} streams: this server's own files, and ${i} more on it.`;let a=[],l=e.server.playing,u=!o.adminPanel.hidden;a.push(Pa({title:e.server.name,detail:[l?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${c(e.server.nowPlaying)}`:`nothing loaded`,l&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:l?`Join party`:u?`Start the stream`:`Nothing playing`,onPlay:()=>{if(l){Ca(e.server.nowPlaying);return}u&&Sa()},link:e.server.live?e.server.url:``,...l?{page:ja(`live`)}:{},direct:l?I.url(`/api/live`):``}));for(let e of r)a.push(Pa({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{tn(e.at)},link:``,direct:I.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=I.url(`/api/channels/${encodeURIComponent(t.id)}`),r=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&r.push(`☎ ${t.code}`),t.redials&&r.push(`redialled ${t.redials}×`),u&&t.error&&r.push(t.error),a.push(Pa({title:t.name,detail:r.join(` · `),onPlay:()=>{wa({id:t.id,name:t.name,video:e,art:t.art})},link:n,page:ja(`channel:${t.id}`),direct:n,onRestart:u&&t.via===`pull`?()=>{Da(t.id,t.name)}:void 0,onStop:u||zt&&G!==``&&t.startedBy===G?()=>{ka(t.id,t.name)}:void 0,onRename:u||zt&&G!==``&&t.startedBy===G?()=>{Oa(t.id,t.name)}:void 0}))}s(o.onairList,...a)}async function xa(){if(p===`remote`)try{if((await fetch(I.media(L(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;S=G===``?`This stream is busy enough to be charging for. Sign in to nixamp.com to pay for a pass.`:`This stream is charging for a pass. Follow the payment prompt to keep listening.`,G===``&&o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),z()}catch{}}async function Sa(){V(`Starting the stream on the server…`);try{await I.send({type:`play`,index:Math.max(0,L())})}catch{V(`could not reach the server`);return}await Ca(b.tracks[L()]?.title??``),V(`Playing to the room. Anybody with the view link sees this.`),await $()}async function Ca(e){C=-1,w=null,E={kind:`live`},et(e,`auto`),await T(()=>F.load({title:e||`Live`,artist:``,album:``,duration:0,url:I.url(`/api/live`),video:!0,objectUrl:!1},!0)),Cn(!0),S=`Watching what this server is playing. Everyone here sees the same thing.`,z()}async function wa(e,t=!0,n){C=-1,w=e,t&&(be=0),t&&(E=n??{kind:`channel`}),t&&et(e.name,E?.link||At(e.name)?`auto`:`channel`);let r=e.video&&Vt();await T(()=>F.load({title:e.name,artist:``,album:``,duration:0,url:I.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),Cn(e.video),w===e&&(S=`Watching ${e.name}, live on this server.`),z()}function Ta(){let e=w;return e?Tt?!0:be>=5?(S=`${e.name} stopped, and did not come back.`,w=null,E=null,z(),!0):(be+=1,S=`${e.name} started over; rejoining…`,z(),Tt=setTimeout(()=>{Tt=null,w===e&&wa(e,!1)},2e3),!0):!1}function Ea(e){o.onairNote.textContent=e,V(e)}async function Da(e,t){Ea(`Restarting ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));Ea(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{Ea(`could not reach the server`)}_a=``,$()}async function Oa(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){Ea(`Renaming ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));Ea(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{Ea(`could not reach the server`)}w?.id===e&&(w={...w,name:r}),_a=``,$(),z()}}async function ka(e,t){Ea(`Taking ${t} off the air…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));Ea(n.ok?`${t} is off the air.`:r.error??`that did not work`)}catch{Ea(`could not reach the server`)}w?.id===e&&(w=null,F.stop()),_a=``,$()}async function Aa(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{S=e,z();return}n===`✓`||n===`✓`?d(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function ja(e,t=0){let n=Ma();if(n===``)return``;let r=globalThis.location.origin,i=t>1?`&t=${Math.floor(t)}`:``;return`${r}/?url=${encodeURIComponent(n)}&play=${encodeURIComponent(e)}${i}`}function Ma(){if(se!==``)return se;let e=p===`remote`?I.shareLink:``;return/\/admin\//.test(e)?``:e}function Na(e){if(v===``)return;let t=v;if(t===`live`){v=``,e.server.playing?Ca(e.server.nowPlaying):(S=`Nothing is playing on this server right now.`,z());return}if(t.startsWith(`link:`)){v=``,Tn(t.slice(5));return}if(t.startsWith(`golive:`)){v=``,o.linkUrl.value=t.slice(7),Kn().then(()=>Mn());return}if(t.startsWith(`track:`)){v=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&tn(e);return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n)??e.channels.find(e=>e.name===n);r&&(v=``,wa({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Pa(e){let t=document.createElement(`li`);t.className=`onair`;let n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.title;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.detail,n.append(r,i);let a=document.createElement(`span`);a.className=`onair-actions`;let o=document.createElement(`button`);o.type=`button`,o.className=`button`,Wt(o,e.playLabel??`Join party`),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,d(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};return(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Aa(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Aa(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),t.append(n,a),t}let Fa=``;function Ia(e,t){Fa=e;let n=e!==``&&t===e;o.loadHome.hidden=e===``,o.homeNote.hidden=e===``,e!==``&&(o.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,o.loadHome.disabled=!1)}o.loadHome.addEventListener(`click`,()=>{Fa!==``&&(o.loadHome.disabled=!0,V(`Reading this server's files…`),(async()=>{try{let e=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Fa})}),t=await e.json();V(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{V(`could not reach the server`)}finally{o.loadHome.disabled=!1}})())});let La=async e=>{o.goLive.disabled=!0,o.stopLive.disabled=!0,o.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(I.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();o.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{o.shareNote.textContent=`could not reach the server`}finally{o.goLive.disabled=!1,o.stopLive.disabled=!1,await ga()}};o.goLive.addEventListener(`click`,()=>void La(!0)),o.stopLive.addEventListener(`click`,()=>void La(!1));function Ra(e){let t=document.createElement(`b`);return t.textContent=e,t}o.shareCopy.addEventListener(`click`,()=>{o.shareLink.select(),navigator.clipboard?.writeText(o.shareLink.value).then(()=>{o.shareNote.textContent=`Copied. Send it to anybody.`},()=>{o.shareNote.textContent=`Copy it from the box above.`})}),o.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=o.shareTo.value.trim();t!==``&&(async()=>{o.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:Ma()})}),n=await e.json();o.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(o.shareTo.value=``)}catch{o.shareNote.textContent=`could not send that`}})()}),o.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(Pt,o.listenHere.checked?`1`:`0`)}catch{}p===`remote`&&(async()=>{o.listenHere.checked?(await I.send({type:`stop`}),await nn(b.index)):(F.stop(),C=-1),z()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)&&!t?.closest(`input, textarea, select, button, a, [contenteditable], [role=button]`)&&t===o.transport)switch(e.key){case` `:e.preventDefault(),rn();return;case`s`:on();return;case`n`:case`ArrowRight`:an(1);return;case`p`:case`ArrowLeft`:an(-1);return;case`ArrowDown`:e.preventDefault(),tn(Math.min(Kt()-1,L()+1));return;case`ArrowUp`:e.preventDefault(),tn(Math.max(0,L()-1));return}});let za=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),za=e,o.install.hidden=!1}),o.install.addEventListener(`click`,()=>{za?.prompt(),za=null,o.install.hidden=!0});try{let e=localStorage.getItem(Nt);e!==null&&(o.volume.value=String(Math.round(Number(e)*100)),F.volume=Number(e));let t=localStorage.getItem(jt);t&&(o.remoteUrl.value=t),localStorage.getItem(Pt)===`0`&&(o.listenHere.checked=!1)}catch{}(async()=>{if(o.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await De(e)===null)return;let t=await we(e);t&&t.trackCount!==0&&(o.remoteUrl.value=e,p=`remote`,S=``,I.connect(e),z())})(),(()=>{if(It||Dt!==``)return;let e=()=>F.source!==``||F.playing||ke()||w!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{It=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||n.play().catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,n.play().then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),z(),requestAnimationFrame(bn)}Lt(),a(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{m as t};
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function t(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function n(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var r=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function i(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&r.has(e.slice(n+1).toLowerCase())}function a(){let e=document.getElementById(`sr-status`);if(!e)return;let t=[`note`,`account-note`,`remote-state`,`transcript-audio-note`,`notify-note`,`notify-phone-note`,`persona-note`],n=new Map,r,i=``;for(let a of t){let t=document.getElementById(a);t&&(n.set(a,t.textContent?.trim()??``),new MutationObserver(()=>{let o=t.textContent?.trim()??``;n.get(a)!==o&&(n.set(a,o),o&&!t.closest(`[hidden], [data-closed], [data-collapsed]`)&&(i=o,clearTimeout(r),r=setTimeout(()=>{e.textContent!==i&&(e.textContent=i)},200)))}).observe(t,{childList:!0,characterData:!0,subtree:!0}))}}var o=new WeakMap;function s(e,...t){if(!e.contains(document.activeElement)){o.delete(e),e.replaceChildren(...t);return}let n=o.has(e);if(o.set(e,t),n)return;let r=()=>{let t=o.get(e);if(t){if(e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}o.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}function c(e){if(!/\.(?:mp4|m4v|mkv|webm|mov|avi|mp3|m4a|flac|ogg|opus|wav|aac)$/i.test(e))return e;let t=(e.split(/[\\/]/).pop()??e).replace(/\.[^.]+$/,``);return t.replace(/^0\d+[_ .-]+(?:\d+[_ .-]+)?/,``).replace(/_+/g,` `).trim()||t}function l(e){if(/^(?:[\\/]|[A-Za-z]:)/.test(e))return[];let t=e.split(/[\\/]/).filter(Boolean);return t.some(e=>e===`..`)?[]:t.filter(e=>e!==`.`).map(e=>e.replace(/_+/g,` `))}function u(e,t,n=`Live`){let r=e[t];if(!r){let e=c(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${c(r.title)}`:c(r.title),a=l(r.folder??``),o=l(r.group??``).join(` › `),s=[...o?[o]:[],...a],u=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,d=e.map((e,t)=>({one:e,at:t})).filter(({one:e})=>(e.group??``)===(r.group??``)&&(e.folder??``)===(r.folder??``)&&(s.length>0||e.album===r.album));return{title:i,context:u,position:`Playlist · ${d.findIndex(({at:e})=>e===t)+1} of ${d.length}`,fullTitle:u?`${u} › ${i}`:i}}var d=`modulepreload`,f=function(e){return`/`+e},p={},m=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=f(t,n),t=s(t),t in p)return;p[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:d,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},h=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],g=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function ee(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of g)if(t.test(e.mimeType))return n}let t=_(e.src);for(let[e,n]of h)if(e.test(t))return n;return`unknown`}function _(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function te(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function ne(e,t){let n=ee(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function v(e,t){let n=t.capabilities??te(),r=ne({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await m(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-6OPW0QO6.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await m(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-DbjJutt4.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await m(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var re=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),ie=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function ae(e){let t=e.lastIndexOf(`.`);return t>0&&ie.has(e.slice(t+1).toLowerCase())}function oe(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&re.has(e.slice(n+1).toLowerCase())}function se(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ce(e){return e.filter(e=>oe(e.name,e.type)).sort((e,t)=>se(y(e),y(t))).map(e=>({title:n(e.name),artist:``,album:le(y(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0,...ae(e.name)?{kind:`mpegts`}:{}}))}function y(e){return e.webkitRelativePath||e.name}function le(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function ue(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var b=2048;function x(e){if(e.startsWith(`blob:`)||e.startsWith(`data:`))return!0;try{let t=globalThis.location?.origin;return t?new URL(e,t).origin===t:!1}catch{return!1}}function de(e,t){return e||t===`hls`||t===`mpegts`}var fe=class{elements;handlers;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;wired=new WeakSet;active;frequencies=new Uint8Array;analysable=!0;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video]){t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&this.handlers.onError(S(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get needsInteraction(){return this.playBlocked}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(!this.context)try{this.context=new t({sampleRate:48e3})}catch{this.context=new t}if(this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=b,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.analyser.connect(this.output),this.output.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}audioInput(){if(!this.analysable)throw Error(`This source blocks audio access, so its audio cannot be translated here.`);if(this.ensureGraph(this.active),!this.context||!this.analyser)throw Error(`This browser cannot capture player audio.`);return{context:this.context,node:this.analyser}}translatedAudio(e){this.output&&(this.output.gain.value=+!e)}get mediaKey(){return this.active.currentSrc||this.active.src}get loaded(){return!!(this.active.currentSrc||this.active.src)}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:ee({src:e.url})),r=de(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||x(e.url)||(this.handlers.readable?.(e.url)??!1);r.crossOrigin=i?`anonymous`:null,r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await v(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}let a=this.active.currentSrc||this.active.src||e.url;this.analysable=i||a.startsWith(`blob:`)||x(a),t&&await this.play()}async play(){this.analysable&&this.ensureGraph(this.active),this.playBlocked=!1;try{await this.active.play()}catch(e){if(e instanceof Error&&e.name===`NotAllowedError`){this.playBlocked=!0,this.handlers.onBusy?.(!1),this.handlers.onState(!1);return}this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){this.playBlocked=!1,this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function S(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function pe(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function me(e,t){return{...t,tracks:t.tracks??e.tracks}}function he(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function ge(e,t,n=``){let r=`${e===``?``:he(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function _e(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=/^\/api\/channels\/([^/]+)\/?$/.exec(t.pathname),r=/^\/api\/media\/(\d+)\/?$/.exec(t.pathname),i=/^\/api\/live\/?$/.test(t.pathname);if(!n&&!r&&!i)return null;let a=t.searchParams.get(`k`)??``,o=a?`${t.origin}/view/${a}`:t.origin,s=`live`;if(r&&(s=`track:${r[1]}`),n)try{s=`channel:${decodeURIComponent(n[1]??``)}`}catch{s=`channel:${n[1]??``}`}return{view:o,what:s}}function ve(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:he(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var C=null;function w(e){if(!e&&C!==null)return C;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(C=n),n}catch{return!1}}function ye(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return ge(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function be(e){if(typeof e!=`object`||!e)return null;let t=e,n=pe(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}function xe(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var Se=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return xe(this.base,e)}url(e){let t=ge(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=ve(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(ge(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=be(Ce(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(ge(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=be(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=w()){return ye(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function Ce(e){try{return JSON.parse(e)}catch{return null}}async function we(e,t,n=``){try{let r=await fetch(ge(e,`/api/state`,n),{signal:t});return r.ok?be(await r.json()):null}catch{return null}}function Te(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function Ee(e,t=``,n){let r;try{r=await fetch(ge(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function De(e,t,n=``){try{let r=await fetch(ge(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function Oe(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var ke=.14,T=.02;function Ae(e,t){let n=[];for(let r=0;r<=e;r++){let i=r/e,a=Math.round(1*(t/1)**i),o=n[n.length-1];n.push(o===void 0?a:Math.max(a,o+1))}return n}function je(e,t){let n=[];for(let r=0;r+1<t.length;r++){let i=Math.min(t[r],e.length),a=Math.min(Math.max(t[r+1],i+1),e.length),o=0,s=0;for(let t=i;t<a;t++)o+=e[t],s++;n.push(s===0?0:o/s/255)}return n}function Me(e,t,n=ke){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Ne(e,t,n=T){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function Pe(e,t,n,r,i){let{width:a,height:o}=t;if(a<=0||o<=0||n.length===0)return;e.clearRect(0,0,a,o);let s=a/n.length,c=Math.max(1,s*.72),l=Math.max(2,o*.012);e.fillStyle=i.bar,n.forEach((t,n)=>{let r=Math.max(1,t*(o-l*2));e.fillRect(n*s+(s-c)/2,o-r,c,r)}),e.fillStyle=i.peak,r.forEach((t,n)=>{let r=o-Math.max(1,t*(o-l*2))-l*2;e.fillRect(n*s+(s-c)/2,Math.max(0,r),c,l)})}function E(e,t){return{name:String(e?.name??e?.displayName??e?.abbreviation??``),score:typeof e?.score==`number`?e.score:typeof t==`number`?t:null,logo:typeof e?.logoUrl==`string`&&/^https?:\/\//.test(e.logoUrl)?e.logoUrl:``}}function Fe(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function D(e,t={}){if(!e)return``;let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t.now??new Date,i=t.timeZone?{timeZone:t.timeZone}:{},a=n.toLocaleDateString(t.locale,i)===r.toLocaleDateString(t.locale,i);return n.toLocaleString(t.locale,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function Ie(e,t={}){let n=e.data,r=E(n.away,n.awayScore),i=E(n.home,n.homeScore),a=Fe(e),o=typeof n.statusDetail==`string`?n.statusDetail.trim():``,s;if(a===`in`)s=o?`LIVE · ${o}`:`LIVE`;else if(a===`post`)s=`FINAL`;else{let n=D(e.published_at,t);s=n?`Kicks off ${n}`:o||`Upcoming`}let c=[],l=n.league,u=String(l?.abbreviation??l?.name??``);u&&c.push(u),typeof n.broadcast==`string`&&n.broadcast.trim()&&c.push(n.broadcast.trim());let d=a!==`pre`,f=e=>d&&e.score!==null?` ${e.score}`:``;return{away:r,home:i,state:a,status:s,chips:c,text:`${r.name}${f(r)} – ${i.name}${f(i)}`}}var Le=`nixamp.tv`,Re=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function ze(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?Be(r):/\bSilk\b/.test(e)&&n===0?!0:Re.test(e):Be(i)}function Be(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Ve(e){return e?12:100}function He(e,t,n){let r=Math.max(1,Math.ceil(e/n)),i=Math.min(Math.max(0,t),r-1),a=i*n;return{page:i,from:a,to:Math.min(e,a+n),pages:r}}var Ue=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,O=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,k=/\.m3u8(\?.*)?$/i,We=/\.(m3u|pls)(\?.*)?$/i;function Ge(e){try{let t=new URL(e);return O.test(t.pathname+t.search)}catch{return!1}}function Ke(e){try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}}),r=(n.pop()??``).replace(/\.(m3u|pls)$/i,``);return(/^(playlist|index|list|all|episodes|feed)?$/i.test(r)?n.pop()??``:r).replace(/[-_]+/g,` `).trim()||t.hostname}catch{return`Playlist`}}function qe(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||Ke(t),r=[],i=(e,n)=>{if(r.length>=1e3)return;let i;try{i=new URL(e.trim(),t)}catch{return}if(i.protocol!==`https:`&&i.protocol!==`http:`)return;let a=i.pathname+i.search;if(!Ue.test(a)&&!O.test(a))return;let o=decodeURIComponent(i.pathname.split(`/`).filter(Boolean).pop()??i.hostname);r.push({url:i.toString(),title:n||o})},a=!1;try{a=/\.pls$/i.test(new URL(t).pathname)}catch{a=!1}if(a){let t=new Map,a=new Map;for(let n of e.split(/\r?\n/)){let e=/^(File|Title)(\d+)\s*=\s*(.*)$/i.exec(n.trim());e&&(/^file$/i.test(e[1]??``)?t:a).set(e[2]??``,e[3]??``)}for(let[e,n]of[...t.entries()].sort((e,t)=>Number(e[0])-Number(t[0])))i(n,(a.get(e)??``).trim());return{title:n,entries:r}}let o=``;for(let t of e.split(/\r?\n/)){let e=t.trim();if(e!==``){if(e.startsWith(`#`)){let t=/^#EXTINF:\s*-?[\d.]+\s*(?:,(.*))?$/i.exec(e);t&&(o=(t[1]??``).trim());continue}i(e,o),o=``}}return{title:n,entries:r}}function Je(e){let t=e.hostname.replace(/^www\.|^m\.|^music\./,``),n=e=>e&&/^[A-Za-z0-9_-]{11}$/.test(e)?e:``;if(t===`youtu.be`)return n(e.pathname.slice(1).split(`/`)[0]??null);if(t!==`youtube.com`&&t!==`youtube-nocookie.com`)return``;if(e.pathname===`/watch`)return n(e.searchParams.get(`v`));let r=/^\/(?:shorts|live|embed|v)\/([^/?]+)/.exec(e.pathname);return r?n(r[1]??null):``}function Ye(e,t=!1){let n;try{n=new URL(e.trim())}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;let r=Je(n);if(r){let e=n.searchParams.get(`t`);return{kind:`embed`,site:`youtube`,src:`https://www.youtube-nocookie.com/embed/${r}?autoplay=1&playsinline=1&rel=0${e&&/^\d+$/.test(e)?`&start=${e}`:``}`,label:`YouTube · ${r}`}}let i=n.hostname.replace(/^www\.|^player\./,``),a=i===`vimeo.com`?/^\/(?:video\/)?(\d+)/.exec(n.pathname)?.[1]:void 0;if(a)return{kind:`embed`,site:`vimeo`,src:`https://player.vimeo.com/video/${a}?autoplay=1&playsinline=1`,label:`Vimeo · ${a}`};if(i===`soundcloud.com`&&n.pathname.split(`/`).filter(Boolean).length>=2)return{kind:`embed`,site:`soundcloud`,src:`https://w.soundcloud.com/player/?url=${encodeURIComponent(n.toString())}&auto_play=true&visual=false`,label:`SoundCloud · ${n.pathname.split(`/`).filter(Boolean).slice(0,2).join(` / `)}`};let o=n.pathname+n.search,s=decodeURIComponent(n.pathname.split(`/`).filter(Boolean).pop()??n.hostname);return We.test(o)?{kind:`list`,url:n.toString(),label:Ke(n.toString())}:Ue.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:O.test(o)||k.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var Xe=`nixamp.panels`;function Ze(){return{order:[],placement:{},collapsed:[],closed:[]}}var Qe=/^[a-z][a-z0-9-]{0,63}$/,$e=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function et(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&Qe.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function tt(e){if(!e)return Ze();let t;try{t=JSON.parse(e)}catch{return Ze()}if(!t||typeof t!=`object`||Array.isArray(t))return Ze();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))Qe.test(e)&&typeof t==`string`&&$e.test(t)&&(r[e]=t);return{order:et(n.order),placement:r,collapsed:et(n.collapsed),closed:et(n.closed)}}function nt(e){return JSON.stringify(e)}function rt(e,t){let n=new Set(e),r=t.filter(e=>n.has(e)),i=new Set(r);return e.forEach((t,n)=>{if(i.has(t))return;let a=0;for(let t=n-1;t>=0;t--){let n=r.indexOf(e[t]);if(n>=0){a=n+1;break}}r.splice(a,0,t),i.add(t)}),r}function it(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}var at=16e3,ot=3e4;function st(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function ct(e,t=at){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function lt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var ut=`nixamp.captions`,dt=`nixamp.captions.native-v2.language`,ft=[{code:``,label:`Original (auto-detect)`},{code:`en`,label:`English`},{code:`de`,label:`Deutsch`},{code:`sv`,label:`Svenska`},{code:`es`,label:`Español`},{code:`fr`,label:`Français`},{code:`it`,label:`Italiano`},{code:`nl`,label:`Nederlands`},{code:`da`,label:`Dansk`},{code:`fi`,label:`Suomi`},{code:`ru`,label:`Русский`},{code:`uk`,label:`Українська`},{code:`cs`,label:`Čeština`},{code:`hu`,label:`Magyar`},{code:`zh`,label:`中文`},{code:`ar`,label:`العربية`},{code:`hi`,label:`हिन्दी`},{code:`vi`,label:`Tiếng Việt`},{code:`id`,label:`Bahasa Indonesia`}];function pt(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return ft.some(e=>e.code===t)?t:``}catch{return``}}function mt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function ht(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function gt(e,t,n){let r=[],i=[];for(let a of e)(a.at<=t-n?r:i).push(a);return r.sort((e,t)=>e.at-t.at),{ready:r,still:i}}function _t(e,t,n,r=1500){let i=t-n;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.at<=i&&i<=n.until+r)return n;if(n.until+r<i)break}return null}function vt(e){try{return e(ut)!==`off`}catch{return!0}}function yt(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var bt=12e3,xt=class{options;context=null;gain=null;enabled=!1;generation=0;running=null;controller=null;next=[];sources=new Set;scheduledUntil=0;seen=new Set;constructor(e){this.options=e}async enable(){this.enabled=!0;try{this.context??=this.options.audioContext?.()??new AudioContext,this.gain||(this.gain=this.context.createGain(),this.gain.connect(this.context.destination)),await this.context.resume(),this.enabled&&this.options.status(`Waiting for the next translated line…`)}catch{this.fail(`Audio could not start. Enable translated audio again to retry.`)}}disable(){this.enabled=!1,this.reset()}reset(){this.generation++,this.controller?.abort(),this.controller=null,this.next=[],this.running=null,this.seen.clear();for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.scheduledUntil=0,this.options.active(!1)}setVolume(){this.gain&&(this.gain.gain.value=Math.max(0,Math.min(1,this.options.volume())))}push(e,t,n){this.pushBatch([{line:e,url:t,lag:n}])}pushBatch(e){if(!this.enabled||!this.options.playing())return;let t=e.slice(0,12).filter(({line:e,lag:t})=>{let n=`${e.channel}|${e.at}|${e.language}|${e.speaker??``}`;return this.seen.has(n)||this.stale(e,t)?!1:(this.seen.add(n),this.seen.size>200&&this.seen.delete(this.seen.values().next().value),!0)});t.length&&(this.next=t,this.running===null&&this.run(this.generation))}stale(e,t){return(this.options.now?.()??Date.now())-t-e.until>bt}fail(e){this.disable(),this.options.status(`${e} Original audio restored.`),this.options.failed()}async run(e){this.running=e;try{for(;this.next.length&&this.enabled&&e===this.generation;){let t=this.next.shift();if(this.stale(t.line,t.lag)||!this.options.playing())continue;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),12e3);try{let r=new Headers(t.init?.headers);if(new Headers(await this.options.authorization?.(n.signal,t.line)).forEach((e,t)=>r.set(t,e)),e!==this.generation)return;let i=await(this.options.fetcher??fetch)(t.url,{...t.init,signal:n.signal,headers:r});if(e!==this.generation){await i.body?.cancel();return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error||`Translated audio is unavailable.`)}if(!i.body||!i.headers.get(`content-type`)?.startsWith(`audio/pcm`))throw Error(`The server returned no voice audio.`);let a=i.body.getReader(),o=new Uint8Array,s=0;try{for(;;){let{done:t,value:n}=await a.read();if(e!==this.generation){await a.cancel();return}if(t)break;let r=new Uint8Array(o.length+n.length);r.set(o),r.set(n,o.length);let i=r.length-r.length%2;o=r.slice(i),i&&(this.schedule(r.subarray(0,i)),s+=i)}}finally{a.releaseLock()}if(!s||o.length)throw Error(`The voice audio was interrupted.`)}finally{clearTimeout(r)}for(;e===this.generation&&this.context&&this.scheduledUntil-this.context.currentTime>.15;)if(await new Promise(e=>setTimeout(e,50)),!this.options.playing()){this.reset();return}}}catch(t){e===this.generation&&this.fail(t instanceof Error?t.message:`Translated audio stopped.`)}finally{this.running===e&&(this.running=null)}}schedule(e){let t=this.context;if(!t||!this.gain||!this.enabled)return;if(t.state!==`running`)throw Error(`Audio playback was suspended.`);let n=e.length/2,r=Math.max(t.currentTime+.03,this.scheduledUntil);if(r-t.currentTime+n/16e3>10)throw Error(`Translated audio fell too far behind.`);let i=t.createBuffer(1,n,16e3),a=i.getChannelData(0),o=new DataView(e.buffer,e.byteOffset,e.length);for(let e=0;e<n;e++)a[e]=o.getInt16(e*2,!0)/32768;let s=t.createBufferSource();s.buffer=i,s.connect(this.gain),this.setVolume(),this.sources.add(s),s.onended=()=>{this.sources.delete(s),s.disconnect()},s.start(r),this.scheduledUntil=r+i.duration,this.options.active(!0),this.options.status(`Playing translated audio · a few seconds behind the video`)}},St=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,A=new WeakMap,Ct=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t){this.stop();let n=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(A.has(e)||A.set(e,e.audioWorklet.addModule(St).catch(t=>{throw A.delete(e),t})),await A.get(e),n!==this.generation)return;let r=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=r;let i=e.createGain();i.gain.value=0,t.connect(r),r.connect(i),i.connect(e.destination);let a=new Float32Array(e.sampleRate*5),o=0,s=new Float32Array,c=Date.now();r.port.onmessage=t=>{if(n!==this.generation)return;let r=0,i=t.data;for(;r<i.length;){let t=Math.min(a.length-o,i.length-r);if(a.set(i.subarray(r,r+t),o),o+=t,r+=t,o!==a.length)continue;let n=new Float32Array(8e4),l=e.sampleRate/16e3;for(let e=0;e<n.length;e++){let t=Math.floor(e*l),r=Math.max(t+1,Math.floor((e+1)*l)),i=0;for(let e=t;e<r;e++)i+=a[e]??0;n[e]=i/(r-t)}c+=5e3,Math.abs(Date.now()-c)>1500&&(c=Date.now(),s=new Float32Array);let u=new Float32Array(s.length+n.length);u.set(s),u.set(n,s.length),this.take({samples:u,at:c-u.length/16,until:c,freshAt:c-5e3}),s=u.slice(-16e4),o=0}},this.disconnect=()=>{r.port.onmessage=null,r.port.close(),t.disconnect(r),r.disconnect(),i.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},wt=class e{failed;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;static loaded=new WeakMap;constructor(e){this.failed=e}async start(t,n){this.stop();let r=this.generation;try{if(t.sampleRate!==48e3)throw Error(`Unsupported background sample rate`);let i=e.loaded.get(t);if(i||(i=t.audioWorklet.addModule(new URL(`data:text/javascript;base64,LyogQXVkaW8gdHJhbnNwb3J0IG9ubHk6IG5ldXJhbCBpbmZlcmVuY2UgcnVucyBpbiBhIGRlZGljYXRlZCB3b3JrZXIuIE5ldmVyCiAqIGJ5cGFzcyB0byB0aGUgb3JpZ2luYWwgaW5wdXQgb24gYW4gZXJyb3I6IHRoYXQgd291bGQgcmVzdG9yZSBmb3JlaWduIHNwZWVjaC4gKi8KY2xhc3MgQmFja2dyb3VuZFRyYW5zcG9ydCBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7CiAgY29uc3RydWN0b3IoKSB7CiAgICBzdXBlcigpOwogICAgdGhpcy5jaGFubmVsID0gbnVsbDsgdGhpcy5hbGl2ZSA9IHRydWU7IHRoaXMucmVhZHkgPSBmYWxzZTsKICAgIHRoaXMuaW5wdXRzID0gW25ldyBGbG9hdDMyQXJyYXkoNTEyKSwgbmV3IEZsb2F0MzJBcnJheSg1MTIpXTsKICAgIHRoaXMud3JpdHRlbiA9IDA7IHRoaXMuaWQgPSAwOyB0aGlzLmluZmxpZ2h0ID0gMDsKICAgIHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnJlYWQgPSAwOwogICAgdGhpcy5wb3J0Lm9ubWVzc2FnZSA9IGV2ZW50ID0+IHsKICAgICAgaWYgKGV2ZW50LmRhdGEuc3RvcCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMuY2hhbm5lbD8uY2xvc2UoKTsgcmV0dXJuOyB9CiAgICAgIHRoaXMuY2hhbm5lbCA9IGV2ZW50LmRhdGEucG9ydDsKICAgICAgdGhpcy5jaGFubmVsLm9ubWVzc2FnZSA9IHJlc3VsdCA9PiB7CiAgICAgICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm47CiAgICAgICAgdGhpcy5pbmZsaWdodC0tOwogICAgICAgIGlmICh0aGlzLnF1ZXVlLmxlbmd0aCA+PSA0KSB7IHRoaXMuZmFpbCgpOyByZXR1cm47IH0KICAgICAgICB0aGlzLnF1ZXVlLnB1c2gocmVzdWx0LmRhdGEuY2hhbm5lbHMpOwogICAgICAgIGlmICh0aGlzLnF1ZXVlLmxlbmd0aCA+PSAyKSB0aGlzLnJlYWR5ID0gdHJ1ZTsKICAgICAgfTsKICAgICAgdGhpcy5jaGFubmVsLnN0YXJ0KCk7CiAgICB9OwogIH0KICBmYWlsKCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyBlcnJvcjogdHJ1ZSB9KTsgfQogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzKSB7CiAgICBjb25zdCBvdXQgPSBvdXRwdXRzWzBdOwogICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm4gZmFsc2U7CiAgICBjb25zdCBpbnB1dCA9IGlucHV0c1swXTsKICAgIGlmICghaW5wdXQ/LlswXSB8fCAhdGhpcy5jaGFubmVsKSByZXR1cm4gdHJ1ZTsKICAgIGNvbnN0IGNvdW50ID0gaW5wdXRbMF0ubGVuZ3RoOwogICAgZm9yIChsZXQgY2hhbm5lbCA9IDA7IGNoYW5uZWwgPCAyOyBjaGFubmVsKyspIHRoaXMuaW5wdXRzW2NoYW5uZWxdLnNldChpbnB1dFtjaGFubmVsXSA/PyBpbnB1dFswXSwgdGhpcy53cml0dGVuKTsKICAgIHRoaXMud3JpdHRlbiArPSBjb3VudDsKICAgIGlmICh0aGlzLndyaXR0ZW4gPT09IDUxMikgewogICAgICBpZiAodGhpcy5pbmZsaWdodCA+PSA0KSB7IHRoaXMuZmFpbCgpOyByZXR1cm4gZmFsc2U7IH0KICAgICAgY29uc3QgY2hhbm5lbHMgPSB0aGlzLmlucHV0czsgdGhpcy5pbmZsaWdodCsrOwogICAgICB0aGlzLmNoYW5uZWwucG9zdE1lc3NhZ2UoeyBpZDogdGhpcy5pZCsrLCBjaGFubmVscyB9LCBjaGFubmVscy5tYXAob25lID0+IG9uZS5idWZmZXIpKTsKICAgICAgdGhpcy5pbnB1dHMgPSBbbmV3IEZsb2F0MzJBcnJheSg1MTIpLCBuZXcgRmxvYXQzMkFycmF5KDUxMildOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgaWYgKCF0aGlzLnJlYWR5KSByZXR1cm4gdHJ1ZTsKICAgIGlmICghdGhpcy5vdXRwdXQgfHwgdGhpcy5yZWFkID09PSA1MTIpIHsgdGhpcy5vdXRwdXQgPSB0aGlzLnF1ZXVlLnNoaWZ0KCkgPz8gbnVsbDsgdGhpcy5yZWFkID0gMDsgfQogICAgaWYgKCF0aGlzLm91dHB1dCkgeyB0aGlzLnJlYWR5ID0gZmFsc2U7IHJldHVybiB0cnVlOyB9CiAgICBmb3IgKGxldCBjaGFubmVsID0gMDsgY2hhbm5lbCA8IG91dC5sZW5ndGg7IGNoYW5uZWwrKykgb3V0W2NoYW5uZWxdLnNldCh0aGlzLm91dHB1dFtjaGFubmVsXS5zdWJhcnJheSh0aGlzLnJlYWQsIHRoaXMucmVhZCArIGNvdW50KSk7CiAgICB0aGlzLnJlYWQgKz0gY291bnQ7CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1iYWNrZ3JvdW5kIiwgQmFja2dyb3VuZFRyYW5zcG9ydCk7Cg==`,``+import.meta.url)),e.loaded.set(t,i),i.catch(()=>e.loaded.delete(t))),await i,r!==this.generation)return!1;let a=new Worker(new URL(`/assets/background.worker-D9ejvk_o.js`,``+import.meta.url),{type:`module`});this.worker=a;let o=new MessageChannel;if(this.pendingPort=o.port1,await new Promise((e,t)=>{let n=!1,r=r=>{n||(n=!0,clearTimeout(i),this.cancelStart=null,r?t(r):e())},i=setTimeout(()=>r(Error(`Background model did not load`)),8e3);this.cancelStart=()=>r(Error(`Background loading cancelled`)),a.onerror=()=>r(Error(`Background worker failed`)),a.onmessage=e=>r(e.data.ready?void 0:Error(`Background model unavailable`)),a.postMessage({port:o.port2},[o.port2])}),r!==this.generation)return!1;let s=()=>{r===this.generation&&(this.stop(),this.failed())};a.onerror=s,a.onmessage=e=>{e.data.error&&s()};let c=new AudioWorkletNode(t,`nixamp-background`,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});this.node=c,c.onprocessorerror=s,c.port.onmessage=e=>{e.data.error&&s()},c.port.postMessage({port:o.port1},[o.port1]),this.pendingPort=null;let l=t.createGain();return this.gain=l,l.gain.value=+!!this.on,this.input=n,c.connect(l),l.connect(t.destination),n.connect(c),!0}catch{r===this.generation&&(this.stop(),this.failed())}return!1}active(e){this.on=e,this.gain&&(this.gain.gain.value=+!!e)}stop(){if(this.generation++,this.on=!1,this.cancelStart?.(),this.cancelStart=null,this.pendingPort?.close(),this.pendingPort=null,this.node){this.node.port.postMessage({stop:!0});try{this.input?.disconnect(this.node)}catch{}this.node.disconnect(),this.node.port.close()}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},Tt=class{random;previous=[];sequence=0;speakers=new Map;constructor(e=Math.random){this.random=e}reset(){this.previous=[],this.sequence=0,this.speakers.clear()}reconcile(e,t,n){let r=new Map,i=new Set,a=[],o=new Map;for(let n of e)for(let e of this.previous){let r=Math.min(t+n.end*1e3,e.end)-Math.max(t+n.start*1e3,e.start);if(r>120){let t=`${n.speaker}|${e.speaker}`;o.set(t,(o.get(t)??0)+r)}}for(let[e,t]of o){let[n,r]=e.split(`|`);a.push({local:n,global:r,overlap:t})}for(let e of a.sort((e,t)=>t.overlap-e.overlap)){let t=this.speakers.get(e.global);t&&!r.has(e.local)&&!i.has(e.global)&&(r.set(e.local,t),i.add(e.global))}for(let t of e){let e=r.get(t.speaker);if(!e){let i=new Set([...this.speakers.values()].map(e=>e.voice)),a=n.filter(e=>!i.has(e.id)),o=a.length?a:n,s=o[Math.floor(this.random()*o.length)];e={id:`speaker-${++this.sequence}`,profile:t.profile,voice:s?.id??`auto`},this.speakers.set(e.id,e),r.set(t.speaker,e)}}this.previous=e.map(e=>({start:t+e.start*1e3,end:t+e.end*1e3,speaker:r.get(e.speaker).id}));let s=new Set(this.previous.map(e=>e.speaker));for(let e of this.speakers.keys())this.speakers.size>64&&!s.has(e)&&this.speakers.delete(e);return r}},Et=class{options;tracker=new Tt;generation=0;pending=null;running=null;controller=null;constructor(e){this.options=e}reset(){this.generation++,this.controller?.abort(),this.pending=null,this.running=null,this.tracker.reset()}push(e){this.pending=e,this.running===null&&this.run(this.generation)}async json(e,t,n){let r=await(this.options.fetcher??fetch)(e,{...t,signal:n}),i=await r.json();if(!r.ok)throw Error(i.error||`Audio translation is unavailable.`);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;if(this.pending=null,Date.now()-t.until>12e3)continue;let n=new AbortController;this.controller=n;let r=AbortSignal.any([n.signal,AbortSignal.timeout(12e3)]),i=this.options.speakers(),a=this.options.language(),o=await this.json(i?`/api/v1/speech/speakers`:`/api/v1/speech/transcribe?live=1`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Uint8Array(ct(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices());for(let n of o.turns??[]){let r=n.words.filter(e=>t.at+(e.start+e.end)*500>=t.freshAt);if(!r.length)continue;let i=e.get(n.speaker);c.push({channel:this.options.channel(),at:t.at+r[0].start*1e3,until:t.at+r.at(-1).end*1e3,text:r.map(e=>e.text).join(` `).trim(),language:s,speaker:i.id,voiceProfile:n.profile})}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(c.length){if(a&&s!==a){if(!s)throw Error(`The audio language could not be detected. Waiting for clearer speech.`);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:c.map(e=>e.text),from:s,to:a})},r);c=c.map((t,n)=>({...t,original:t.text,sourceLanguage:s,language:a,text:e.texts[n]??``}))}if(e!==this.generation)return;if(Date.now()-t.until>12e3)throw Error(`Translation fell behind. Try again after the language model has warmed up.`);this.options.lines(c.filter(e=>e.text.trim()!==``&&e.text.length<=600)),this.options.status(a?`${s} → ${a} · live translation`:`Original audio language: ${s||`detecting…`}`)}}}catch(t){e===this.generation&&(this.reset(),this.options.failed(),this.options.status(t instanceof Error?t.message:`Live translation stopped.`))}finally{this.running===e&&(this.running=null)}}},Dt=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,Ot=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,kt=/\s+(?:vs\.?|v\.?|at|@)\s+/i,j=/^(?:the|a|an|live|tonight|recorded|filmed|concert|home|dinner|breakfast|lunch|midnight|night|one night|death|murder|meet me|panic|sunset|sunrise)\b/i;function M(e){let t=e.replace(Ot,``).replace(Ot,``).trim().split(kt);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!j.test(t)})}function At(e){let t=String(e??``).trim();return t===``?!1:M(t.replace(Dt,``))||M(t)}var jt=`nixamp.remote`,Mt=`nixamp.defaultServer`,Nt=`nixamp.volume`,Pt=`nixamp.listenHere`,Ft=1e4,It=!1;function N(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function Lt(){let n=null;try{n=localStorage.getItem(Le)}catch{}let r=ze(navigator.userAgent,location.search,navigator.maxTouchPoints,n);if(document.body.classList.toggle(`tv`,r),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Le,r?`1`:`0`)}catch{}let i=document.getElementById(`tv-toggle`);i&&(i.textContent=r?`TV mode: on`:`TV mode`,i.title=r?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,i.addEventListener(`click`,()=>{try{localStorage.setItem(Le,r?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let a=Ve(r),o={status:N(`status`),source:N(`source`),install:N(`install`),video:N(`video`),audio:N(`audio`),title:N(`title-line`),album:N(`album-line`),meta:N(`meta-line`),metaBlurb:N(`meta-blurb`),liveLine:N(`live-line`),downloadNow:N(`download-now`),wayInHere:N(`way-in-here`),embed:N(`embed`),embedFrame:N(`embed-frame`),linkForm:N(`link-form`),linkUrl:N(`link-url`),linkServer:N(`link-server`),linkGoLive:N(`link-go-live`),goLiveNow:N(`go-live-now`),elapsed:N(`elapsed`),total:N(`total`),seek:N(`seek`),fullscreen:N(`fullscreen`),copyNow:N(`copy-now`),canvas:N(`spectrum`),glyphs:N(`glyphs`),levels:N(`levels`),playlist:N(`playlist`),playlistPager:N(`playlist-pager`),crumbs:N(`crumbs`),filter:N(`filter`),playlistTitle:N(`playlist-panel`),note:N(`note`),linkNote:N(`link-note`),logList:N(`log-list`),files:N(`files`),folder:N(`folder`),remoteUrl:N(`remote-url`),remoteForm:N(`remote-form`),remoteState:N(`remote-state`),disconnect:N(`disconnect`),browse:N(`browse`),panelsToggle:N(`panels-toggle`),panelsPanel:N(`panels-panel`),panelsList:N(`panels-list`),panelsReset:N(`panels-reset`),accountForm:N(`account-form`),accountEmail:N(`account-email`),accountPassword:N(`account-password`),accountSubmit:N(`account-submit`),accountToggle:N(`account-toggle`),accountProviders:N(`account-providers`),accountPanel:N(`account-panel`),accountElsewhere:N(`account-elsewhere`),welcome:N(`welcome`),welcomeCreate:N(`welcome-create`),welcomeBrowse:N(`welcome-browse`),welcomeHide:N(`welcome-hide`),accountSignOut:N(`account-signout`),accountNote:N(`account-note`),personaForm:N(`persona-form`),personaHandle:N(`persona-handle`),personaVoice:N(`persona-voice`),personaProfile:N(`persona-profile`),personaNote:N(`persona-note`),adminPanel:N(`admin-panel`),adminNote:N(`admin-note`),adminSaid:N(`admin-said`),adminConnections:N(`admin-connections`),publishPanel:N(`publish-panel`),publishNote:N(`publish-note`),publishList:N(`publish-list`),adminRestream:N(`admin-restream`),adminReplace:N(`admin-replace`),adminSource:N(`admin-source`),adminName:N(`admin-name`),adminAdd:N(`admin-add`),homeNote:N(`home-note`),loadHome:N(`load-home`),directory:N(`directory`),recentNote:N(`recent-note`),recentList:N(`recent-list`),followingNote:N(`following-note`),followingList:N(`following-list`),serversPanel:N(`servers-panel`),serversNote:N(`servers-note`),serversList:N(`servers-list`),favoritesPanel:N(`favorites-panel`),favoritesNote:N(`favorites-note`),favoritesList:N(`favorites-list`),favHere:N(`fav-here`),partiesPanel:N(`parties-panel`),partiesNote:N(`parties-note`),partiesList:N(`parties-list`),partyForm:N(`party-form`),partyCode:N(`party-code`),partyJoin:N(`party-join`),connectionsNote:N(`connections-note`),connectionsList:N(`connections-list`),catalogsPanel:N(`catalogs-panel`),catalogsNote:N(`catalogs-note`),catalogsForm:N(`catalogs-form`),catalogSource:N(`catalog-source`),catalogName:N(`catalog-name`),catalogsList:N(`catalogs-list`),catalogsCrumbs:N(`catalogs-crumbs`),catalogsFilter:N(`catalogs-filter`),catalogsEntries:N(`catalogs-entries`),notifyPanel:N(`notify-panel`),notifyNote:N(`notify-note`),notifyWeb:N(`notify-web`),notifyEmail:N(`notify-email`),notifySms:N(`notify-sms`),notifyPhone:N(`notify-phone`),notifyPhoneForm:N(`notify-phone-form`),notifyPhoneNote:N(`notify-phone-note`),directoryNote:N(`directory-note`),directoryList:N(`directory-list`),onairPanel:N(`onair-panel`),onairNote:N(`onair-note`),onairList:N(`onair-list`),sharePanel:N(`share-panel`),trollboxPanel:N(`trollbox-panel`),trollboxNote:N(`trollbox-note`),trollboxList:N(`trollbox-list`),trollboxForm:N(`trollbox-form`),trollboxInput:N(`trollbox-input`),trollboxMic:N(`trollbox-mic`),trollboxEdit:N(`trollbox-edit`),trollboxEditLabel:N(`trollbox-edit-label`),transcriptPanel:N(`transcript-panel`),transcriptNote:N(`transcript-note`),transcriptOn:N(`transcript-on`),transcriptLanguage:N(`transcript-language`),transcriptAudio:N(`transcript-audio`),transcriptVoiceSettings:N(`transcript-voice-settings`),transcriptBackground:N(`transcript-background`),transcriptAudioNote:N(`transcript-audio-note`),transcriptSpeakers:N(`transcript-speakers`),transcriptList:N(`transcript-list`),subtitle:N(`subtitle`),shareNote:N(`share-note`),shareLink:N(`share-link`),shareCopy:N(`share-copy`),sharePhone:N(`share-phone`),shareSend:N(`share-send`),liveControls:N(`live-controls`),goLive:N(`go-live`),stopLive:N(`stop-live`),shareTo:N(`share-to`),listenOnly:N(`listen-only`),listenHere:N(`listen-here`),volume:N(`volume`),prev:N(`prev`),playPause:N(`play-pause`),transport:N(`transport`),stop:N(`stop`),next:N(`next`),shareNow:N(`share-now`)},l={party:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 21 4-12 8 8Z"/><path d="m7 9 8 8M12 7l1-3M16 10l4-1M16 5l2-2M20 14l1 1M8 4l-1-1"/><circle cx="21" cy="4" r=".5" fill="currentColor"/></svg>`,rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`},d=(e,t)=>{e.innerHTML=l[t]},f=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,p=`local`,m=``,h=[],g=``,ee=!0,_=``;function te(e){try{return new URL(e).origin}catch{return e}}let ne=!1,v=``,re=0,ie=new Map,ae=e=>ie.get(H(e))??null;function oe(e,t){let n=n=>{ne=n,v=``,o.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),o.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,d(r,`eye`),r.title=`Viewer: browse and watch. Changes nothing on the server.`,r.setAttribute(`aria-label`,`View ${e.name}`),r.addEventListener(`click`,()=>n(!0));let i=document.createElement(`button`);return i.type=`button`,i.className=`icon way-in`,d(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:G?`Admin: you do not administer this server.`:`Admin: sign in as this server's owner to administer it.`,i.setAttribute(`aria-label`,`Administer ${e.name}`),i.addEventListener(`click`,()=>n(!1)),[r,i]}let se=``,y=[],le=0,b=pe(),x=`idle`,de=``,S=`Pick files, or connect to a nixamp running somewhere else.`,he=!1,C=-1,w=null;function ye(e){return e?/^https?:\/\//i.test(e)?e:I.url(e):``}let be=0,xe=0,Ce=!1,ke=()=>!F.needsInteraction&&(xe>0||Ce);async function T(e){xe+=1,z();try{return await e()}finally{--xe,z()}}let E=null,D=null,Re=``,Be=null,Ue=``,O=null,k=null,We=0;function Ke(){o.embed.hidden||(o.embedFrame.src=`about:blank`),o.embed.hidden=!0}let Je=null,Qe=``,$e=null;function et(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Qe=i,$e&&clearTimeout($e),$e=null,!r){if(Je?.key===i)return;Je=null}if(p!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(I.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Qe!==i)return;Je={key:i,match:r.match??null},z();let a=Je.match;a?.kind===`fixture`&&Fe(a)!==`post`&&($e=setTimeout(()=>{$e=null,!(Qe!==i||F.source===``&&!w)&&et(e,t,n,!0)},6e4))}).catch(()=>void 0)}let bt=!1,St=``,A=``,Tt=null,Dt=``,Ot=``,kt=``,j=Array(24).fill(0),M=Array(24).fill(0),Lt=[],P=()=>p===`remote`&&!o.listenHere.checked,Rt=()=>p===`remote`&&!o.adminPanel.hidden,zt=!1,Bt=()=>Rt()||p===`remote`&&zt;function Vt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:o.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function Ht(){if(p!==`remote`||O)return null;if(E?.catalog&&E.entry)return{kind:`entry`,catalog:E.catalog,entry:E.entry};if(w)return{kind:`channel`,id:w.id,name:w.name};let e=b.tracks[L()];return e&&(F.source!==``||P())?{kind:`track`,index:L(),name:t(e)}:null}async function Ut(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;S=`Putting ${n} on the air…`,z();try{let r=``,i=``,a=!0;{let t=e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(I.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){S=s.error??`${n} would not go on the air.`,z();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(Rt()&&(bt?await fetch(I.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await La(!0)),await ga(),$(),i!==``&&w?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await wa({id:i,name:n,video:a},!0,t)}let o=ja(r),s=St?` Call ${A||`the line`} and key ${St} to talk about it.`:``;o===``?S=`${n} is on the air and you are watching it.${s}`:(await Aa(o,t,`✓`),S=`${n} is on the air and you are watching it. Link copied.${s}`),z()}catch{S=`could not reach the server`,z()}finally{t.disabled=!1}}function Wt(e,t=`Join party`){d(e,t===`Join party`?`party`:`live`),e.append(document.createTextNode(` ${t}`)),e.title=t===`Join party`?`Join live`:t}Wt(o.partyJoin);function Gt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,d(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),Ut(e(),n)}),n}let F=new fe({audio:o.audio,video:o.video},{readable:e=>I.owns(e),onTime:(e,t)=>{let n=y[le];p===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),z()},onEnded:()=>{Ta()||On()||p===`remote`&&C<0&&!P()||an(1)},onState:()=>z(),onBusy:e=>{Ce!==e&&(Ce=e,z())},onError:e=>{if(!Ta()&&!(We!==0&&Date.now()-We<2e3)){if(k&&e===`this browser cannot play that format`){let e=k.url;if(k=null,We=Date.now(),Bt()){S=`That site will not let a page play it directly; going live with it on ${m||`the server`} instead.`,z(),o.linkUrl.value=e,Mn();return}S=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,z();return}S=e,z(),xa()}}}),I=new Se({onSnapshot:e=>{let t=e.tracks!==void 0||b.index!==e.index;if(b=me(b,e),v.startsWith(`track:`)&&b.tracks.length>0){let e=Number(v.slice(6));if(v=``,Number.isInteger(e)&&e>=0&&e<b.tracks.length){let t=re;nn(e).then(()=>{t>0&&(F.seek(t),setTimeout(()=>F.seek(t),600))})}}P()&&(j=e.bars.length>0?e.bars:j,M=Ne(M,j)),z(),t&&D&&ba(D)},onStatus:(e,t)=>{x=e,de=t??``,z()}}),Kt=()=>p===`remote`?b.tracks.length:y.length,L=()=>p===`remote`?P()||C<0?b.index:Math.min(C,Math.max(0,b.tracks.length-1)):le,qt=()=>{let e=D?.server.nowPlaying||`Live`;return(!Be||Be.tracks!==b.tracks||Be.index!==b.index||Be.fallback!==e)&&(Be={tracks:b.tracks,index:b.index,fallback:e,value:u(b.tracks,b.index,e)}),Be.value},Jt=()=>p===`remote`&&!w&&E?.kind===`live`,Yt=()=>Jt()?qt().fullTitle:R(),R=()=>{if(w)return w.name;if(O)return O.label;if(Jt())return qt().title;let e=p===`remote`?b.tracks[L()]:y[L()];return e?t(e):`Nothing loaded.`},Xt=()=>{if(w)return`live on this server`;if(O)return`playing here, in this browser`;if(Jt()){let{context:e,position:t}=qt();return[e,t,`live on ${m||`this server`}`].filter(Boolean).join(` · `)}return(p===`remote`?b.tracks[L()]:y[L()])?.album||`—`};function Zt(){if(p!==`remote`||w===null&&E?.kind!==`live`){o.liveLine.hidden=!0,o.liveLine.replaceChildren(),delete o.liveLine.dataset.drawn;return}let e=m||`this server`,t=w?w.name:qt().fullTitle,n=[w?`Live on ${e}: `:`Live from ${e}, now playing: `,Ra(t)],r=w?D?.channels.find(e=>e.id===w?.id)?.code??``:bt?St:``;r&&n.push(`. To talk about it, call `,Ra(A||`the line`),` and key `,Ra(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);o.liveLine.dataset.drawn!==i&&(o.liveLine.dataset.drawn=i,o.liveLine.hidden=!1,o.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let Qt=()=>P()?b.tracks[L()]?.duration??0:F.duration,$t=()=>P()?b.position:F.position,en=()=>P()?b.playing:F.playing;async function tn(e){if(p===`remote`){if(P()){await I.send({type:`play`,index:e});return}await nn(e);return}let t=y[e];t&&(le=e,w=null,E={kind:`file`},await T(()=>F.load(t,!0)),Cn(t.video),wn(),z())}async function nn(e){let t=b.tracks[e];t&&(C=e,w=null,E={kind:`file`},et(t.title,`auto`),await T(()=>F.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:I.media(e,0),video:t.video===!0,objectUrl:!1},!0)),Cn(t.video===!0),wn())}async function rn(){if(F.needsInteraction){await F.play(),z();return}if(P()){await I.send({type:`toggle`});return}Kt()!==0&&(F.playing?F.pause():F.position>0?await F.play():await tn(L()),z())}async function an(e){let t=Kt();if(t!==0){if(P()){await I.send({type:e>0?`next`:`prev`});return}await tn((L()+e+t)%t)}}async function on(){if(Ke(),O=null,k=null,P()){await I.send({type:`stop`});return}w=null,E=null,F.stop(),j=Array(24).fill(0),M=[...j],z()}let sn=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,cn=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],ln=``;function un(){let t=[],n=``,r=null,i=w?D?.channels.find(e=>e.id===w?.id):void 0;w&&i?.ended&&Ue!==w.id&&(Ue=w.id,or(`${w.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let a=F.source===``&&!w&&!(P()&&b.tracks[L()]);if(!a){w&&i?.ended?t.push(`ENDED`):w?t.push(E?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):E?.kind===`vod`?t.push(`ON DEMAND`):E?.kind===`live`?t.push(`LIVE`):p===`remote`&&P()?t.push(`ON THE SERVER`):t.push(`FILE`),!o.video.hidden&&o.video.videoWidth>0?t.push(`${o.video.videoWidth}×${o.video.videoHeight}`):o.video.hidden?t.push(`audio`):t.push(`video`),i?(t.push(i.via===`pull`?`${i.listeners} watching`:`${i.listeners} listening · over ${i.via}`),i.startedAt>0&&t.push(`on air ${e(Math.max(0,(Date.now()-i.startedAt)/1e3))}`),i.redials&&t.push(`redialled ${i.redials}×`),Rt()&&i.error&&t.push(i.error)):p===`remote`&&!w?(b.tracks[L()]&&Kt()>0&&t.push(`${Jt()?`library track`:`track`} ${L()+1} of ${Kt()}`),P()&&D&&t.push(`${D.server.playing?`playing`:`stopped`} on ${m||`the server`}`)):p===`local`&&Kt()>0&&t.push(`track ${L()+1} of ${Kt()}`),E?.catalog!==void 0&&(E.kind===`channel`?w!==null:E.kind===`vod`&&F.source!==``)&&E?.catalog&&(t.push(E.entry?.group?`${E.catalog.name} › ${E.entry.group}`:E.catalog.name),n=E.entry?.logo??``),n===``&&w&&(n=ye(i?.art??w.art));let a=Je?.key===Qe?Je.match:null;if(a?.kind===`fixture`)r=Ie(a),t.unshift(r.status,...r.chips);else if(a){a.image&&(n=a.image);let e=a.data;if(a.kind===`title`){a.year&&t.push(String(a.year));let n=typeof e.rating==`number`?e.rating:null;n&&t.push(`★ ${n.toFixed(1)}`);let r=Array.isArray(e.genres)?e.genres.slice(0,2).map(String):[];r.length&&t.push(r.join(` · `));let i=typeof e.runtimeMin==`number`?e.runtimeMin:0;i&&t.push(`${i} min`)}else if(a.kind===`channel`){let n=typeof e.country==`string`?e.country:``,r=Array.isArray(e.categories)?e.categories.slice(0,2).map(String):[],i=typeof e.network==`string`?e.network:``;n&&t.push(n),r.length&&t.push(r.join(` · `)),i&&t.push(i)}}if(w&&E?.link){let e=``;try{e=new URL(E.link.url).hostname.replace(/^www\./,``)}catch{}t.push(E.link.extractor&&E.link.extractor!==`direct`&&E.link.extractor!==`generic`?`${E.link.extractor} · ${e}`:e||`link`)}bt&&St&&P()&&!w&&E?.kind!==`live`&&t.push(A?`☎ ${A} · key ${St}`:`☎ code ${St}`)}let s=Je?.key===Qe?Je.match:null,c=!a&&!r&&s?.summary?s.summary:``,l=`${n}|${r?`${r.away.logo}|${r.home.logo}|${r.text}`:``}|${t.join(`|`)}|${c}`;if(l===ln)return;ln=l,o.meta.hidden=t.length===0,o.metaBlurb.textContent=c,o.metaBlurb.hidden=c===``;let u=[];if(r){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let n=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,n.push(i),r?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),n.push(t)}if(e.logo!==``){let r=document.createElement(`img`);r.className=`meta-team-logo`,r.alt=``,r.src=e.logo,r.addEventListener(`error`,()=>{r.hidden=!0}),t?n.unshift(r):n.push(r)}return n},n=document.createElement(`span`);n.className=`meta-dash`,n.textContent=`–`,e.replaceChildren(...t(r.away,!0),n,...t(r.home,!1)),u.push(e)}if(n!==``&&/^(https?:\/\/|\/api\/)/.test(n)){let e=document.createElement(`img`);e.className=s?.kind===`title`&&n===s.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=n,e.addEventListener(`error`,()=>{e.hidden=!0}),u.push(e)}for(let e of t){let t=document.createElement(`span`);t.className=r?.state===`in`&&e===r.status?`meta-chip chip-live`:`meta-chip`,t.textContent=e,u.push(t)}o.meta.replaceChildren(...u)}function z(){let t=Kt(),n=en(),r=ke();o.status.textContent=r?`LOADING`:n?`▶ PLAYING`:`■ STOPPED`,o.status.dataset.playing=r?`loading`:String(n),o.title.textContent=R(),o.title.classList.toggle(`with-context`,Jt()),o.album.classList.toggle(`with-context`,Jt()),(Jt()||w)&&wn(),Zt(),un(),o.goLiveNow.hidden=!Bt()||Ht()===null;let i=n?`${Yt()} · ${f}`:f;document.title!==i&&(document.title=i),o.copyNow.hidden=F.source===``,o.shareNow.hidden=ci()===``,Hr(),ei(),o.downloadNow.hidden=!(w&&E?.link?.download),An(),o.album.textContent=Xt();let a=$t(),s=Qt();o.elapsed.textContent=e(a),o.total.textContent=s>0?e(s):`--:--`,he||(o.seek.value=String(s>0?Math.round(a/s*1e3):0),o.seek.disabled=s<=0||P()),o.playPause.textContent=n?`❚❚`:`▶`,o.playPause.setAttribute(`aria-label`,n?`Pause`:`Play`),o.seek.setAttribute(`aria-valuetext`,`${e(F.position)} of ${e(F.duration)}`),o.volume.setAttribute(`aria-valuetext`,`${o.volume.value} percent`),o.playlistTitle.dataset.title=p===`remote`?`Files on ${m||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,o.source.textContent=p===`remote`?`connected · ${m||I.address.replace(/^https?:\/\//,``)||`—`}`:y.length>0?`local · ${y.length} files`:`no source`,Sn(),o.remoteState.textContent=p===`remote`?`${x}${de?` — ${de}`:``}`:`not connected`,o.remoteState.dataset.status=p===`remote`?x:`idle`,o.disconnect.hidden=p!==`remote`;let c=F.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:p===`remote`&&b.note!==``?b.note:S;o.note.textContent=c,o.note.hidden=c===``,o.linkNote.textContent=c,o.linkNote.hidden=c===``,or(c),_n(),o.glyphs.textContent=j.map(cn).join(``);let[l,u]=P()?b.levels:F.levels();o.levels.textContent=sn(l,u)}let dn=``,B=``,fn=0;function pn(e){B=e,fn=0,dn=``,_n()}function mn(e,t,n,r,i){if(o.playlistPager.hidden=n<=1,n<=1){o.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{fn=t,dn=``,_n()}),i},s=document.createElement(`span`);s.className=`pager-where`,s.textContent=`${r+1}–${i} of ${e.toLocaleString()}`,o.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),s,a(`Next ›`,t+1,`The page after this one`))}function hn(e){if(o.crumbs.hidden=!e,!e)return;let t=B===``?[]:B.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>pn(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),o.crumbs.replaceChildren(...r)}function gn(e,t){let n=document.createElement(`li`);n.className=`folder`;let r=document.createElement(`span`);r.className=`name`,r.textContent=`${e}/`;let i=document.createElement(`span`);i.className=`count`,i.textContent=`${t} file${t===1?``:`s`}`,n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),a.append(r,i),n.replaceChildren(a),a.addEventListener(`click`,t=>{t.stopPropagation(),pn(B===``?e:`${B}/${e}`)}),n}function _n(){let n=p===`remote`?b.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):y.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=o.filter.value.trim().toLowerCase(),i=n.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>r===``||`${e.folder}/${e.name}`.toLowerCase().includes(r)),c=e=>r!==``||B===``||e===B||e.startsWith(`${B}/`),l=e=>r!==``||e===B,u=e=>{let t=B===``?e:e.slice(B.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of i){if(!c(e.folder)||l(e.folder))continue;let t=u(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let m=i.filter(e=>l(e.folder)&&c(e.folder)),h=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),g=He(h.length+m.length,fn,a);fn=g.page;let ee=h.slice(g.from,g.to),_=m.slice(Math.max(0,g.from-h.length),Math.max(0,g.to-h.length)),te=`${p}:${B}:${r}:${g.page}/${a}:${h.join(`,`)}:${m.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(te!==dn){dn=te,hn(r===``&&(h.length>0||B!==``)),mn(h.length+m.length,g.page,g.pages,g.from,g.to);let t=[];for(let[e,n]of ee)t.push(gn(e,n));let n=``,i=m.some(e=>e.group!==``);for(let r of _){r.group!==n&&(i||r.group!==``)&&(n=r.group,t.push(vn(r.group)));let a=document.createElement(`li`);a.className=`row`,a.dataset.index=String(r.index);let o=document.createElement(`span`);o.className=`n`,o.textContent=String(r.index+1).padStart(2,` `);let s=document.createElement(`span`);s.className=`name`,s.textContent=r.name;let c=document.createElement(`span`);c.className=`time`,c.textContent=r.seconds>0?e(r.seconds):`--:--`;let l=document.createElement(`button`);if(l.type=`button`,l.className=`row-main`,l.setAttribute(`aria-label`,`Play ${r.name}${r.seconds>0?`, ${e(r.seconds)}`:``}`),l.append(o,s,c),a.append(l),p===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,d(e,`copy`),e.title=`Copy a link that plays this here, from where it is`,e.setAttribute(`aria-label`,`Copy a link that plays ${r.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),Aa(ja(`track:${r.index}`,C===r.index?F.position:0),e,`✓`)}),a.append(e),Bt()&&a.append(Gt(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}t.push(a)}s(o.playlist,...t)}let ne=L(),v=en();for(let e of Array.from(o.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===ne;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&v),r?t.setAttribute(`aria-current`,`true`):t.removeAttribute(`aria-current`)}}function vn(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!o.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,t=>{t.stopPropagation(),yn(e)}),t.append(n)}return t}async function yn(e){try{let t=await fetch(I.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();V(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{V(`could not reach the server`)}}function bn(){let t=o.canvas,n=Math.min(2,globalThis.devicePixelRatio||1),r=Math.round(t.clientWidth*n),i=Math.round(t.clientHeight*n);r>0&&i>0&&(t.width!==r||t.height!==i)&&(t.width=r,t.height=i);let a=t.getContext(`2d`);if(P())M=Ne(M,j);else{let e=F.read();e.length>0&&(Lt.length!==25&&(Lt=Ae(24,e.length)),j=Me(j,je(e,Lt)),M=Ne(M,j))}if(a){let e=getComputedStyle(document.documentElement);Pe(a,{width:t.width,height:t.height},j,M,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(en()){o.glyphs.textContent=j.map(cn).join(``);let[t,n]=P()?b.levels:F.levels();o.levels.textContent=sn(t,n),o.elapsed.textContent=e($t());let r=Qt();!he&&r>0&&(o.seek.value=String(Math.round($t()/r*1e3)))}requestAnimationFrame(bn)}let xn=``;function Sn(){if(p!==`remote`){o.wayInHere.hidden=!0,xn=``;return}let e=Rt()&&!ne,t=se||I.address,n=e?null:ae(I.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===xn)return;xn=r;let[i,a]=oe({name:m||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,o.wayInHere.replaceChildren(i,a),o.wayInHere.hidden=!1}function Cn(e){o.video.hidden=!e,o.fullscreen.hidden=!e,Ke(),O=null,k=null}function wn(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=w?ye(D?.channels.find(e=>e.id===w?.id)?.art??w.art):``,t=JSON.stringify([R(),Xt(),e]);t!==Re&&(Re=t,navigator.mediaSession.metadata=new MediaMetadata({title:R(),album:Xt(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void rn()),navigator.mediaSession.setActionHandler(`pause`,()=>void rn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void an(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void an(-1)))}o.filter.addEventListener(`input`,()=>{fn=0,dn=``,_n()}),o.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),o.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&tn(n)}),o.fullscreen.addEventListener(`click`,()=>{let e=o.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),o.prev.addEventListener(`click`,()=>void an(-1)),o.next.addEventListener(`click`,()=>void an(1)),o.stop.addEventListener(`click`,()=>void on()),o.playPause.addEventListener(`click`,()=>void rn());async function Tn(e){let t=Ye(e,Vt());if(!t){if(!Bt()){S=p===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,z();return}await kn(e);return}if(w=null,F.stop(),t.kind===`embed`){E={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},Cn(!1),o.embedFrame.src=t.src,o.embed.hidden=!1,O={url:e,label:t.label,kind:`embed`},S=`Playing ${t.label} here, in this browser.`,z();return}if(t.kind===`list`){await En(e,t.label);return}E={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await T(()=>F.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),Cn(t.video),O={url:e,label:t.label,kind:`direct`},S=`Playing ${t.label} here, in this browser.`,z()}async function En(e,t){S=`Reading ${t}…`,z();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){S=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,z();return}let r=qe(n,e);if(r.entries.length===0){S=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,z();return}k={url:e,title:r.title||t,entries:r.entries,at:0},await Dn()}async function Dn(){let e=k,t=e?.entries[e.at];if(!e||!t)return;let n=Ge(t.url);E={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await T(()=>F.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),k!==null&&(Cn(n),O={url:e.url,label:e.title,kind:`direct`},k=e,S=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,z())}function On(){let e=k;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Dn(),!0)}async function kn(e){if(p!==`remote`){S=`Pick a server to go live on, or connect to one, to put a link on the air.`,z();return}S=`Asking ${m||`the server`} to fetch ${e}…`,z(),await T(async()=>{let t,n={};try{t=await fetch(I.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{S=`could not reach the server`;return}if(!t.ok||!n.channel){S=n.error??`that link would not play.`;return}try{await fetch(I.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await wa({id:n.channel,name:n.name||e,video:n.video!==!1,art:n.art},!0,{kind:`channel`,link:{url:e,extractor:n.extractor??``,download:n.download===!0,live:n.live===!0,video:n.video!==!1}}),(n.entries??0)>1&&(S=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),z()}o.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.linkUrl.value.trim();t!==``&&Tn(t)});function An(){let e=p===`remote`?I.address:``,t=h.filter(t=>te(t.url)!==te(e)),n=JSON.stringify({here:e,name:m,carries:ee,others:t});if(n===g||document.activeElement===o.linkServer)return;g=n;let r=[];if(e!==``&&ee){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${m||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}o.linkServer.replaceChildren(...r),o.linkServer.value=e!==``&&!ee&&t[0]?t[0].url:``,o.linkServer.hidden=t.length===0}async function jn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;h=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),An()}catch{}}async function Mn(){let e=o.linkUrl.value.trim()||O?.url||``;if(e===``){S=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,z();return}let t=o.linkServer.value;if(t!==``&&(p!==`remote`||te(t)!==te(I.address))){let n=h.find(e=>e.url===t)?.name??t;_=e,S=`Connecting to ${n} to go live with it…`,z(),Nn(t);return}if(p!==`remote`){S=h.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,z();return}if(!ee){S=`${m||`This server`} has no ffmpeg, so it cannot carry a link.`+(h.length>0?` Pick a server to go live on, beside the link.`:``),z();return}if(!Bt()){S=`Sign in to nixamp.com to go live here, or use the server's control link.`,z();return}await kn(e)}function Nn(e){let t=o.linkUrl.value.trim();ne=!0,v=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit(),o.linkUrl.value=t}o.linkGoLive.addEventListener(`click`,()=>{Mn()}),o.linkServer.addEventListener(`change`,()=>{let e=o.linkServer.value;e!==``&&Nn(e)}),o.downloadNow.addEventListener(`click`,()=>{let e=E?.link;if(!e||p!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(I.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),S=`Fetching it through the server; your browser will save it when it arrives.`,z()}),o.goLiveNow.addEventListener(`click`,()=>{let e=Ht();e&&Ut(e,o.goLiveNow)}),o.seek.addEventListener(`input`,()=>{he=!0}),o.seek.addEventListener(`change`,()=>{let e=Qt();e>0&&F.seek(Number(o.seek.value)/1e3*e),he=!1}),o.volume.addEventListener(`input`,()=>{let e=Number(o.volume.value)/100;F.volume=e;try{localStorage.setItem(Nt,String(e))}catch{}});let Pn=e=>{e.addEventListener(`change`,()=>{let t=ce(Array.from(e.files??[]));if(t.length===0){S=`Nothing playable in that selection.`,z();return}ue(y),y=t,le=0,p=`local`,I.close(),S=``,tn(0)})};Pn(o.files),Pn(o.folder),o.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.remoteUrl.value,{base:n,key:r}=ve(t);if(n===``){S=`That is not an address.`,z();return}(async()=>{x=`connecting`,z();let e=Oe(n);if(e){x=`error`,de=e,S=e,_=``,p=`local`,z();return}if(await De(n,void 0,r)===null){x=`error`;let e=Te(n);de=e?`needs the server's name`:`not answering`,S=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,_=``,p=`local`,z();return}let i=await Ee(n,r);if(i){x=`error`,de=i,S=i,_=``,p=`local`,z();return}p=`remote`,S=``;try{localStorage.setItem(jt,t.trim())}catch{}I.connect(t),$(),_i(),ya(!0),Kn(),ga(),z()})()});let Fn=``,In=null,Ln=async(e=!1)=>{o.directory.hidden=!1,e||(o.directoryNote.textContent=`Looking for live streams…`,s(o.directoryList)),In||=setInterval(()=>{!o.directory.hidden&&document.visibilityState===`visible`&&Ln(!0)},Ft);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],h=t.map(e=>({name:e.name,url:e.url})),An();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:G});if(e&&i===Fn)return;Fn=i,Yn(r.recent??[])}catch{e||(o.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(s(o.directoryList),t.length===0){o.directoryNote.textContent=`Nobody is streaming right now.`;return}o.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let a=[`${e.tracks.toLocaleString()} files to browse`];e.playing!==!1&&e.nowPlaying?a.push(`playing ${e.nowPlaying}`):a.push(`player idle`),e.code&&a.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=a.join(` · `),i.title=i.textContent,n.append(r,i);let s=e.admin??ae(e.url),c=(t,n=``)=>{ne=t,v=n,o.remoteUrl.value=t?e.url:s??e.url,o.directory.hidden=!0,o.remoteForm.requestSubmit()},l=document.createElement(`ul`);l.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let o=e.lineup?.find(e=>e.name===t);if(o?.art&&/^https?:\/\//i.test(o.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=o.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}o?.about&&(r.title=o.about);let s=document.createElement(`button`);s.type=`button`,s.className=`button`,Wt(s),s.title=`Join live: ${t} on ${e.name}`,s.addEventListener(`click`,()=>c(!0,`channel:${t}`)),n.append(r,s),l.append(n)}let[u,d]=oe({name:e.name,view:e.url,admin:s},()=>{o.directory.hidden=!0});if(t.append(n,u,d),G&&t.append(ir(e.url,e.name)),e.ownerId&&G&&e.ownerId!==G&&t.append(Ai(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&G&&e.ownerId===G){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));o.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{o.directoryNote.textContent=`could not reach the directory`}finally{await Ln()}})()}),t.append(n)}o.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!o.directory.hidden&&Ln(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),Ln()}let Rn=null,zn=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Bn=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,Vn=``,Hn=``,Un=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===Vn)return;Vn=t,o.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}o.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[zn(t.network),`network-${t.network}`],[Bn(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}o.adminConnections.append(e)}};function V(e){o.adminSaid.textContent=e,o.adminSaid.hidden=e===``}let Wn=async()=>{try{let e=await fetch(I.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;o.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,Un(t.connections??[]),Gn(t.publish??[],(t.channels??[]).map(e=>e.id)),Ia(t.home??``,t.root??``),$()}catch{o.adminNote.textContent=`lost touch with the server`}};function Gn(e,t){o.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Hn)return;if(Hn=n,e.length===0){s(o.publishList);return}let r=e.length-t.length;o.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,s(o.publishList,...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,o.textContent=`Copy`,o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let Kn=async()=>{if(p!==`remote`){o.adminPanel.hidden=!0,o.publishPanel.hidden=!0,Rn&&clearInterval(Rn),Rn=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(I.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;if(ne&&(e=!1),zt=i&&!e,o.adminPanel.hidden=!e,ha(e),_!==``){let e=_;_=``,Bt()?kn(e):(S=`Sign in to nixamp.com to go live here.`,z())}if(Rn&&clearInterval(Rn),Rn=null,$(),_i(),ga(),o.listenOnly.hidden=e,!e){o.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}o.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Wn(),Rn=setInterval(()=>void Wn(),2e3)};function qn(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;V(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(I.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),a=await i.json();if(!i.ok){V(a.error??`that did not work`);return}V(`${a.channel?.name||t||e} is on the air.`),o.adminSource.value=``,o.adminName.value=``,ga(),$()}catch{V(`could not reach the server`)}})()}o.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=o.adminSource.value.trim();t&&qn(t,o.adminName.value.trim())}),o.adminAdd.addEventListener(`click`,()=>{let e=o.adminSource.value.trim();if(!e)return;V(`Reading ${e}…`);let t=o.adminReplace.checked,n=o.adminName.value.trim();(async()=>{try{let r=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();V(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(o.adminSource.value=``,o.adminName.value=``,ga(),$())}catch{V(`could not reach the server`)}})()});let Jn=e=>{let t=Math.max(1,Math.round((Date.now()-e)/6e4));if(t<60)return`${t} minute${t===1?``:`s`} ago`;let n=Math.round(t/60);return`${n} hour${n===1?``:`s`} ago`},Yn=e=>{let t=[],n=G?e.filter(e=>e.ownerId&&e.ownerId!==G):[];if(o.recentNote.hidden=n.length===0,n.length===0){s(o.recentList);return}for(let e of n){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${Jn(e.endedAt)}`:`ended ${Jn(e.endedAt)}`,r.append(i,a),n.append(r,Ai(e.ownerId,e.name)),t.push(n)}s(o.recentList,...t)},Xn=e=>{let t=Math.max(0,Math.floor(e)),n=String(t%60).padStart(2,`0`),r=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(r).padStart(2,`0`)}:${n}`:`${r}:${n}`};function Zn(e){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.event.title||e.party.partyCode;let i=document.createElement(`span`);i.className=e.party.playing?`detail live`:`detail`,i.textContent=[e.party.playing?`▶ ${Xn(e.party.positionNow)}`:`❚❚ ${Xn(e.party.positionNow)}`,e.party.mediaTitle,e.party.origin,e.host?`yours`:``].filter(Boolean).join(` · `),n.append(r,i);let a=document.createElement(`a`);a.className=`button`,a.href=e.links.partyUrl||e.links.nixampUrl,a.rel=`noopener`,a.target=`_blank`,Wt(a),a.title=`Join live on the site hosting this party (opens in a new tab)`;let o=document.createElement(`a`);return o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.append(n,a,o),t}async function Qn(){if(!G){o.partiesPanel.hidden=!0;return}try{let e=await fetch(`/api/v1/watch-parties`);if(!e.ok){o.partiesPanel.hidden=!0;return}let t=(await e.json()).parties??[];o.partiesPanel.hidden=!1,o.partiesNote.textContent=t.length===0?`No parties happening right now. Join with an invite code.`:`Join a party on the site hosting the film, or open its room here.`,s(o.partiesList,...t.map(Zn))}catch{o.partiesPanel.hidden=!0}}o.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){S=n.error??`No party found with that invite code.`,z();return}o.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{S=`Could not look up that party. Try again.`,z()}})()});async function $n(){if(!G){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];o.connectionsNote.hidden=t.length===0,o.connectionsList.hidden=t.length===0,s(o.connectionsList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,a.textContent=`Disconnect`,a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await $n()})()}),t.append(n,a),t}))}catch{o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0}}let er=new Set,H=e=>{try{return new URL(e).origin}catch{return e}},tr=e=>[...er].some(t=>H(t)===H(e));async function nr(){if(!G){er=new Set,o.favoritesPanel.hidden=!0,ar();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){o.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];er=new Set(t.map(e=>e.url)),o.favoritesPanel.hidden=t.length===0,o.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,s(o.favoritesList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...oe({name:e.name||e.url,view:e.url,admin:ae(e.url)}),ir(e.url,e.name)),t}))}catch{o.favoritesPanel.hidden=!0}ar()}async function rr(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){S=n?`Could not save that favourite.`:`Could not remove that favourite.`,z();return}}catch{S=`could not reach nixamp.com`,z();return}if(n)er.add(e);else for(let t of[...er])H(t)===H(e)&&er.delete(t);await nr()}function ir(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=tr(e);n.textContent=t?`♥`:`♡`,n.dataset.on=t?`yes`:`no`,n.title=t?`Remove from favourites`:`Add to favourites`,n.setAttribute(`aria-label`,n.title)};return r(),n.addEventListener(`click`,n=>{n.stopPropagation();let i=[...er].find(t=>H(t)===H(e))??e;rr(tr(e)?i:e,t,!tr(e)).then(r)}),n}function ar(){let e=p===`remote`?I.shareLink:``;if(o.favHere.hidden=!(G&&e),o.favHere.hidden)return;let t=tr(e);o.favHere.textContent=t?`♥`:`♡`,o.favHere.dataset.on=t?`yes`:`no`,o.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,o.favHere.setAttribute(`aria-label`,o.favHere.title)}d(o.copyNow,`copy`),o.copyNow.addEventListener(`click`,()=>{Aa(F.source,o.copyNow,`✓`)});function or(e){if(e===``||e===kt)return;kt=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),n.textContent=r.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`});let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),o.logList.prepend(t);o.logList.children.length>100;)o.logList.lastElementChild?.remove()}let sr=3e3,U=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,cr=``,lr=``,ur=null,dr=!1,fr=new Set,pr=``,mr=null,hr=!1,gr=vt(e=>localStorage.getItem(e)),W=pt(e=>localStorage.getItem(e)),_r=new Set,vr=new Set,yr=null,br=``,xr=``,G=``,Sr=`listener-${crypto.randomUUID()}`,K=null,q=!1,Cr=``,wr=!1,Tr=0,Er=!1,Dr=!1;try{o.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let Or=new wt(()=>{Dr=!0,Er&&(o.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)}),J=new xt({playing:()=>F.playing,volume:()=>F.volume,active:e=>{Er=e,F.translatedAudio(e),Or.active(e&&o.transcriptBackground.checked)},status:e=>{o.transcriptAudioNote.textContent=e+(Dr&&Er?` · background unavailable`:``)},failed:()=>{xr=o.transcriptAudioNote.textContent||`Translated audio stopped.`,q=!1,o.transcriptAudio.checked=!1,jr()},authorization:async(e,t)=>{if(!G||U!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!K||K.channel!==t.channel||K.expires<Date.now()+2e4||K.remaining<t.text.length){let n=await fetch(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),r=await n.json();if(!n.ok||!r.token||!r.expires)throw Error(r.error||`Sign in to enable translated audio.`);K={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return K.remaining-=t.text.length,{authorization:`Bearer ${K.token}`}}}),kr=new Et({language:()=>W,speakers:()=>o.transcriptAudio.checked,voices:()=>yr?.voices??[],channel:()=>Sr,status:e=>{!wr&&!q&&(Cr=e),o.transcriptNote.textContent=e},failed:()=>{q=!1,o.transcriptAudio.checked=!1,J.disable(),jr()},lines:e=>{Ir=0,Lr.push(...e),ri(),Nr(),o.transcriptAudio.checked&&J.pushBatch(e.map(e=>({line:e,lag:0,url:`/api/v1/speech/synthesize`,init:{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:e.text,language:W,channel:Sr,speaker:e.speaker,voice:kr.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),Ar=new Ct(e=>{wr&&F.playing&&kr.push(e)});function jr(){Tr++,wr=!1,Ar.stop(),kr.reset(),Or.stop(),J.reset(),F.translatedAudio(!1),s(o.transcriptSpeakers)}async function Mr(){jr();let e=Tr;try{if(!G||U!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=F.audioInput();if(Dr=!1,o.transcriptAudio.checked&&o.transcriptBackground.checked&&Or.start(t.context,t.node).then(t=>{t&&e===Tr&&Or.active(Er&&o.transcriptBackground.checked)}),await Ar.start(t.context,t.node),e!==Tr)return;wr=!0,q=!0,Ir=0,zr??=setInterval(ri,250),o.transcriptNote.textContent=o.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==Tr)return;q=!1,o.transcriptAudio.checked=!1,J.disable(),jr(),Cr=t instanceof Error?t.message:`This audio could not be captured.`,o.transcriptNote.textContent=Cr}}function Nr(){let e=[...kr.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(o.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id,e.append(`Speaker ${t.id.split(`-`)[1]} `);let n=document.createElement(`select`);n.className=`transcript-language`,n.setAttribute(`aria-label`,`Voice for ${e.textContent?.trim()}`);for(let e of yr?.voices??[])n.append(new Option(e.name,e.id));n.value=t.voice,n.addEventListener(`change`,()=>{t.voice=n.value,J.reset()}),e.append(n),o.transcriptSpeakers.append(e)}o.transcriptVoiceSettings.hidden=!o.transcriptAudio.checked||!e.length;for(let e of o.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[o.audio,o.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{jr()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{q&&gr&&F.playing&&Mr()});e.addEventListener(`volumechange`,()=>{J.setVolume()})}let Pr=``,Fr=null,Ir=ht(6,!1),Lr=[],Rr=[],zr=null;function Br(){if(p!==`remote`)return null;let{base:e}=ve(Ma());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=w?w.id:E?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Vr(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${U}/api/v1/trollbox?${n.toString()}`}function Hr(){let e=Br(),t=e?`${e.server}|${e.channel}`:``;t!==cr&&(cr=t,lr=``,fr.clear(),o.trollboxList.replaceChildren(),ur&&clearTimeout(ur),ur=null,o.trollboxPanel.hidden=e===null,o.trollboxForm.hidden=!0,qr(!1),e&&(o.trollboxNote.textContent=`The room for ${R()||e.channel}. Loading…`,Wr()))}function Ur(e){let t=document.createElement(`li`);t.dataset.id=e.id;let n=document.createElement(`time`);n.className=`when`,n.dateTime=e.createdAt;let r=new Date(e.createdAt);n.textContent=Number.isNaN(r.getTime())?``:r.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`});let i=document.createElement(`span`);i.className=`who`,i.textContent=e.handle;let a=document.createElement(`span`);return a.className=`line`,a.textContent=e.body,t.append(n,i,a),t}async function Wr(){let e=Br(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===cr&&!dr){dr=!0;try{let n=await fetch(Vr(e,lr)),r=await n.json().catch(()=>({}));if(t!==cr)return;if(!n.ok){o.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!fr.has(e.id));for(let e of i)fr.add(e.id),o.trollboxList.append(Ur(e)),lr=e.createdAt;for(;o.trollboxList.children.length>200;)o.trollboxList.firstElementChild?.remove();let a=r.you??``,s=pr!==a;pr=a,s&&(K=null,ai()),o.trollboxForm.hidden=a===``,o.trollboxEditLabel.hidden=a===``||!Gr,a===``&&qr(!1),o.trollboxNote.textContent=a===``?U===``?`The room for ${R()||e.channel}. Sign in to say something.`:`The room for ${R()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${a} in the room for ${R()||e.channel}.`}catch{t===cr&&(o.trollboxNote.textContent=`The trollbox is not answering.`)}finally{dr=!1,t===cr&&(ur=setTimeout(()=>{document.visibilityState===`visible`?Wr():ur=setTimeout(()=>void Wr(),sr)},sr))}}}o.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Br(),n=o.trollboxInput.value.trim();t&&n!==``&&(o.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${U}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:n})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.message){o.trollboxNote.textContent=r.error??`that did not send`;return}o.trollboxInput.value=``,fr.has(r.message.id)||(fr.add(r.message.id),o.trollboxList.append(Ur(r.message)),lr=r.message.createdAt)}catch{o.trollboxNote.textContent=`The trollbox is not answering.`}finally{o.trollboxInput.disabled=!1}})())});let Gr=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Kr=Gr?st(e=>MediaRecorder.isTypeSupported(e)):``;o.trollboxMic.hidden=!Gr;function Y(e){o.trollboxNote.textContent=e,or(e)}function qr(e){let t=mr;if(!t)return;mr=null,clearTimeout(t.stop),clearInterval(t.tick),o.trollboxMic.setAttribute(`aria-pressed`,`false`),o.trollboxMic.textContent=`🎤`;let n=new Promise(e=>{t.recorder.addEventListener(`stop`,()=>e(),{once:!0})});t.recorder.state!==`inactive`&&t.recorder.stop();for(let e of t.stream.getTracks())e.stop();e&&n.then(()=>Yr(new Blob(t.chunks,{type:t.recorder.mimeType||Kr||`audio/webm`}),t.startedAt))}async function Jr(){if(mr||hr||pr===``||!Br())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){Y(e.name===`NotAllowedError`?`The microphone was refused. Allow it for nixamp.com and tap again.`:`No microphone could be opened here.`);return}let t;try{t=new MediaRecorder(e,Kr?{mimeType:Kr}:{})}catch{for(let t of e.getTracks())t.stop();Y(`This browser cannot record the microphone.`);return}let n=[];t.addEventListener(`dataavailable`,e=>{e.data.size>0&&n.push(e.data)});let r=Date.now();mr={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>qr(!0),ot),tick:setInterval(()=>{o.trollboxMic.textContent=lt(r,Date.now())},500)},t.start(250),o.trollboxMic.setAttribute(`aria-pressed`,`true`),o.trollboxMic.textContent=lt(r,r),Y(`Listening. Tap the mic again when you have said it (${Math.round(ot/1e3)} s at most).`)}async function Yr(e,t){let n=Br();if(n&&pr!==``){if(Date.now()-t<400||e.size===0){Y(`That was too short to hear. Tap, say it, then tap again.`);return}hr=!0,o.trollboxMic.disabled=!0,o.trollboxMic.textContent=`…`,Y(`Hearing you…`);try{let t=new AudioContext,r;try{r=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let i=new OfflineAudioContext(1,Math.max(1,Math.ceil(r.duration*at)),at),a=i.createBufferSource();a.buffer=r,a.connect(i.destination),a.start();let s=ct((await i.startRendering()).getChannelData(0),at),c=o.trollboxEdit.checked,l=new URLSearchParams(c?{}:{server:n.server,channel:n.channel}),u=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(u)&&l.set(`language`,u);let d=await fetch(`${U}/api/v1/speech/transcribe?${l.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([s.buffer],{type:`audio/wav`})}),f=await d.json().catch(()=>({}));if(!d.ok){Y(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){Y(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=o.trollboxInput.value.trimEnd();o.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),Y(`Heard: “${p}”. Send it, or fix it first.`);return}Br()&&!fr.has(f.message.id)&&(fr.add(f.message.id),o.trollboxList.append(Ur(f.message)),lr=f.message.createdAt),Y(`Said: “${f.message.body}”`)}catch{Y(`That recording could not be read here.`)}finally{hr=!1,o.trollboxMic.disabled=!1,o.trollboxMic.textContent=`🎤`}}}o.trollboxMic.addEventListener(`click`,()=>{mr?qr(!0):Jr()});try{o.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}o.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,o.trollboxEdit.checked?`on`:`off`)}catch{}Y(o.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Xr(){try{let e=await fetch(`${U}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){o.personaNote.textContent=t.error??`Could not read your profile.`;return}o.personaHandle.value=t.chosen?t.handle??``:``,o.personaHandle.placeholder=t.handle||`handle`,o.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,o.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;o.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${Zr(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${Zr(t.voice??``)}${n}.`}catch{o.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function Zr(e){return e===`female`?`in a woman's voice`:e===`male`?`in a man's voice`:e.includes(`.`)?`in the voice ${e}`:`in whichever voice your profile says, or one picked for you`}o.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.personaHandle.value.trim(),n={voice:o.personaVoice.value,profile:o.personaProfile.value.trim()};t!==``&&(n.handle=t),o.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${U}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){o.personaNote.textContent=t.error??`that did not save`;return}await Xr()}catch{o.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&mr&&qr(!0)});function Qr(){return p===`remote`&&w?{id:w.id,name:w.name,hls:w.video&&Vt()}:F.loaded||O?{id:Sr,name:R()||`This audio`,hls:!1}:null}function $r(){jr(),K=null,_r.clear(),vr.clear(),Fr?.close(),Fr=null,zr&&clearInterval(zr),zr=null,Lr=[],Rr=[],o.transcriptList.replaceChildren(),o.subtitle.hidden=!0,o.subtitle.textContent=``}function ei(){let e=Qr(),t=`${e?.id??``}|${F.mediaKey}|${gr}|${W}|${o.transcriptAudio.checked}|${q}|${G}`;if(t!==Pr){if(Pr=t,$r(),o.transcriptPanel.hidden=!1,o.transcriptOn.checked=gr&&(!!w||q||o.transcriptAudio.checked),o.transcriptLanguage.options.length===0)for(let e of ft)o.transcriptLanguage.append(new Option(e.label,e.code));if(o.transcriptLanguage.value=W,ai(),oi(),!e){o.transcriptNote.textContent=`Play something to see its captions.`;return}if(!gr){o.transcriptNote.textContent=`Captions are off.`;return}if(Cr){o.transcriptNote.textContent=Cr;return}o.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,o.transcriptAudio.checked||q?F.playing?Mr():o.transcriptNote.textContent=`Press Play to start listening.`:p===`remote`&&w?ti(e,t):o.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function ti(e,t){let n=6,r=W?`?language=${encodeURIComponent(W)}`:``;try{let i=await fetch(I.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),a=await i.json().catch(()=>({}));if(t!==Pr)return;if(!i.ok){o.transcriptNote.textContent=a.error??`This server is not captioning.`;return}if(a.recognitionRevision!==`native-v2`){G&&U===``?(q=!0,ei()):o.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=a.backlog??n}catch{t===Pr&&(o.transcriptNote.textContent=`The server did not answer about captions.`);return}Ir=ht(n,e.hls);let i=new EventSource(I.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));Fr=i;let a=(e,t=!1)=>{for(let n of e){if(!n||typeof n.text!=`string`||!Number.isFinite(n.at)||!Number.isFinite(n.until))continue;let e=`${n.at}|${n.language}`;_r.has(e)||(_r.add(e),_r.size>600&&_r.delete(_r.values().next().value),Lr.push(n),t&&o.transcriptAudio.checked&&vr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==Pr)return;let i=JSON.parse(r.data);Ir=ht(i.backlog??n,e.hls),a(i.lines??[]);let s=ft.find(e=>e.code===i.language)?.label??i.language,c=ft.find(e=>e.code===W)?.label??W;if(o.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:W?`${s||`Detected audio`} → ${c}`:`Original audio · ${s||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${U||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,o.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==Pr)return;let r=JSON.parse(n.data);a([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=ft.find(e=>e.code===i)?.label??i,c=ft.find(e=>e.code===W)?.label??W;o.transcriptNote.textContent=W?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===Pr&&i.readyState===EventSource.CLOSED&&(o.transcriptNote.textContent=`Captions stopped; the server went away.`)}),zr=setInterval(ri,250)}function ni(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),n.textContent=yt(e.at);let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text;let i=mt(e);if(i){let a=document.createElement(`span`);a.className=`lang`,a.textContent=i.trim(),e.original&&(r.title=e.original),t.append(n,a,r)}else t.append(n,r);return t}function ri(){let e=Date.now(),{ready:t,still:n}=gt(Lr,e,Ir);Lr=n;for(let e of t)if(Rr.push(e),o.transcriptList.append(ni(e)),vr.delete(e)&&o.transcriptAudio.checked&&W){let t=new URLSearchParams({at:String(e.at),language:W,voice:`auto`});J.push(e,I.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),Ir)}for(;Rr.length>200;)Rr.shift();for(;o.transcriptList.children.length>200;)o.transcriptList.firstElementChild?.remove();let r=_t(Rr,e,Ir),i=o.transcriptList.children,a=r?Rr.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let s=F.playing&&r!==null&&!o.video.hidden&&o.video.offsetHeight>0;o.subtitle.hidden=!s,s&&r&&(o.subtitle.textContent!==r.text&&(o.subtitle.textContent=r.text),o.subtitle.style.top=`${o.video.offsetTop+o.video.offsetHeight-o.subtitle.offsetHeight-10}px`)}o.transcriptOn.addEventListener(`change`,()=>{gr=o.transcriptOn.checked,q=gr&&(!w||o.transcriptAudio.checked),gr||(o.transcriptAudio.checked=!1,J.disable());try{localStorage.setItem(ut,gr?`on`:`off`)}catch{}ei()}),o.transcriptLanguage.addEventListener(`change`,()=>{Cr=``,xr=``,W=pt(()=>o.transcriptLanguage.value),!W&&o.transcriptAudio.checked&&(o.transcriptAudio.checked=!1,q=!1,J.disable());try{W?localStorage.setItem(dt,W):localStorage.removeItem(dt)}catch{}ei()});function ii(){if(W)return W;let e=navigator.language.split(`-`)[0]||`en`;return ft.some(t=>t.code===e)&&yr?.languages.includes(e)?e:`en`}function ai(){let e=G!==``&&U===``,t=e&&!!Qr()&&!!yr?.languages.includes(ii());o.transcriptAudio.disabled=!t,o.transcriptVoiceSettings.contains(document.activeElement)||(o.transcriptVoiceSettings.hidden=!o.transcriptAudio.checked||!o.transcriptSpeakers.children.length),t?o.transcriptAudio.checked||(o.transcriptAudioNote.textContent=xr||`Original audio.`):(o.transcriptAudio.checked=!1,J.disable(),o.transcriptAudioNote.textContent=e?Qr()?xr||(yr?`Audio translation is unavailable for this language.`:`Loading voices…`):`Play something to translate its audio.`:`Sign in to translate audio.`)}async function oi(){if(!G||U!==``)return;let e=`/api/v1/speech/voices`;if(br!==e){br=e,yr=null,xr=``,ai();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(br!==e)return;if(!t.ok)throw Error(n.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(n.voices)||!Array.isArray(n.languages))throw Error(`This server needs an update for translated audio.`);yr=n}catch(t){if(br!==e)return;xr=t instanceof Error?t.message:`Translated audio is unavailable.`}ai()}}o.transcriptBackground.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.backgroundSound`,o.transcriptBackground.checked?`on`:`off`)}catch{}if(Or.stop(),Dr=!1,o.transcriptBackground.checked&&o.transcriptAudio.checked&&F.playing){let e=Tr,t=F.audioInput();Or.start(t.context,t.node).then(t=>{t&&e===Tr&&Or.active(Er&&o.transcriptBackground.checked)})}}),o.transcriptAudio.addEventListener(`change`,()=>{if(Cr=``,xr=``,vr.clear(),o.transcriptAudio.checked){W=ii();try{localStorage.setItem(dt,W)}catch{}gr=!0,q=!0,J.enable()}else q=!1,J.disable();ei()});function si(){if(O)return O.url;if(p!==`remote`)return``;let{base:e,key:t}=ve(Ma());if(e===``)return``;if(w)return ge(e,`/api/channels/${encodeURIComponent(w.id)}`,t);if(E?.kind===`live`)return ge(e,`/api/live`,t);if(F.source===``)return``;try{let n=new URL(F.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function ci(){let e=si();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}o.shareNow.addEventListener(`click`,()=>{let e=ci();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${Yt()} on nixamp`,url:e}).catch(()=>void 0);return}Aa(e,o.shareNow,`Copied`)}),o.favHere.addEventListener(`click`,()=>{let e=Ma()||I.shareLink;if(!e)return;let t=[...er].find(t=>H(t)===H(e))??e;rr(tr(e)?t:e,m||I.address,!tr(e)).then(ar)});let li=r?a:200,ui=[],X=null,Z=null,di=``,fi=[],pi=0,mi=null,hi=0;function gi(e){if(!e)return`never`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));if(t<90)return`just now`;let n=Math.round(t/60);if(n<90)return`${n} min ago`;let r=Math.round(n/60);return r<36?`${r} h ago`:`${Math.round(r/24)} d ago`}async function _i(){if(p!==`remote`){o.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(I.url(`/api/catalogs`))}catch{o.catalogsPanel.hidden=!0;return}if(!e.ok){o.catalogsPanel.hidden=!0;return}ui=(await e.json().catch(()=>({}))).catalogs??[],X&&=ui.find(e=>e.id===X?.id)??null,X||(Z=null),o.catalogsPanel.hidden=!1,vi()}function vi(){let e=!o.adminPanel.hidden;o.catalogsForm.hidden=!e;let t=ui.reduce((e,t)=>e+t.live,0),n=ui.reduce((e,t)=>e+t.vod,0);o.catalogsNote.textContent=ui.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${ui.length} ${ui.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,yi();let r=X!==null&&Z!==null;if(o.catalogsList.hidden=r,o.catalogsFilter.hidden=!r,o.catalogsEntries.hidden=!r,r){wi();return}if(X){xi(X);return}s(o.catalogsList,...ui.map(t=>bi(t,e)))}function yi(){let e=X!==null;if(o.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>{X=null,Z=null,vi()},!1),n(),t(X?.name??``,()=>{Z=null,vi()},Z===null)];Z!==null&&r.push(n(),t(Z===``?`All groups`:Z,()=>void 0,!0)),o.catalogsCrumbs.replaceChildren(...r)}function bi(e,t){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);if(a.className=`detail`,a.textContent=[`${e.entries.toLocaleString()} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString()} live`,`${e.vod.toLocaleString()} on demand`,`refreshed ${gi(e.refreshedAt)}`].join(` · `),r.append(i,a),t&&e.error){let t=document.createElement(`span`);t.className=`detail`,t.textContent=e.error,r.append(t)}let o=document.createElement(`button`);if(o.type=`button`,o.className=`button`,o.textContent=`Browse`,o.addEventListener(`click`,()=>{X=e,Z=null,vi()}),n.append(r,o),t){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Refresh`,t.title=`Read the list again`,t.addEventListener(`click`,()=>{Ei(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Remove`,r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Di(e)}),n.append(t,r)}return n}async function xi(e){s(o.catalogsList);let t=[];try{let n=await T(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`)));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{S=`Could not read the groups in ${e.name}.`,z();return}if(X?.id!==e.id||Z!==null)return;let n=[Si(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>Si(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];s(o.catalogsList,...n)}function Si(e,t,n,r,i){let a=document.createElement(`li`),s=document.createElement(`span`);s.className=`server-label`;let c=document.createElement(`span`);c.className=`name`,c.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${n.toLocaleString()} · ${r.toLocaleString()} live · ${i.toLocaleString()} on demand`,s.append(c,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{Z=t,di=``,o.catalogsFilter.value=``,fi=[],pi=0,vi(),Ci(0)}),a.append(s,u),a}async function Ci(e){let t=X,n=Z;if(!t||n===null)return;let r=++hi,i=new URLSearchParams({group:n,q:di,offset:String(e),limit:String(li)}),a;try{let e=await T(()=>fetch(I.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`)));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{S=`Could not read ${t.name}.`,z();return}r===hi&&(pi=a.total??0,fi=e===0?a.entries??[]:[...fi,...a.entries??[]],wi())}function wi(){let t=X;if(!t)return;let n=fi.map(n=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`name`,i.textContent=n.title;let a=document.createElement(`span`);if(a.className=n.live?`catalog-tag catalog-live`:`catalog-tag`,a.textContent=n.live?`LIVE`:n.duration>0?e(n.duration):`VOD`,r.append(i,a),!n.live){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,d(e,`copy`),e.title=`Copy this entry's URL`,e.setAttribute(`aria-label`,`Copy the URL of ${n.title}`),e.addEventListener(`click`,r=>{r.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(t.id)}/entries/${encodeURIComponent(n.id)}/stream`;Aa(I.url(i),e,`✓`)}),r.append(e)}return Bt()&&r.append(Gt(()=>({kind:`entry`,catalog:{id:t.id,name:t.name},entry:n}),n.title)),r.addEventListener(`click`,()=>{Ti(t,n,r)}),r});if(fi.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=di?`Nothing called "${di}" here.`:`Nothing in this group.`,e.append(t),n.push(e)}else if(fi.length<pi){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${fi.length.toLocaleString()} of ${pi.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),Ci(fi.length)}),e.append(t),n.push(e)}s(o.catalogsEntries,...n)}async function Ti(e,t,n){n?.classList.add(`loading`),S=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await T(async()=>{let n,i={};try{n=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{S=`could not reach the server`;return}if(!n.ok){S=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await wa({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){w=null,C=-1,E={kind:`vod`,...r},et(a,`title`),await F.load({title:a,artist:``,album:``,duration:0,url:I.url(i.url),video:!0,objectUrl:!1},!0),Cn(!0),S=`Playing ${a}.`;return}S=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),z()}}async function Ei(e){V(`Reading ${e.name} again…`);try{let t=await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));V(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{V(`could not reach the server`)}_i()}async function Di(e){try{V((await fetch(I.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{V(`could not reach the server`)}X?.id===e.id&&(X=null,Z=null),_i()}o.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.catalogSource.value.trim(),n=o.catalogName.value.trim();t&&(async()=>{V(`Reading ${n||t}…`);try{let e=await fetch(I.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){V(r.error??`that did not work`);return}V(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString()} entries.`),o.catalogSource.value=``,o.catalogName.value=``}catch{V(`could not reach the server`)}_i()})()}),o.catalogsFilter.addEventListener(`input`,()=>{mi&&clearTimeout(mi),mi=setTimeout(()=>{mi=null,di=o.catalogsFilter.value.trim(),Ci(0)},250)});let Oi=async()=>{s(o.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){o.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ie=new Map(t.map(e=>[H(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),o.serversPanel.hidden=!1,o.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. Arriving signed in, this page connects to your default one, or the first that answers; a link you arrive with goes live there.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let a=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=oe({name:e.name,view:a,admin:a});De(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=Gi()===H(e.url),u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=l?`✓ Default`:`Make default`,u.title=l?`The server this page connects to when you arrive signed in. Press to go back to the first that answers.`:`Connect to this server whenever you arrive signed in`,u.addEventListener(`click`,()=>{Ki(l?``:H(e.url)),Oi()});let d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=`Forget`,d.addEventListener(`click`,()=>{(async()=>{d.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await Oi()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),o.serversList.append(t)}}catch{o.serversPanel.hidden=!0}},ki=async()=>{s(o.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){o.followingNote.hidden=!0;return}let t=(await e.json()).following??[];o.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let a=document.createElement(`button`);a.type=`button`,a.className=`ghost follow`,a.textContent=`Unfollow`,a.addEventListener(`click`,()=>{(async()=>{a.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),o.followingList.children.length===0&&(o.followingNote.hidden=!0)}finally{a.disabled=!1}})()}),t.append(n,a),o.followingList.append(t)}}catch{o.followingNote.hidden=!0}},Ai=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,n.textContent=`Follow`,n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{n.textContent=e?`Following`:`Follow`,n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),ki())}catch{}finally{n.disabled=!1}})()}),n},ji=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},Mi=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Ni=async()=>{if(!Mi())return o.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return o.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return o.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return o.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ji(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return o.notifyNote.textContent=`This device will be told.`,!0}catch{return o.notifyNote.textContent=`Could not set this device up.`,!1}},Pi=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},Fi=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();o.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(o.notifyPhone.value=n.phone)}catch{o.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Ii=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();o.notifyEmail.checked=t.wantsEmail!==!1,o.notifySms.checked=t.wantsSms===!0,o.notifyPhone.value=t.phone??``;let n=Mi()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;o.notifyWeb.checked=t.wantsWeb!==!1&&n,o.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};o.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(o.notifyWeb.checked){let e=await Ni();o.notifyWeb.checked=e,await Fi({wantsWeb:e});return}await Pi(),await Fi({wantsWeb:!1}),o.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),o.notifyEmail.addEventListener(`change`,()=>{Fi({wantsEmail:o.notifyEmail.checked})}),o.notifySms.addEventListener(`change`,()=>{(async()=>{if(o.notifySms.checked&&!o.notifyPhone.value.trim()){o.notifyPhoneNote.textContent=`Add a phone number first.`,o.notifySms.checked=!1;return}await Fi({wantsSms:o.notifySms.checked})})()}),o.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),Fi({phone:o.notifyPhone.value.trim()})});let Li=!1,Ri=!1,zi=`nixamp.welcome`,Bi=()=>{let e=!1;try{e=localStorage.getItem(zi)===`hidden`}catch{}o.welcome.hidden=!Ri||G!==``||e},Vi=e=>{let t=e!==null;br=``,K=null,t||(q=!1,o.transcriptAudio.checked=!1,J.disable(),jr()),ei(),o.notifyPanel.hidden=!t,t?(Ii(),ki(),Oi()):(o.serversPanel.hidden=!0,o.followingNote.hidden=!0,s(o.followingList),o.recentNote.hidden=!0,o.recentList.replaceChildren()),o.accountForm.hidden=t,o.accountProviders.hidden=t||o.accountProviders.childElementCount===0,o.accountSignOut.hidden=!t,o.personaForm.hidden=!t,o.personaNote.hidden=!t,t&&Xr(),o.accountNote.textContent=t?`Signed in as ${e}.`:Li?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,o.accountSubmit.textContent=Li?`Create account`:`Sign in`,o.accountToggle.textContent=Li?`I have one`:`Create one`,o.accountPassword.autocomplete=Li?`new-password`:`current-password`,Bi()},Hi=async()=>{let e=[];Ri=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Ri=!0,e=(await t.json()).providers??[])}catch{}o.accountProviders.replaceChildren(),o.accountProviders.hidden=e.length===0,o.accountPanel.hidden=!Ri,o.accountElsewhere.hidden=Ri,Bi();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,o.accountProviders.append(e)}},Ui=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();G=e.ok?t.account?.id??``:``,Vi(e.ok?t.account?.email??`you`:null)}catch{G=``,Vi(null)}if(I.session=``,G!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));I.session=e.ok&&typeof t.token==`string`?t.token:``}catch{I.session=``}p===`remote`&&Kn()}nr(),Qn(),$n(),qi();let e=await Wi();if(Ot!==``){let t=Ot;Ot=``,e?v=`golive:${t}`:Tn(t)}};async function Wi(){if(G===``||p===`remote`||Dt!==``)return!1;let e=[];try{let t=await fetch(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=Gi(),n=[...e].sort((e,n)=>Number(H(n.url)===t)-Number(H(e.url)===t));for(let e of n)if(await De(e.url,void 0,e.key)!==null)return p!==`remote`&&(ne=!1,v=``,o.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,S=`Connecting to ${e.name}, your server…`,z(),o.remoteForm.requestSubmit(),!0);return!1}function Gi(){try{return localStorage.getItem(Mt)??``}catch{return``}}function Ki(e){try{e===``?localStorage.removeItem(Mt):localStorage.setItem(Mt,e)}catch{}}function qi(){if(Dt===``)return;let e=Dt;Dt=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit()}o.accountToggle.addEventListener(`click`,()=>{Li=!Li,Vi(null)}),o.welcomeCreate.addEventListener(`click`,()=>{Li=!0,Vi(null),o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),o.accountEmail.focus({preventScroll:!0})}),o.welcomeBrowse.addEventListener(`click`,()=>{o.directory.hidden?o.browse.click():o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(zi,`hidden`)}catch{}o.welcome.hidden=!0}),o.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.accountEmail.value.trim(),n=o.accountPassword.value;(async()=>{o.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${Li?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){o.accountNote.textContent=r.error??`that did not work`;return}G=r.account?.id??``,o.accountPassword.value=``,Vi(r.account?.email??t),Kn(),qi()}catch{o.accountNote.textContent=`could not reach nixamp.com`}finally{o.accountSubmit.disabled=!1}})()}),o.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}G=``,Vi(null),I.close(),C=-1,p=`local`,x=`idle`,de=``,o.remoteUrl.value=``,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.catalogsPanel.hidden=!0,o.listenOnly.hidden=!0,ya(!1);try{localStorage.removeItem(jt)}catch{}S=`Signed out, and disconnected from the server.`,Kn(),z()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Dt=t,v=e.get(`play`)??``,re=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t,S=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(o.linkUrl.value=n,t!==``&&v===``?v=`link:${n}`:t===``&&(Ot=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=_e(r);t?(Dt=t.view,v=t.what,re=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t.view,S=`Opening the stream you were sent…`):(o.linkUrl.value=r,Ot=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Ji=[`zone-top`,`zone-main`],Yi=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Xi=e=>e.parentElement&&Ji.includes(e.parentElement.id)?e.parentElement:null,Zi=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Qi=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Yi(e)&&Xi(e)!==null),$i=e=>e.dataset.title??e.id,ea=new Map,ta=Qi().map((e,t)=>(ea.set(e.id,{zone:Xi(e)?.id??``,col:Zi(e),index:t}),e.id)),Q=Ze();try{Q=tt(localStorage.getItem(Xe))}catch{}let na=()=>Q.order.length>0||Object.keys(Q.placement).length>0;function ra(){Q.order=Qi().map(e=>e.id);try{localStorage.setItem(Xe,nt(Q))}catch{}}function ia(e,t,n){e.classList.remove(`col-a`,`col-b`),t.classList.contains(`split`)&&n!==``&&e.classList.add(`col-${n}`),t!==e.parentElement&&t.append(e)}function aa(){for(let e of Qi()){let t=Q.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Ji.includes(i.id)&&ia(e,i,r===`a`||r===`b`?r:``)}let e=rt(Qi().map(e=>e.id),Q.order);for(let t of Ji){let n=document.getElementById(t);if(!n)continue;let r=[...n.children].filter(Yi),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((t,n)=>e.indexOf(t.id)-e.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of Qi())e.toggleAttribute(`data-collapsed`,Q.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Q.closed.includes(e.id))}function oa(e,t){e.toggleAttribute(`data-collapsed`,t),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),Q.collapsed=it(Q.collapsed,e.id,t),ra(),pa()}function sa(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),t&&n&&o.panelsToggle.focus({preventScroll:!0}),Q.closed=it(Q.closed,e.id,t),ra(),pa()}function ca(e,t,n){let r=Xi(t);r&&e!==t&&(ia(e,r,Zi(t)),n?t.after(e):t.before(e),Q.placement[e.id]=`${r.id}:${Zi(t)}`,ra(),pa())}let la=null,ua=()=>{for(let e of Qi())e.classList.remove(`drop-before`,`drop-after`)},da=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon-btn`,r.textContent=e,r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,e=>{e.stopPropagation(),n()}),r};function fa(){for(let e of Qi()){let t=$i(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);if(n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n)),n.textContent!==t&&(n.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let r=document.createElement(`span`);r.className=`panel-tools`;let i=da(`≡`,`Move ${$i(e)}: Alt plus Up or Down, or drag`,()=>void 0);i.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=Qi().filter(t=>Xi(t)===Xi(e)&&Zi(t)===Zi(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(ca(e,r,t.key===`ArrowDown`),i.focus({preventScroll:!0}))}),i.classList.add(`grip`),i.draggable=!0,i.addEventListener(`dragstart`,t=>{la=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),i.addEventListener(`dragend`,()=>{la=null,e.classList.remove(`dragging`),ua()});let a=da(`▁`,`Shade ${$i(e)} to its title`,()=>oa(e,!e.hasAttribute(`data-collapsed`)));a.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let o=da(`✕`,`Hide ${$i(e)}; the Panels list turns it back on`,()=>sa(e,!0));r.append(i,a,o),e.prepend(r),e.addEventListener(`dragover`,t=>{if(!la||la===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;ua(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!la||la===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);ua(),ca(la,e,n)})}}function pa(){if(o.panelsPanel.hidden||o.panelsList.contains(document.activeElement))return;let e=Qi().filter(e=>e!==o.panelsPanel).map(e=>{let t=document.createElement(`li`),n=e.hasAttribute(`data-closed`);t.classList.toggle(`off`,n);let r=document.createElement(`label`),i=document.createElement(`input`);i.type=`checkbox`,i.checked=!n,i.setAttribute(`aria-label`,`${$i(e)} on`),i.addEventListener(`change`,()=>sa(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,a.textContent=$i(e),r.append(i,a);let o=document.createElement(`span`);return o.className=`detail`,o.textContent=n?`off`:e.hasAttribute(`data-collapsed`)?`shaded`:e.hidden?`nothing to show right now`:``,t.append(r,o),t});o.panelsList.replaceChildren(...e)}function ma(){Q=Ze();for(let e of ta){let t=document.getElementById(e),n=ea.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(ia(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Q.order=[...ta],aa(),Q=Ze();try{localStorage.removeItem(Xe)}catch{}pa()}function ha(e){if(!e||na())return;let t=Xi(o.adminPanel);if(!t)return;let n=[...t.children].filter(Yi).find(e=>Zi(e)===Zi(o.adminPanel));n&&n!==o.adminPanel&&n.before(o.adminPanel),o.adminPanel.removeAttribute(`data-collapsed`),o.adminPanel.removeAttribute(`data-closed`)}o.panelsToggle.addEventListener(`click`,()=>{let e=o.panelsPanel.hidden;o.panelsPanel.hidden=!e,o.panelsToggle.setAttribute(`aria-expanded`,String(e)),e&&(o.panelsPanel.hasAttribute(`data-closed`)&&sa(o.panelsPanel,!1),pa(),o.panelsPanel.scrollIntoView({behavior:`smooth`,block:`nearest`}))}),o.panelsReset.addEventListener(`click`,ma),new MutationObserver(()=>{fa(),pa()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),fa(),aa(),Hi(),Ui(),Kn(),jn(),o.browse.addEventListener(`click`,()=>{if(!o.directory.hidden){o.directory.hidden=!0;return}Ln(),o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.disconnect.addEventListener(`click`,()=>{I.close(),o.listenOnly.hidden=!0,C=-1,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.onairPanel.dataset.title=`Parties on this server`,o.catalogsPanel.hidden=!0,o.catalogsPanel.dataset.title=`Catalogs on this server`,m=``,se=``,ar(),ya(!1),p=`local`,x=`idle`,de=``,z()});async function ga(){if(p!==`remote`||I.shareLink===``){o.sharePanel.hidden=!0;return}o.sharePanel.hidden=!1;let e=Ma(),t=globalThis.location.origin;o.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,o.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,o.sharePhone.hidden=!0,o.shareSend.hidden=!0,o.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(I.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,se=r.url,o.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(bt=r.live,St=r.live?r.code:``,A=n,o.liveControls.hidden=o.adminPanel.hidden||!r.possible,o.goLive.hidden=r.live,o.stopLive.hidden=!r.live,o.sharePhone.hidden=!1,!r.live){o.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){o.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,o.shareSend.hidden=!1;return}o.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),Ra(n),document.createTextNode(` and key `),Ra(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),o.shareSend.hidden=!1}}let _a=``,va=null,ya=e=>{va&&clearInterval(va),va=null,e&&(va=setInterval(()=>void $(),6e3))};async function $(){if(p!==`remote`){o.onairPanel.hidden=!0;return}let e;try{let t=await fetch(I.url(`/api/streams`));if(!t.ok){o.onairPanel.hidden=!0;return}e=await t.json(),ee=e.server.carries!==!1,e.server.name&&e.server.name!==m&&(m=e.server.name,o.onairPanel.dataset.title=`Parties on ${m}`,o.catalogsPanel.dataset.title=`Catalogs on ${m}`,ar(),z())}catch{o.onairPanel.hidden=!0;return}o.onairPanel.hidden=!1,D=e,Na(e),z(),ba(e)}function ba(e){let t=qt(),n=`${o.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}:${t.fullTitle}:${t.position}`;if(n===_a)return;_a=n;let r=e.restreams??[],i=e.channels.length+r.length;o.onairNote.textContent=i===0?`One stream, from this server's own files.`:`${i+1} streams: this server's own files, and ${i} more on it.`;let a=[],l=e.server.playing,u=!o.adminPanel.hidden;a.push(Pa({title:e.server.name,detail:[l?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${c(e.server.nowPlaying)}`:`nothing loaded`,l&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:l?`Join party`:u?`Start the stream`:`Nothing playing`,onPlay:()=>{if(l){Ca(e.server.nowPlaying);return}u&&Sa()},link:e.server.live?e.server.url:``,...l?{page:ja(`live`)}:{},direct:l?I.url(`/api/live`):``}));for(let e of r)a.push(Pa({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{tn(e.at)},link:``,direct:I.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=I.url(`/api/channels/${encodeURIComponent(t.id)}`),r=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&r.push(`☎ ${t.code}`),t.redials&&r.push(`redialled ${t.redials}×`),u&&t.error&&r.push(t.error),a.push(Pa({title:t.name,detail:r.join(` · `),onPlay:()=>{wa({id:t.id,name:t.name,video:e,art:t.art})},link:n,page:ja(`channel:${t.id}`),direct:n,onRestart:u&&t.via===`pull`?()=>{Da(t.id,t.name)}:void 0,onStop:u||zt&&G!==``&&t.startedBy===G?()=>{ka(t.id,t.name)}:void 0,onRename:u||zt&&G!==``&&t.startedBy===G?()=>{Oa(t.id,t.name)}:void 0}))}s(o.onairList,...a)}async function xa(){if(p===`remote`)try{if((await fetch(I.media(L(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;S=G===``?`This stream is busy enough to be charging for. Sign in to nixamp.com to pay for a pass.`:`This stream is charging for a pass. Follow the payment prompt to keep listening.`,G===``&&o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),z()}catch{}}async function Sa(){V(`Starting the stream on the server…`);try{await I.send({type:`play`,index:Math.max(0,L())})}catch{V(`could not reach the server`);return}await Ca(b.tracks[L()]?.title??``),V(`Playing to the room. Anybody with the view link sees this.`),await $()}async function Ca(e){C=-1,w=null,E={kind:`live`},et(e,`auto`),await T(()=>F.load({title:e||`Live`,artist:``,album:``,duration:0,url:I.url(`/api/live`),video:!0,objectUrl:!1},!0)),Cn(!0),S=`Watching what this server is playing. Everyone here sees the same thing.`,z()}async function wa(e,t=!0,n){C=-1,w=e,t&&(be=0),t&&(E=n??{kind:`channel`}),t&&et(e.name,E?.link||At(e.name)?`auto`:`channel`);let r=e.video&&Vt();await T(()=>F.load({title:e.name,artist:``,album:``,duration:0,url:I.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),Cn(e.video),w===e&&(S=`Watching ${e.name}, live on this server.`),z()}function Ta(){let e=w;return e?Tt?!0:be>=5?(S=`${e.name} stopped, and did not come back.`,w=null,E=null,z(),!0):(be+=1,S=`${e.name} started over; rejoining…`,z(),Tt=setTimeout(()=>{Tt=null,w===e&&wa(e,!1)},2e3),!0):!1}function Ea(e){o.onairNote.textContent=e,V(e)}async function Da(e,t){Ea(`Restarting ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));Ea(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{Ea(`could not reach the server`)}_a=``,$()}async function Oa(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){Ea(`Renaming ${t}…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));Ea(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{Ea(`could not reach the server`)}w?.id===e&&(w={...w,name:r}),_a=``,$(),z()}}async function ka(e,t){Ea(`Taking ${t} off the air…`);try{let n=await fetch(I.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));Ea(n.ok?`${t} is off the air.`:r.error??`that did not work`)}catch{Ea(`could not reach the server`)}w?.id===e&&(w=null,F.stop()),_a=``,$()}async function Aa(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{S=e,z();return}n===`✓`||n===`✓`?d(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function ja(e,t=0){let n=Ma();if(n===``)return``;let r=globalThis.location.origin,i=t>1?`&t=${Math.floor(t)}`:``;return`${r}/?url=${encodeURIComponent(n)}&play=${encodeURIComponent(e)}${i}`}function Ma(){if(se!==``)return se;let e=p===`remote`?I.shareLink:``;return/\/admin\//.test(e)?``:e}function Na(e){if(v===``)return;let t=v;if(t===`live`){v=``,e.server.playing?Ca(e.server.nowPlaying):(S=`Nothing is playing on this server right now.`,z());return}if(t.startsWith(`link:`)){v=``,Tn(t.slice(5));return}if(t.startsWith(`golive:`)){v=``,o.linkUrl.value=t.slice(7),Kn().then(()=>Mn());return}if(t.startsWith(`track:`)){v=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&tn(e);return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n)??e.channels.find(e=>e.name===n);r&&(v=``,wa({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Pa(e){let t=document.createElement(`li`);t.className=`onair`;let n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.title;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.detail,n.append(r,i);let a=document.createElement(`span`);a.className=`onair-actions`;let o=document.createElement(`button`);o.type=`button`,o.className=`button`,Wt(o,e.playLabel??`Join party`),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,d(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};return(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Aa(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Aa(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),t.append(n,a),t}let Fa=``;function Ia(e,t){Fa=e;let n=e!==``&&t===e;o.loadHome.hidden=e===``,o.homeNote.hidden=e===``,e!==``&&(o.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,o.loadHome.disabled=!1)}o.loadHome.addEventListener(`click`,()=>{Fa!==``&&(o.loadHome.disabled=!0,V(`Reading this server's files…`),(async()=>{try{let e=await fetch(I.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Fa})}),t=await e.json();V(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{V(`could not reach the server`)}finally{o.loadHome.disabled=!1}})())});let La=async e=>{o.goLive.disabled=!0,o.stopLive.disabled=!0,o.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(I.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();o.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{o.shareNote.textContent=`could not reach the server`}finally{o.goLive.disabled=!1,o.stopLive.disabled=!1,await ga()}};o.goLive.addEventListener(`click`,()=>void La(!0)),o.stopLive.addEventListener(`click`,()=>void La(!1));function Ra(e){let t=document.createElement(`b`);return t.textContent=e,t}o.shareCopy.addEventListener(`click`,()=>{o.shareLink.select(),navigator.clipboard?.writeText(o.shareLink.value).then(()=>{o.shareNote.textContent=`Copied. Send it to anybody.`},()=>{o.shareNote.textContent=`Copy it from the box above.`})}),o.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=o.shareTo.value.trim();t!==``&&(async()=>{o.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:Ma()})}),n=await e.json();o.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(o.shareTo.value=``)}catch{o.shareNote.textContent=`could not send that`}})()}),o.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(Pt,o.listenHere.checked?`1`:`0`)}catch{}p===`remote`&&(async()=>{o.listenHere.checked?(await I.send({type:`stop`}),await nn(b.index)):(F.stop(),C=-1),z()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)&&!t?.closest(`input, textarea, select, button, a, [contenteditable], [role=button]`)&&t===o.transport)switch(e.key){case` `:e.preventDefault(),rn();return;case`s`:on();return;case`n`:case`ArrowRight`:an(1);return;case`p`:case`ArrowLeft`:an(-1);return;case`ArrowDown`:e.preventDefault(),tn(Math.min(Kt()-1,L()+1));return;case`ArrowUp`:e.preventDefault(),tn(Math.max(0,L()-1));return}});let za=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),za=e,o.install.hidden=!1}),o.install.addEventListener(`click`,()=>{za?.prompt(),za=null,o.install.hidden=!0});try{let e=localStorage.getItem(Nt);e!==null&&(o.volume.value=String(Math.round(Number(e)*100)),F.volume=Number(e));let t=localStorage.getItem(jt);t&&(o.remoteUrl.value=t),localStorage.getItem(Pt)===`0`&&(o.listenHere.checked=!1)}catch{}(async()=>{if(o.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await De(e)===null)return;let t=await we(e);t&&t.trackCount!==0&&(o.remoteUrl.value=e,p=`remote`,S=``,I.connect(e),z())})(),(()=>{if(It||Dt!==``)return;let e=()=>F.source!==``||F.playing||ke()||w!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{It=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||n.play().catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,n.play().then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),z(),requestAnimationFrame(bn)}Lt(),a(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{m as t};