nixamp 0.28.20 → 0.28.22

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.
Files changed (25) hide show
  1. package/package.json +1 -1
  2. package/web/dist/assets/{ar-FVjXF4_7.js → ar-LBAMiBKG.js} +1 -1
  3. package/web/dist/assets/{cs-RXbm1qLv.js → cs-lQyYj1vj.js} +1 -1
  4. package/web/dist/assets/{da-BLmjhANY.js → da-ChU3Kuk-.js} +1 -1
  5. package/web/dist/assets/{de-Cd3K7kJv.js → de-GIUpioF8.js} +1 -1
  6. package/web/dist/assets/{es-DY32AqOJ.js → es-DYl1woBl.js} +1 -1
  7. package/web/dist/assets/{fi-wJnYNgmv.js → fi-DcCzuMch.js} +1 -1
  8. package/web/dist/assets/{fr-DNqJ2TL3.js → fr-BnBn3sQ4.js} +1 -1
  9. package/web/dist/assets/{hi-DDzGtRXm.js → hi-CPkGxMBI.js} +1 -1
  10. package/web/dist/assets/{hls-3VKVEQE3-Big9PkCO.js → hls-3VKVEQE3-9KD7WXBu.js} +1 -1
  11. package/web/dist/assets/{hu-BUPSUIN_.js → hu-CRU_GolZ.js} +1 -1
  12. package/web/dist/assets/{id-CjITaK-p.js → id-BGiv1VIV.js} +1 -1
  13. package/web/dist/assets/{index-DCtiSLJv.js → index-CIjrTF_y.js} +2 -2
  14. package/web/dist/assets/{index-CE3BbT3v.css → index-D9po3Yrm.css} +1 -1
  15. package/web/dist/assets/{it-BbHLp8RO.js → it-NO6gDgAq.js} +1 -1
  16. package/web/dist/assets/{mpegts-C1fiGex_.js → mpegts-CXRBPaQ2.js} +1 -1
  17. package/web/dist/assets/{mpegts-LO6RVLD6-BblchxBY.js → mpegts-LO6RVLD6-n4DFtkJH.js} +1 -1
  18. package/web/dist/assets/{nl-22UmcN_P.js → nl-Yn-CJ5On.js} +1 -1
  19. package/web/dist/assets/{ru-k5NwxG8b.js → ru-BK8Zz61e.js} +1 -1
  20. package/web/dist/assets/{sv-BwudEoV1.js → sv-D2DxEds9.js} +1 -1
  21. package/web/dist/assets/{uk-DLb_-XGO.js → uk-Dgdp-BEG.js} +1 -1
  22. package/web/dist/assets/{vi-C5uLjKB8.js → vi-BOgCl1aV.js} +1 -1
  23. package/web/dist/assets/{zh-CR8c8lCi.js → zh-DopV51uz.js} +1 -1
  24. package/web/dist/index.html +2 -2
  25. package/web/dist/sw.js +23 -23
@@ -1,3 +1,3 @@
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)}})();var e={"Supported platforms":`Supported platforms`,"In review":`In review`,"Not available":`Not available`,"Install PWA":`Install PWA`,"PWA installed":`PWA installed`,"Web app":`Web app`,"Install the web app":`Install the web app`,"Keep BackToSchool on your home screen or desktop. No app store needed.":`Keep BackToSchool on your home screen or desktop. No app store needed.`,"iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.":`iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.`,"Android: open your browser menu and choose Install app or Add to Home screen.":`Android: open your browser menu and choose Install app or Add to Home screen.`,"Desktop: look for Install in the address bar or browser menu. The option depends on your browser.":`Desktop: look for Install in the address bar or browser menu. The option depends on your browser.`,"You can also keep using BackToSchool in this browser.":`You can also keep using BackToSchool in this browser.`,"The web app is installed. You can keep learning here.":`The web app is installed. You can keep learning here.`,"Continue learning":`Continue learning`,"The install prompt could not open. Select Web app again for installation instructions.":`The install prompt could not open. Select Web app again for installation instructions.`,"Follow host":`Follow host`,Following:`Following`,"You’ll get email and web notifications for this host.":`You’ll get email and web notifications for this host.`,"Notifications turned off for this host.":`Notifications turned off for this host.`,"Could not update notifications.":`Could not update notifications.`},t={...e,"No parties live right now.":`No parties live right now.`,"Could not refresh parties.":`Could not refresh parties.`,"Pick a server in the directory, or paste its link here.":`Pick a server in the directory, or paste its link here.`,"Interface language":`Interface language`,Language:`Language`,"Translation language":`Translation language`,"Original (auto-detect)":`Original (auto-detect)`,Play:`Play`,Pause:`Pause`,Stop:`Stop`,Next:`Next`,Previous:`Previous`,Select:`Select`,"Next/Prev":`Next/Prev`,Quit:`Quit`,"Now Playing":`Now Playing`,"Spectrum Analyser":`Spectrum Analyser`,Playlist:`Playlist`,Files:`Files`,"Open files":`Open files`,"Open folder":`Open folder`,"Add to library":`Add to library`,"Replace playlist":`Replace playlist`,Filter:`Filter`,Search:`Search`,"Nothing loaded.":`Nothing loaded.`,"Empty.":`Empty.`,"Loading…":`Loading…`,"Connecting…":`Connecting…`,Connected:`Connected`,"Not connected":`Not connected`,"No source":`No source`,Playing:`Playing`,Stopped:`Stopped`,Volume:`Volume`,Seek:`Seek`,"Full screen":`Full screen`,Download:`Download`,Share:`Share`,Copy:`Copy`,"Copy link":`Copy link`,Copied:`Copied`,Save:`Save`,Cancel:`Cancel`,Close:`Close`,Remove:`Remove`,Delete:`Delete`,Edit:`Edit`,Add:`Add`,Send:`Send`,Retry:`Retry`,Back:`Back`,"Next page":`Next page`,"Previous page":`Previous page`,"Show more":`Show more`,Panels:`Panels`,"Reset layout":`Reset layout`,Show:`Show`,Hide:`Hide`,Collapse:`Collapse`,Expand:`Expand`,"Move up":`Move up`,"Move down":`Move down`,Install:`Install`,"TV mode":`TV mode`,On:`On`,Off:`Off`,Account:`Account`,"Sign in":`Sign in`,"Sign out":`Sign out`,"Create account":`Create account`,Email:`Email`,Password:`Password`,"Forgot password?":`Forgot password?`,"Welcome back":`Welcome back`,Profile:`Profile`,Handle:`Handle`,"Your servers":`Your servers`,Server:`Server`,Connect:`Connect`,Disconnect:`Disconnect`,Directory:`Directory`,Favourites:`Favourites`,Follow:`Follow`,Unfollow:`Unfollow`,Notifications:`Notifications`,"Phone number":`Phone number`,"Save number":`Save number`,Transcript:`Transcript`,Captions:`Captions`,"Translate audio":`Translate audio`,"Audio language":`Audio language`,"Audio options":`Audio options`,"Keep background sound":`Keep background sound`,"Background level":`Background level`,"Speaker voices":`Speaker voices`,"Any voice":`Any voice`,"Male voice":`Male voice`,"Female voice":`Female voice`,"Original audio.":`Original audio.`,"Buy translated audio":`Buy translated audio`,"Audio credit":`Audio credit`,"Buy pass":`Buy pass`,Pass:`Pass`,"Pay with":`Pay with`,"Check payment":`Check payment`,"Open checkout":`Open checkout`,"Free sessions":`Free sessions`,"Usage rates and expiry":`Usage rates and expiry`,Catalogs:`Catalogs`,"Add catalog":`Add catalog`,"Catalog name":`Catalog name`,Link:`Link`,"Play link":`Play link`,"Go live":`Go live`,Publish:`Publish`,Listen:`Listen`,"Live now":`Live now`,Upcoming:`Upcoming`,Parties:`Parties`,"Join party":`Join party`,"Invite code":`Invite code`,Invite:`Invite`,Chat:`Chat`,"Chat message":`Chat message`,People:`People`,Speaker:`Speaker`,Speakers:`Speakers`,Listener:`Listener`,Moderator:`Moderator`,"Raise hand":`Raise hand`,"Hand raises":`Hand raises`,Questions:`Questions`,Resources:`Resources`,Replay:`Replay`,Schedule:`Schedule`,Event:`Event`,Host:`Host`,About:`About`,Stage:`Stage`,Title:`Title`,Description:`Description`,Topic:`Topic`,Public:`Public`,"Anyone with the link":`Anyone with the link`,"Invited people":`Invited people`,"Who can join":`Who can join`,"Date and time":`Date and time`,"Expected length":`Expected length`,Repeat:`Repeat`,"Does not repeat":`Does not repeat`,"Every day":`Every day`,"Every week":`Every week`,Homepage:`Homepage`,"Host name":`Host name`,"Profile photo URL":`Profile photo URL`,"Broadcast link":`Broadcast link`,"Edit event":`Edit event`,"Save changes":`Save changes`,"Create live":`Create live`,"Schedule class":`Schedule class`,"Start class":`Start class`,"End event":`End event`,"End session":`End session`,"Session ended":`Session ended`,"Event ended":`Event ended`,Cancelled:`Cancelled`,"Replay available":`Replay available`,Join:`Join`,"Create invite":`Create invite`,"Invite as":`Invite as`,"Watch now":`Watch now`,"Start a room":`Start a room`,"Recent replays":`Recent replays`,"Your account":`Your account`,"Write with AI":`Write with AI`,"Suggested title":`Suggested title`,"Suggested description":`Suggested description`,"Suggested topic":`Suggested topic`,"Use these details":`Use these details`,"Learn something live.":`Learn something live.`,"Screen share":`Screen share`,"Upload and broadcast":`Upload and broadcast`,Help:`Help`,"Reload Player":`Reload Player`,"Copy Bundled CLI Path":`Copy Bundled CLI Path`,"Developer tools":`Developer tools`,Undo:`Undo`,Redo:`Redo`,Cut:`Cut`,Paste:`Paste`,"Select all":`Select all`,Status:`Status`,"Activity log":`Activity log`,Admin:`Admin`,"Playback controls":`Playback controls`,"Tracks and folders":`Tracks and folders`,"Original-language captions.":`Original-language captions.`,"Skip to playback controls":`Skip to playback controls`,"Skip to playlist":`Skip to playlist`,"Skip to transcript and translated audio":`Skip to transcript and translated audio`},n={"■ STOPPED":`Stopped`,"▶ PLAYING":`Playing`,LOADING:`Loading…`,"no source":`No source`,"not connected":`Not connected`,"Now playing":`Now Playing`,"● GO LIVE":`Go live`,"● Go live":`Go live`,"⤓ Download":`Download`,"A man's voice":`Male voice`,"A woman's voice":`Female voice`,"Catalogs on this server":`Catalogs`,"Catalog folders":`Catalogs`,"Parties on this server":`Parties`,"Servers streaming now":`Directory`,"Playlist (0)":`Playlist`,"Playlist folders":`Playlist`,"Playlist pages":`Playlist`,"Filter these files":`Filter`,"Filter these entries":`Filter`,"Filter the entries":`Filter`,"Filter the playlist":`Filter`,"Create a free account":`Create account`,"Create one":`Create account`,"Create your account":`Create account`,"New here? Create an account":`Create account`,"Already have an account? Sign in":`Sign in`,"Your NixAmp account":`Your account`,"Your public handle":`Handle`,handle:`Handle`,password:`Password`,"Phone number for texts":`Phone number`,"Back to the player":`Back`,"Share what is playing":`Share`,"Share this stream":`Share`,"Link to this stream":`Link`,"Copy this stream's URL":`Copy link`,"A link to play":`Link`,"A server's link":`Server`,"Close translated audio purchase":`Close`,"Open secure checkout ↗ (new tab)":`Open checkout`,"Checking…":`Loading…`,"Browse the directory":`Directory`,"See what is live":`Live now`,"Join live":`Join`,"Raise Hand":`Raise hand`,"Hand Raises":`Hand raises`,"Hide this":`Hide`,Log:`Activity log`,"Status:":`Status`,"Nixamp player":`Playback controls`,"Nixamp audio and video player":`Playback controls`,"What is being said":`Transcript`,"The room's chat":`Chat`,Trollbox:`Chat`,"A line for the trollbox":`Chat message`,"Say something to the room…":`Chat message`,"Send it":`Send`,"Something to add":`Chat message`,"What to call it":`Catalog name`,"call it something":`Catalog name`,"An m3u catalog to add":`Catalogs`,"On this device":`Play`,"Play on this device":`Play`,"What this is":`About`,"Looking for servers…":`Loading…`,"Finding today’s conversations…":`Loading…`,"Coming up":`Upcoming`,"Listen after class":`Replay`,"Schedule live":`Schedule class`,"Schedule a class":`Schedule class`,"Plan a conversation":`Schedule class`,"Your classroom":`Event`,"Join in":`Join`,"Open a room →":`Start a room`,"Chat message":`Chat message`,"Add to the conversation":`Chat message`,"Create live":`Create live`,"Host stage":`Stage`,"Your host":`Host`,"Class host":`Host`,"Hand raised ✓":`Raise hand`,"Copied ✓":`Copied`,"Screen share with Pairux ↗":`Screen share`,"Upload & broadcast in Nixamp ↗":`Upload and broadcast`,"Open Music Folder…":`Open folder`,"Choose a music folder":`Open folder`,"Main navigation":`Panels`,"Skip to a section":`Panels`},r=[{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`}],i=`nixamp.ui.language`;function a(e){let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code??`en`}function o(e,t=[]){let n=e=>{let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code};return n(e)??t.map(n).find(Boolean)??`en`}var s=`modulepreload`,c=function(e){return`/`+e},l={},u=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 u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=c(t,n),t=u(t),t in l)return;l[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`:s,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)})},d={en:async()=>({default:t}),de:()=>u(()=>import(`./de-Cd3K7kJv.js`),[]),sv:()=>u(()=>import(`./sv-BwudEoV1.js`),[]),es:()=>u(()=>import(`./es-DY32AqOJ.js`),[]),fr:()=>u(()=>import(`./fr-DNqJ2TL3.js`),[]),it:()=>u(()=>import(`./it-BbHLp8RO.js`),[]),nl:()=>u(()=>import(`./nl-22UmcN_P.js`),[]),da:()=>u(()=>import(`./da-BLmjhANY.js`),[]),fi:()=>u(()=>import(`./fi-wJnYNgmv.js`),[]),ru:()=>u(()=>import(`./ru-k5NwxG8b.js`),[]),uk:()=>u(()=>import(`./uk-DLb_-XGO.js`),[]),cs:()=>u(()=>import(`./cs-RXbm1qLv.js`),[]),hu:()=>u(()=>import(`./hu-BUPSUIN_.js`),[]),zh:()=>u(()=>import(`./zh-CR8c8lCi.js`),[]),ar:()=>u(()=>import(`./ar-FVjXF4_7.js`),[]),hi:()=>u(()=>import(`./hi-DDzGtRXm.js`),[]),vi:()=>u(()=>import(`./vi-C5uLjKB8.js`),[]),id:()=>u(()=>import(`./id-CjITaK-p.js`),[])},f=new class{load;code=`en`;get language(){return this.code}constructor(e=async e=>(await d[e]()).default){this.load=e}messages=t;revision=0;numberFormats=new Map;dateFormats=new Map;listeners=new Set;async setLanguage(e){let t=++this.revision,n=a(e),r=await this.load(n);if(t!==this.revision)return!1;this.code=n,this.messages=r,this.numberFormats.clear(),this.dateFormats.clear();for(let e of this.listeners)e();return!0}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}text(e,t={}){let r=this.language!==`en`&&Object.hasOwn(n,e)?n[e]:e,i=Object.hasOwn(this.messages,r)?this.messages[r]:e;return this.language!==`en`&&Object.hasOwn(n,e)&&(i=(e.match(/^[▶■●⤓]\s+/)?.[0]??``)+i+(e.endsWith(` ✓`)?` ✓`:``)),i.replace(/\{([\w]+)\}/g,(e,n)=>Object.hasOwn(t,n)?String(t[n]):e)}number(e,t){let n=JSON.stringify(t??{}),r=this.numberFormats.get(n);return r||(this.numberFormats.size>=64&&this.numberFormats.clear(),r=new Intl.NumberFormat(this.language,t),this.numberFormats.set(n,r)),r.format(e)}date(e,t){let n=JSON.stringify(t??{}),r=this.dateFormats.get(n);return r||(this.dateFormats.size>=64&&this.dateFormats.clear(),r=new Intl.DateTimeFormat(this.language,t),this.dateFormats.set(n,r)),r.format(e)}get direction(){return this.language===`ar`?`rtl`:`ltr`}},p=(e,t)=>f.text(e,t),m=new Map;function h(e,t,n){let r=m.get(e);r||(r=new Map,m.set(e,r)),r.set(t,n),n()}function g(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return h(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){m.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function _(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return h(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){m.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var v=[`aria-label`,`title`,`placeholder`,`data-title`],ee=[`[data-i18n]`,...v.map(e=>`[data-i18n-${e}]`)].join(`,`);function y(e){let t=[...e.querySelectorAll(ee)];e instanceof HTMLElement&&e.matches(ee)&&t.unshift(e);for(let e of t){if(e.closest(`[translate="no"], [contenteditable="true"]`))continue;let t=e.getAttribute(`data-i18n`);if(t){let n=e.textContent;h(e,`text`,()=>{if(e.textContent!==n){m.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=p(t),e.textContent!==n&&(e.textContent=n)})}for(let t of v){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);h(e,t,()=>{if(e.getAttribute(t)!==r){m.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=p(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function te(){document.documentElement.lang=f.language,document.documentElement.dir=f.direction;for(let[e,t]of m){if(!e.isConnected){m.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=f.language}var ne=0;async function re(e){let t=++ne;try{if(!await f.setLanguage(e)||t!==ne)return;try{localStorage.setItem(i,f.language)}catch{}window.nixampLanguage?.set(f.language).catch(()=>{})}catch{te()}}async function ie(){let e=o(null,navigator.languages);try{e=o(await window.nixampLanguage?.get()??localStorage.getItem(`nixamp.ui.language`),navigator.languages)}catch{}for(let e of document.querySelectorAll(`[data-ui-language]`))e.replaceChildren(...r.map(e=>{let t=new Option(e.label,e.code);return t.lang=e.code,t.dir=`auto`,t})),e.addEventListener(`change`,()=>{re(e.value)});y(document),te(),f.onChange(te),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&y(e);for(let e of m.keys())e.isConnected||m.delete(e)}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener(`storage`,e=>{e.key===`nixamp.ui.language`&&f.setLanguage(o(e.newValue,navigator.languages)).catch(()=>{})}),window.nixampLanguage?.subscribe(e=>{e!==f.language&&f.setLanguage(e).catch(()=>{})});try{await f.setLanguage(e)}catch{}}var ae={play:`<span aria-hidden="true">▶</span>`,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>`};function oe(e,t){e.innerHTML=ae[t]}function se(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 ce(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function b(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var le=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function x(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&le.has(e.slice(n+1).toLowerCase())}function ue(){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 S=new WeakMap;function de(e,t=!0){let n=e.contains(document.activeElement);S.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function C(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){S.delete(e),e.replaceChildren(...t);return}let n=S.has(e);if(S.set(e,t),n)return;let r=()=>{let t=S.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}S.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var w=new WeakMap,fe=new WeakSet;function pe(e,t){let n=new Map([...e.children].map(e=>[e.dataset.liveKey,e])),r=new Set(t.map(e=>e.dataset.liveKey)),i=!1;for(let r of t){let t=n.get(r.dataset.liveKey);t?t!==r&&!t.isEqualNode(r)&&(t.contains(document.activeElement)||t.querySelector(`details[open]`)?i=!0:t.replaceWith(r)):e.append(r)}for(let[e,t]of n)r.has(e)||(t.contains(document.activeElement)?i=!0:t.remove());if(i?w.set(e,t):w.delete(e),fe.has(e))return;fe.add(e);let a=()=>{let t=w.get(e);t&&pe(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function me(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 T(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 he(e,t,n=`Live`){let r=e[t];if(!r){let e=me(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${me(r.title)}`:me(r.title),a=T(r.folder??``),o=T(r.group??``).join(` › `),s=[...o?[o]:[],...a],c=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,l=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:c,position:`Playlist · ${l.findIndex(({at:e})=>e===t)+1} of ${l.length}`,fullTitle:c?`${c} › ${i}`:i}}var ge=[[/\.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`]],_e=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function E(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of _e)if(t.test(e.mimeType))return n}let t=ve(e.src);for(let[e,n]of ge)if(e.test(t))return n;return`unknown`}function ve(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function ye(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 be(e,t){let n=E(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 xe(e,t){let n=t.capabilities??ye(),r=be({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 u(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-Big9PkCO.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await u(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-BblchxBY.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await u(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 Se=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`]),Ce=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function D(e){let t=e.lastIndexOf(`.`);return t>0&&Ce.has(e.slice(t+1).toLowerCase())}function O(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&Se.has(e.slice(n+1).toLowerCase())}function we(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function Te(e){return e.filter(e=>O(e.name,e.type)).sort((e,t)=>we(Ee(e),Ee(t))).map(e=>({title:b(e.name),artist:``,album:De(Ee(e)),duration:0,url:URL.createObjectURL(e),video:x(e.name,e.type),objectUrl:!0,...D(e.name)?{kind:`mpegts`}:{}}))}function Ee(e){return e.webkitRelativePath||e.name}function De(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function Oe(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var k=2048;function A(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 ke(e,t){return e||t===`hls`||t===`mpegts`}var Ae=class{elements;handlers;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;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(je(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 jinglePlaying(){return!!this.jingle&&!this.jingle.paused&&!this.jingle.ended}async playJingle(e){this.jingle!==e&&this.stopJingle(),this.jingle=e,this.ensureGraph(e);try{if(await e.play(),this.context?.state===`suspended`)throw new DOMException(`Audio needs an interaction`,`NotAllowedError`)}catch(t){throw e.pause(),e.currentTime=0,t}}stopJingle(){this.jingle?.pause(),this.jingle=null}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=k,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.output.gain.value=+!this.translated,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.translated=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.stopJingle(),this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:E({src:e.url})),r=ke(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||A(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 xe(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:`)||A(a),t&&await this.play()}async play(){this.stopJingle(),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.stopJingle(),this.playBlocked=!1,this.active.pause()}async resumeAfterInteraction(){this.playBlocked?await this.play():this.playing&&this.context?.state===`suspended`&&await this.context.resume()}stop(){this.stopJingle(),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 je(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 Me(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function Ne(e,t){return{...t,tracks:t.tracks??e.tracks}}function Pe(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 Fe(e,t,n=``){let r=`${e===``?``:Pe(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function Ie(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 Le(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:Pe(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var Re=null;function ze(e){if(!e&&Re!==null)return Re;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||(Re=n),n}catch{return!1}}function Be(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return Fe(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function Ve(e){if(typeof e!=`object`||!e)return null;let t=e,n=Me(),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 He(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var Ue=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return He(this.base,e)}url(e){let t=Fe(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}=Le(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(Fe(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=Ve(We(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(Fe(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=Ve(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=ze()){return Be(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function We(e){try{return JSON.parse(e)}catch{return null}}async function Ge(e,t,n=``){try{let r=await fetch(Fe(e,`/api/state`,n),{signal:t});return r.ok?Ve(await r.json()):null}catch{return null}}function Ke(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 qe(e,t=``,n){let r;try{r=await fetch(Fe(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 Je(e,t,n=``){try{let r=await fetch(Fe(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 Ye(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 Xe=.14,Ze=.02;function Qe(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 $e(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 et(e,t,n=Xe){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function tt(e,t,n=Ze){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function nt(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 rt(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 it(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function at(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??f.language,i)===r.toLocaleDateString(t.locale??f.language,i);return n.toLocaleString(t.locale??f.language,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function ot(e,t={}){let n=e.data,r=rt(n.away,n.awayScore),i=rt(n.home,n.homeScore),a=it(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=at(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 st=`nixamp.tv`,j=/\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 ct(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?lt(r):/\bSilk\b/.test(e)&&n===0?!0:j.test(e):lt(i)}function lt(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function ut(e){return e?12:100}function dt(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 ft=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,M=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,pt=/\.m3u8(\?.*)?$/i,mt=/\.(m3u|pls)(\?.*)?$/i;function ht(e){try{let t=new URL(e);return M.test(t.pathname+t.search)}catch{return!1}}function gt(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 _t(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||gt(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(!ft.test(a)&&!M.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 vt(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 yt(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=vt(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 mt.test(o)?{kind:`list`,url:n.toString(),label:gt(n.toString())}:ft.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:M.test(o)||pt.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var bt=`nixamp.panels`;function xt(){return{order:[],placement:{},collapsed:[],closed:[]}}var St=/^[a-z][a-z0-9-]{0,63}$/,Ct=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function wt(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&St.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function Tt(e){if(!e)return xt();let t;try{t=JSON.parse(e)}catch{return xt()}if(!t||typeof t!=`object`||Array.isArray(t))return xt();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))St.test(e)&&typeof t==`string`&&Ct.test(t)&&(r[e]=t);let i=e=>{let t=wt(e),n=t.includes(`parties-panel`)?t.filter(e=>e!==`onair-panel`):t;return[...new Set(n.map(e=>e===`onair-panel`?`parties-panel`:e))]};return!r[`parties-panel`]&&r[`onair-panel`]&&(r[`parties-panel`]=r[`onair-panel`]),delete r[`onair-panel`],{order:i(n.order),placement:r,collapsed:i(n.collapsed),closed:i(n.closed)}}function Et(e){return JSON.stringify(e)}function Dt(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 Ot(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function kt(e,t=16e3){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}var At=16e3,jt=3e4;function Mt(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function Nt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var Pt=`nixamp.captions`,Ft=`nixamp.captions.native-v2.language`,It=[{code:``,label:`Original (auto-detect)`},...r];function Lt(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return It.some(e=>e.code===t)?t:``}catch{return``}}function Rt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function zt(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function Bt(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 Vt(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 Ht(e){try{return e(Pt)!==`off`}catch{return!0}}function Ut(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Wt(e){let t=e?.status;return typeof t==`number`?[408,502,503,504].includes(t):e instanceof TypeError||e instanceof Error&&[`AbortError`,`TimeoutError`].includes(e.name)}function N(e,t){return Object.assign(Error(e),{status:t})}var Gt=12e3,Kt=class{options;context=null;gain=null;enabled=!1;generation=0;running=null;controller=null;next=[];sources=new Set;scheduledUntil=0;failures=0;seen=new Set;constructor(e){this.options=e}async enable(){this.enabled=!0,this.options.active(!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(),this.failures=0;for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.scheduledUntil=0,this.options.active(this.enabled)}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=[...this.next.filter(e=>!this.stale(e.line,e.lag)),...t].slice(-24),this.running===null&&this.run(this.generation))}stale(e,t){return(this.options.now?.()??Date.now())-t-e.until>Gt}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;){if(await this.waitForRoom(e,3),e!==this.generation)return;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 i=new Headers(t.init?.headers);if(new Headers(await this.options.authorization?.(n.signal,t.line)).forEach((e,t)=>i.set(t,e)),e!==this.generation)return;let a=await(this.options.fetcher??fetch)(t.url,{...t.init,signal:n.signal,headers:i});if(clearTimeout(r),e!==this.generation){await a.body?.cancel();return}if(!a.ok)throw N((await a.json().catch(()=>({}))).error||`Translated audio is unavailable.`,a.status);if(!a.body||!a.headers.get(`content-type`)?.startsWith(`audio/pcm`))throw Error(`The server returned no voice audio.`);let o=a.body.getReader(),s=new Uint8Array,c=0;try{for(;;){let t,{done:r,value:i}=await Promise.race([o.read(),new Promise((e,r)=>{t=setTimeout(()=>{n.abort(),o.cancel().catch(()=>{}),r(new DOMException(`Voice connection timed out`,`TimeoutError`))},12e3)})]).finally(()=>clearTimeout(t));if(e!==this.generation){await o.cancel();return}if(r)break;let a=new Uint8Array(s.length+i.length);a.set(s),a.set(i,s.length);let l=a.length-a.length%2;s=a.slice(l);for(let t=0;t<l;t+=6400){if(await this.waitForRoom(e,8),e!==this.generation){await o.cancel();return}let n=a.subarray(t,Math.min(l,t+6400));this.schedule(n),c+=n.length}}}finally{o.releaseLock()}if(!c||s.length)throw N(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!Wt(t)||++this.failures>=3)throw t;this.options.status(`Voice interrupted · waiting for the next translated phrase…`)}finally{clearTimeout(r)}}}catch(t){e===this.generation&&this.fail(t instanceof Error?t.message:`Translated audio stopped.`)}finally{this.running===e&&(this.running=null)}}async waitForRoom(e,t){for(;e===this.generation&&this.context&&this.scheduledUntil-this.context.currentTime>t;)if(await new Promise(e=>setTimeout(e,25)),!this.options.playing()){this.reset();return}}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.status(`Playing translated audio · a few seconds behind the video`)}},P=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,F=new WeakMap,qt=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t,n=5){this.stop();let r=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(F.has(e)||F.set(e,e.audioWorklet.addModule(P).catch(t=>{throw F.delete(e),t})),await F.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=i;let a=e.createGain();a.gain.value=0,t.connect(i),i.connect(a),a.connect(e.destination);let o=new Float32Array(e.sampleRate*n),s=0,c=new Float32Array,l=Date.now();i.port.onmessage=t=>{if(r!==this.generation)return;let i=0,a=t.data;for(;i<a.length;){let t=Math.min(o.length-s,a.length-i);if(o.set(a.subarray(i,i+t),s),s+=t,i+=t,s!==o.length)continue;let r=new Float32Array(16e3*n),u=e.sampleRate/16e3;for(let e=0;e<r.length;e++){let t=Math.floor(e*u),n=Math.max(t+1,Math.floor((e+1)*u)),i=0;for(let e=t;e<n;e++)i+=o[e]??0;r[e]=i/(n-t)}l+=n*1e3,Math.abs(Date.now()-l)>1500&&(l=Date.now(),c=new Float32Array);let d=new Float32Array(c.length+r.length);d.set(c),d.set(r,c.length),this.take({samples:d,at:l-d.length/16,until:l,freshAt:l-n*1e3}),c=d.slice(-32e3*n),s=0}},this.disconnect=()=>{i.port.onmessage=null,i.port.close(),t.disconnect(i),i.disconnect(),a.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},I=3,Jt=1,Yt=class e{failed;options;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;level=1;static loaded=new WeakMap;constructor(e,t={}){this.failed=e,this.options=t}async start(t,n){this.stop();let r=this.generation;try{if(this.options.process===!1){if(r!==this.generation)return!1;let e=t.createGain();return this.gain=e,e.gain.value=this.on?this.level*Jt:0,this.input=n,n.connect(e),e.connect(t.destination),!0}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,LyogQXVkaW8gdHJhbnNwb3J0IG9ubHk6IG5ldXJhbCBpbmZlcmVuY2UgcnVucyBpbiBhIGRlZGljYXRlZCB3b3JrZXIuIEEgYnJpZWYKICogc3RhbGwgZHJvcHMgc3RhbGUgZnJhbWVzIGFuZCByZWNvdmVyczsgaXQgbXVzdCBub3QgcGVybWFuZW50bHkgbXV0ZSBhbWJpZW5jZS4KICogTmV2ZXIgYnlwYXNzIHRvIHJhdyBpbnB1dCwgd2hpY2ggd291bGQgcmVzdG9yZSB0aGUgb3JpZ2luYWwgZGlhbG9ndWUuICovCmNvbnN0IEhPUCA9IDUxMjsKY29uc3QgTUFYX1BFTkRJTkcgPSAzMjsgLy8gQm91bmQgd29yayB0byBhYm91dCAzNDAgbXMgYXQgNDgga0h6Lgpjb25zdCBNQVhfQUdFID0gMTI7IC8vIEtlZXAgYXVkaWJsZSBhbWJpZW5jZSB3aXRoaW4gYWJvdXQgMTMwIG1zIG9mIHRoZSBzb3VyY2UuCmNvbnN0IFBSRUJVRkZFUiA9IDQ7CmNsYXNzIEJhY2tncm91bmRUcmFuc3BvcnQgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogIGNvbnN0cnVjdG9yKCkgewogICAgc3VwZXIoKTsKICAgIHRoaXMuY2hhbm5lbCA9IG51bGw7IHRoaXMuYWxpdmUgPSB0cnVlOyB0aGlzLnJlYWR5ID0gZmFsc2U7CiAgICB0aGlzLmlucHV0cyA9IFtdOwogICAgdGhpcy53cml0dGVuID0gMDsgdGhpcy5pZCA9IDA7IHRoaXMuaW5mbGlnaHQgPSAwOwogICAgdGhpcy5xdWV1ZSA9IFtdOyB0aGlzLm91dHB1dCA9IG51bGw7IHRoaXMucmVhZCA9IDA7CiAgICB0aGlzLnBvcnQub25tZXNzYWdlID0gZXZlbnQgPT4gewogICAgICBpZiAoZXZlbnQuZGF0YS5zdG9wKSB7IHRoaXMuYWxpdmUgPSBmYWxzZTsgdGhpcy5jaGFubmVsPy5jbG9zZSgpOyByZXR1cm47IH0KICAgICAgdGhpcy5jaGFubmVsID0gZXZlbnQuZGF0YS5wb3J0OwogICAgICB0aGlzLmNoYW5uZWwub25tZXNzYWdlID0gcmVzdWx0ID0+IHsKICAgICAgICBpZiAoIXRoaXMuYWxpdmUpIHJldHVybjsKICAgICAgICB0aGlzLmluZmxpZ2h0LS07CiAgICAgICAgY29uc3QgZnJhbWUgPSByZXN1bHQuZGF0YTsKICAgICAgICBpZiAoIU51bWJlci5pc1NhZmVJbnRlZ2VyKGZyYW1lLmlkKSB8fCAhQXJyYXkuaXNBcnJheShmcmFtZS5jaGFubmVscykgfHwgZnJhbWUuY2hhbm5lbHMubGVuZ3RoICE9PSAyCiAgICAgICAgICAgIHx8IGZyYW1lLmNoYW5uZWxzLnNvbWUoY2hhbm5lbCA9PiAhKGNoYW5uZWwgaW5zdGFuY2VvZiBGbG9hdDMyQXJyYXkpIHx8IGNoYW5uZWwubGVuZ3RoICE9PSBIT1ApKSB7IHRoaXMuZmFpbCgpOyByZXR1cm47IH0KICAgICAgICAvLyBMYXRlIGJhY2tncm91bmQgaXMgYXMgZGlzdHJhY3RpbmcgYXMgbWlzc2luZyBiYWNrZ3JvdW5kLiBEaXNjYXJkIGl0CiAgICAgICAgLy8gd2hpbGUga2VlcGluZyB0aGUgd29ya2VyIGFsaXZlIHRvIGhhbmRsZSB0aGUgbmV4dCBjdXJyZW50IGZyYW1lLgogICAgICAgIGlmIChmcmFtZS5pZCA8IHRoaXMuaWQgLSBNQVhfQUdFKSByZXR1cm47CiAgICAgICAgaWYgKHRoaXMucXVldWUubGVuZ3RoID49IE1BWF9QRU5ESU5HKSB0aGlzLnF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgdGhpcy5xdWV1ZS5wdXNoKGZyYW1lKTsKICAgICAgICBpZiAodGhpcy5xdWV1ZS5sZW5ndGggPj0gUFJFQlVGRkVSKSB0aGlzLnJlYWR5ID0gdHJ1ZTsKICAgICAgfTsKICAgICAgdGhpcy5jaGFubmVsLnN0YXJ0KCk7CiAgICB9OwogIH0KICBmYWlsKCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyBlcnJvcjogdHJ1ZSB9KTsgfQogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzKSB7CiAgICBjb25zdCBvdXQgPSBvdXRwdXRzWzBdOwogICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm4gZmFsc2U7CiAgICBjb25zdCBpbnB1dCA9IGlucHV0c1swXTsKICAgIGlmICghaW5wdXQ/LlswXSB8fCAhdGhpcy5jaGFubmVsKSByZXR1cm4gdHJ1ZTsKICAgIGlmICghWzEsIDIsIDQsIDYsIDhdLmluY2x1ZGVzKGlucHV0Lmxlbmd0aCkpIHsgdGhpcy5mYWlsKCk7IHJldHVybiBmYWxzZTsgfQogICAgaWYgKHRoaXMuaW5wdXRzLmxlbmd0aCAhPT0gaW5wdXQubGVuZ3RoKSB7CiAgICAgIGlmICh0aGlzLmlucHV0cy5sZW5ndGgpIHRoaXMuaWQrKzsgLy8gRGlzY2FyZCBhIHBhcnRpYWwgZnJhbWUgb24gYSBsYXlvdXQgY2hhbmdlLgogICAgICB0aGlzLmlucHV0cyA9IGlucHV0Lm1hcCgoKSA9PiBuZXcgRmxvYXQzMkFycmF5KEhPUCkpOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgY29uc3QgY291bnQgPSBpbnB1dFswXS5sZW5ndGg7CiAgICBmb3IgKGxldCBjaGFubmVsID0gMDsgY2hhbm5lbCA8IGlucHV0Lmxlbmd0aDsgY2hhbm5lbCsrKSB0aGlzLmlucHV0c1tjaGFubmVsXS5zZXQoaW5wdXRbY2hhbm5lbF0sIHRoaXMud3JpdHRlbik7CiAgICB0aGlzLndyaXR0ZW4gKz0gY291bnQ7CiAgICBpZiAodGhpcy53cml0dGVuID09PSBIT1ApIHsKICAgICAgaWYgKHRoaXMuaW5mbGlnaHQgPCBNQVhfUEVORElORykgewogICAgICAgIGNvbnN0IGNoYW5uZWxzID0gdGhpcy5pbnB1dHM7IHRoaXMuaW5mbGlnaHQrKzsKICAgICAgICB0aGlzLmNoYW5uZWwucG9zdE1lc3NhZ2UoeyBpZDogdGhpcy5pZCwgY2hhbm5lbHMgfSwgY2hhbm5lbHMubWFwKG9uZSA9PiBvbmUuYnVmZmVyKSk7CiAgICAgICAgdGhpcy5pbnB1dHMgPSBpbnB1dC5tYXAoKCkgPT4gbmV3IEZsb2F0MzJBcnJheShIT1ApKTsKICAgICAgfQogICAgICAvLyBTa2lwIGV4Y2VzcyB3b3JrIGluc3RlYWQgb2YgYnVpbGRpbmcgYSBiYWNrbG9nIG9yIGtpbGxpbmcgdGhlIGJyYW5jaC4KICAgICAgdGhpcy5pZCsrOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgaWYgKCF0aGlzLnJlYWR5KSByZXR1cm4gdHJ1ZTsKICAgIGlmICghdGhpcy5vdXRwdXQgfHwgdGhpcy5yZWFkID09PSBIT1ApIHsKICAgICAgd2hpbGUgKHRoaXMucXVldWUubGVuZ3RoICYmIHRoaXMucXVldWVbMF0uaWQgPCB0aGlzLmlkIC0gTUFYX0FHRSkgdGhpcy5xdWV1ZS5zaGlmdCgpOwogICAgICB0aGlzLm91dHB1dCA9IHRoaXMucXVldWUuc2hpZnQoKT8uY2hhbm5lbHMgPz8gbnVsbDsgdGhpcy5yZWFkID0gMDsKICAgIH0KICAgIGlmICghdGhpcy5vdXRwdXQpIHsgdGhpcy5yZWFkeSA9IGZhbHNlOyByZXR1cm4gdHJ1ZTsgfQogICAgZm9yIChsZXQgY2hhbm5lbCA9IDA7IGNoYW5uZWwgPCBvdXQubGVuZ3RoOyBjaGFubmVsKyspIG91dFtjaGFubmVsXS5zZXQodGhpcy5vdXRwdXRbY2hhbm5lbF0uc3ViYXJyYXkodGhpcy5yZWFkLCB0aGlzLnJlYWQgKyBjb3VudCkpOwogICAgdGhpcy5yZWFkICs9IGNvdW50OwogICAgcmV0dXJuIHRydWU7CiAgfQp9CnJlZ2lzdGVyUHJvY2Vzc29yKCJuaXhhbXAtYmFja2dyb3VuZCIsIEJhY2tncm91bmRUcmFuc3BvcnQpOwo=`,``+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-Hz7oaQ8X.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],channelCount:8,channelCountMode:`clamped-max`,channelInterpretation:`speakers`});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.level*I:0,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?this.level*(this.options.process===!1?Jt:I):0)}setLevel(e){Number.isFinite(e)&&(this.level=Math.max(0,Math.min(2,e)),this.gain&&(this.gain.gain.value=this.on?this.level*(this.options.process===!1?Jt:I):0))}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()}if(!this.node&&this.input&&this.gain)try{this.input.disconnect(this.gain)}catch{}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},Xt=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t){this.stop();let n=new AbortController;this.controller=n;let r=async()=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e3),a=await(this.options.fetcher??fetch)(`/api/v1/speech/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,language:t}),signal:AbortSignal.any([n.signal,r.signal])}).finally(()=>clearTimeout(i));if(!a.ok||!a.body)throw N((await a.json().catch(()=>({}))).error||`Live translation is unavailable.`,a.status);return a.body},i=await r();if(this.controller!==n){await i.cancel();return}this.consume(i,n,r)}clearClips(){for(let e of this.clips.values())if(!e.ended)try{e.controller.error(new DOMException(`Playback stopped`,`AbortError`))}catch{}this.clips.clear()}stop(){this.controller?.abort(),this.controller=null,this.clearClips()}audio(e){let t=this.clips.get(e);if(!t||t.taken)throw N(`The live audio segment expired. Catching up…`,503);return t.taken=!0,new Response(t.stream,{headers:{"content-type":`audio/pcm`}})}async consume(e,t,n){let r=0;for(;!t.signal.aborted;){let i=Date.now();try{await this.read(e,t);return}catch(a){if(t.signal.aborted||this.controller!==t)return;Date.now()-i>6e4&&(r=0),this.options.reconnecting?.(),this.clearClips();let o=a;for(;!t.signal.aborted;){if(!Wt(o)||r>=5){this.stop(),this.options.failed(o instanceof Error?o.message:`Live audio was interrupted.`);return}if(this.options.status(`Live audio disconnected · reconnecting…`),await new Promise(e=>{let n=()=>{clearTimeout(i),t.signal.removeEventListener(`abort`,n),e()},i=setTimeout(n,500*2**r++);t.signal.addEventListener(`abort`,n,{once:!0})}),t.signal.aborted)return;try{e=await n();break}catch(e){o=e}}}}}async read(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t.signal.addEventListener(`abort`,a,{once:!0});try{for(;!t.signal.aborted;){let e,{done:o,value:s}=await Promise.race([n.read(),new Promise((t,n)=>{e=setTimeout(()=>{n(N(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw N(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
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)}})();var e={"Supported platforms":`Supported platforms`,"In review":`In review`,"Not available":`Not available`,"Install PWA":`Install PWA`,"PWA installed":`PWA installed`,"Web app":`Web app`,"Install the web app":`Install the web app`,"Keep BackToSchool on your home screen or desktop. No app store needed.":`Keep BackToSchool on your home screen or desktop. No app store needed.`,"iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.":`iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.`,"Android: open your browser menu and choose Install app or Add to Home screen.":`Android: open your browser menu and choose Install app or Add to Home screen.`,"Desktop: look for Install in the address bar or browser menu. The option depends on your browser.":`Desktop: look for Install in the address bar or browser menu. The option depends on your browser.`,"You can also keep using BackToSchool in this browser.":`You can also keep using BackToSchool in this browser.`,"The web app is installed. You can keep learning here.":`The web app is installed. You can keep learning here.`,"Continue learning":`Continue learning`,"The install prompt could not open. Select Web app again for installation instructions.":`The install prompt could not open. Select Web app again for installation instructions.`,"Follow host":`Follow host`,Following:`Following`,"You’ll get email and web notifications for this host.":`You’ll get email and web notifications for this host.`,"Notifications turned off for this host.":`Notifications turned off for this host.`,"Could not update notifications.":`Could not update notifications.`},t={...e,"No parties live right now.":`No parties live right now.`,"Could not refresh parties.":`Could not refresh parties.`,"Pick a server in the directory, or paste its link here.":`Pick a server in the directory, or paste its link here.`,"Interface language":`Interface language`,Language:`Language`,"Translation language":`Translation language`,"Original (auto-detect)":`Original (auto-detect)`,Play:`Play`,Pause:`Pause`,Stop:`Stop`,Next:`Next`,Previous:`Previous`,Select:`Select`,"Next/Prev":`Next/Prev`,Quit:`Quit`,"Now Playing":`Now Playing`,"Spectrum Analyser":`Spectrum Analyser`,Playlist:`Playlist`,Files:`Files`,"Open files":`Open files`,"Open folder":`Open folder`,"Add to library":`Add to library`,"Replace playlist":`Replace playlist`,Filter:`Filter`,Search:`Search`,"Nothing loaded.":`Nothing loaded.`,"Empty.":`Empty.`,"Loading…":`Loading…`,"Connecting…":`Connecting…`,Connected:`Connected`,"Not connected":`Not connected`,"No source":`No source`,Playing:`Playing`,Stopped:`Stopped`,Volume:`Volume`,Seek:`Seek`,"Full screen":`Full screen`,Download:`Download`,Share:`Share`,Copy:`Copy`,"Copy link":`Copy link`,Copied:`Copied`,Save:`Save`,Cancel:`Cancel`,Close:`Close`,Remove:`Remove`,Delete:`Delete`,Edit:`Edit`,Add:`Add`,Send:`Send`,Retry:`Retry`,Back:`Back`,"Next page":`Next page`,"Previous page":`Previous page`,"Show more":`Show more`,Panels:`Panels`,"Reset layout":`Reset layout`,Show:`Show`,Hide:`Hide`,Collapse:`Collapse`,Expand:`Expand`,"Move up":`Move up`,"Move down":`Move down`,Install:`Install`,"TV mode":`TV mode`,On:`On`,Off:`Off`,Account:`Account`,"Sign in":`Sign in`,"Sign out":`Sign out`,"Create account":`Create account`,Email:`Email`,Password:`Password`,"Forgot password?":`Forgot password?`,"Welcome back":`Welcome back`,Profile:`Profile`,Handle:`Handle`,"Your servers":`Your servers`,Server:`Server`,Connect:`Connect`,Disconnect:`Disconnect`,Directory:`Directory`,Favourites:`Favourites`,Follow:`Follow`,Unfollow:`Unfollow`,Notifications:`Notifications`,"Phone number":`Phone number`,"Save number":`Save number`,Transcript:`Transcript`,Captions:`Captions`,"Translate audio":`Translate audio`,"Audio language":`Audio language`,"Audio options":`Audio options`,"Keep background sound":`Keep background sound`,"Background level":`Background level`,"Speaker voices":`Speaker voices`,"Any voice":`Any voice`,"Male voice":`Male voice`,"Female voice":`Female voice`,"Original audio.":`Original audio.`,"Buy translated audio":`Buy translated audio`,"Audio credit":`Audio credit`,"Buy pass":`Buy pass`,Pass:`Pass`,"Pay with":`Pay with`,"Check payment":`Check payment`,"Open checkout":`Open checkout`,"Free sessions":`Free sessions`,"Usage rates and expiry":`Usage rates and expiry`,Catalogs:`Catalogs`,"Add catalog":`Add catalog`,"Catalog name":`Catalog name`,Link:`Link`,"Play link":`Play link`,"Go live":`Go live`,Publish:`Publish`,Listen:`Listen`,"Live now":`Live now`,Upcoming:`Upcoming`,Parties:`Parties`,"Join party":`Join party`,"Invite code":`Invite code`,Invite:`Invite`,Chat:`Chat`,"Chat message":`Chat message`,People:`People`,Speaker:`Speaker`,Speakers:`Speakers`,Listener:`Listener`,Moderator:`Moderator`,"Raise hand":`Raise hand`,"Hand raises":`Hand raises`,Questions:`Questions`,Resources:`Resources`,Replay:`Replay`,Schedule:`Schedule`,Event:`Event`,Host:`Host`,About:`About`,Stage:`Stage`,Title:`Title`,Description:`Description`,Topic:`Topic`,Public:`Public`,"Anyone with the link":`Anyone with the link`,"Invited people":`Invited people`,"Who can join":`Who can join`,"Date and time":`Date and time`,"Expected length":`Expected length`,Repeat:`Repeat`,"Does not repeat":`Does not repeat`,"Every day":`Every day`,"Every week":`Every week`,Homepage:`Homepage`,"Host name":`Host name`,"Profile photo URL":`Profile photo URL`,"Broadcast link":`Broadcast link`,"Edit event":`Edit event`,"Save changes":`Save changes`,"Create live":`Create live`,"Schedule class":`Schedule class`,"Start class":`Start class`,"End event":`End event`,"End session":`End session`,"Session ended":`Session ended`,"Event ended":`Event ended`,Cancelled:`Cancelled`,"Replay available":`Replay available`,Join:`Join`,"Create invite":`Create invite`,"Invite as":`Invite as`,"Watch now":`Watch now`,"Start a room":`Start a room`,"Recent replays":`Recent replays`,"Your account":`Your account`,"Write with AI":`Write with AI`,"Suggested title":`Suggested title`,"Suggested description":`Suggested description`,"Suggested topic":`Suggested topic`,"Use these details":`Use these details`,"Learn something live.":`Learn something live.`,"Screen share":`Screen share`,"Upload and broadcast":`Upload and broadcast`,Help:`Help`,"Reload Player":`Reload Player`,"Copy Bundled CLI Path":`Copy Bundled CLI Path`,"Developer tools":`Developer tools`,Undo:`Undo`,Redo:`Redo`,Cut:`Cut`,Paste:`Paste`,"Select all":`Select all`,Status:`Status`,"Activity log":`Activity log`,Admin:`Admin`,"Playback controls":`Playback controls`,"Tracks and folders":`Tracks and folders`,"Original-language captions.":`Original-language captions.`,"Skip to playback controls":`Skip to playback controls`,"Skip to playlist":`Skip to playlist`,"Skip to transcript and translated audio":`Skip to transcript and translated audio`},n={"■ STOPPED":`Stopped`,"▶ PLAYING":`Playing`,LOADING:`Loading…`,"no source":`No source`,"not connected":`Not connected`,"Now playing":`Now Playing`,"● GO LIVE":`Go live`,"● Go live":`Go live`,"⤓ Download":`Download`,"A man's voice":`Male voice`,"A woman's voice":`Female voice`,"Catalogs on this server":`Catalogs`,"Catalog folders":`Catalogs`,"Parties on this server":`Parties`,"Servers streaming now":`Directory`,"Playlist (0)":`Playlist`,"Playlist folders":`Playlist`,"Playlist pages":`Playlist`,"Filter these files":`Filter`,"Filter these entries":`Filter`,"Filter the entries":`Filter`,"Filter the playlist":`Filter`,"Create a free account":`Create account`,"Create one":`Create account`,"Create your account":`Create account`,"New here? Create an account":`Create account`,"Already have an account? Sign in":`Sign in`,"Your NixAmp account":`Your account`,"Your public handle":`Handle`,handle:`Handle`,password:`Password`,"Phone number for texts":`Phone number`,"Back to the player":`Back`,"Share what is playing":`Share`,"Share this stream":`Share`,"Link to this stream":`Link`,"Copy this stream's URL":`Copy link`,"A link to play":`Link`,"A server's link":`Server`,"Close translated audio purchase":`Close`,"Open secure checkout ↗ (new tab)":`Open checkout`,"Checking…":`Loading…`,"Browse the directory":`Directory`,"See what is live":`Live now`,"Join live":`Join`,"Raise Hand":`Raise hand`,"Hand Raises":`Hand raises`,"Hide this":`Hide`,Log:`Activity log`,"Status:":`Status`,"Nixamp player":`Playback controls`,"Nixamp audio and video player":`Playback controls`,"What is being said":`Transcript`,"The room's chat":`Chat`,Trollbox:`Chat`,"A line for the trollbox":`Chat message`,"Say something to the room…":`Chat message`,"Send it":`Send`,"Something to add":`Chat message`,"What to call it":`Catalog name`,"call it something":`Catalog name`,"An m3u catalog to add":`Catalogs`,"On this device":`Play`,"Play on this device":`Play`,"What this is":`About`,"Looking for servers…":`Loading…`,"Finding today’s conversations…":`Loading…`,"Coming up":`Upcoming`,"Listen after class":`Replay`,"Schedule live":`Schedule class`,"Schedule a class":`Schedule class`,"Plan a conversation":`Schedule class`,"Your classroom":`Event`,"Join in":`Join`,"Open a room →":`Start a room`,"Chat message":`Chat message`,"Add to the conversation":`Chat message`,"Create live":`Create live`,"Host stage":`Stage`,"Your host":`Host`,"Class host":`Host`,"Hand raised ✓":`Raise hand`,"Copied ✓":`Copied`,"Screen share with Pairux ↗":`Screen share`,"Upload & broadcast in Nixamp ↗":`Upload and broadcast`,"Open Music Folder…":`Open folder`,"Choose a music folder":`Open folder`,"Main navigation":`Panels`,"Skip to a section":`Panels`},r=[{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`}],i=`nixamp.ui.language`;function a(e){let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code??`en`}function o(e,t=[]){let n=e=>{let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code};return n(e)??t.map(n).find(Boolean)??`en`}var s=`modulepreload`,c=function(e){return`/`+e},l={},u=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 u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=c(t,n),t=u(t),t in l)return;l[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`:s,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)})},d={en:async()=>({default:t}),de:()=>u(()=>import(`./de-GIUpioF8.js`),[]),sv:()=>u(()=>import(`./sv-D2DxEds9.js`),[]),es:()=>u(()=>import(`./es-DYl1woBl.js`),[]),fr:()=>u(()=>import(`./fr-BnBn3sQ4.js`),[]),it:()=>u(()=>import(`./it-NO6gDgAq.js`),[]),nl:()=>u(()=>import(`./nl-Yn-CJ5On.js`),[]),da:()=>u(()=>import(`./da-ChU3Kuk-.js`),[]),fi:()=>u(()=>import(`./fi-DcCzuMch.js`),[]),ru:()=>u(()=>import(`./ru-BK8Zz61e.js`),[]),uk:()=>u(()=>import(`./uk-Dgdp-BEG.js`),[]),cs:()=>u(()=>import(`./cs-lQyYj1vj.js`),[]),hu:()=>u(()=>import(`./hu-CRU_GolZ.js`),[]),zh:()=>u(()=>import(`./zh-DopV51uz.js`),[]),ar:()=>u(()=>import(`./ar-LBAMiBKG.js`),[]),hi:()=>u(()=>import(`./hi-CPkGxMBI.js`),[]),vi:()=>u(()=>import(`./vi-BOgCl1aV.js`),[]),id:()=>u(()=>import(`./id-BGiv1VIV.js`),[])},f=new class{load;code=`en`;get language(){return this.code}constructor(e=async e=>(await d[e]()).default){this.load=e}messages=t;revision=0;numberFormats=new Map;dateFormats=new Map;listeners=new Set;async setLanguage(e){let t=++this.revision,n=a(e),r=await this.load(n);if(t!==this.revision)return!1;this.code=n,this.messages=r,this.numberFormats.clear(),this.dateFormats.clear();for(let e of this.listeners)e();return!0}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}text(e,t={}){let r=this.language!==`en`&&Object.hasOwn(n,e)?n[e]:e,i=Object.hasOwn(this.messages,r)?this.messages[r]:e;return this.language!==`en`&&Object.hasOwn(n,e)&&(i=(e.match(/^[▶■●⤓]\s+/)?.[0]??``)+i+(e.endsWith(` ✓`)?` ✓`:``)),i.replace(/\{([\w]+)\}/g,(e,n)=>Object.hasOwn(t,n)?String(t[n]):e)}number(e,t){let n=JSON.stringify(t??{}),r=this.numberFormats.get(n);return r||(this.numberFormats.size>=64&&this.numberFormats.clear(),r=new Intl.NumberFormat(this.language,t),this.numberFormats.set(n,r)),r.format(e)}date(e,t){let n=JSON.stringify(t??{}),r=this.dateFormats.get(n);return r||(this.dateFormats.size>=64&&this.dateFormats.clear(),r=new Intl.DateTimeFormat(this.language,t),this.dateFormats.set(n,r)),r.format(e)}get direction(){return this.language===`ar`?`rtl`:`ltr`}},p=(e,t)=>f.text(e,t),m=new Map;function h(e,t,n){let r=m.get(e);r||(r=new Map,m.set(e,r)),r.set(t,n),n()}function g(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return h(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){m.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function _(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return h(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){m.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var v=[`aria-label`,`title`,`placeholder`,`data-title`],ee=[`[data-i18n]`,...v.map(e=>`[data-i18n-${e}]`)].join(`,`);function y(e){let t=[...e.querySelectorAll(ee)];e instanceof HTMLElement&&e.matches(ee)&&t.unshift(e);for(let e of t){if(e.closest(`[translate="no"], [contenteditable="true"]`))continue;let t=e.getAttribute(`data-i18n`);if(t){let n=e.textContent;h(e,`text`,()=>{if(e.textContent!==n){m.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=p(t),e.textContent!==n&&(e.textContent=n)})}for(let t of v){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);h(e,t,()=>{if(e.getAttribute(t)!==r){m.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=p(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function te(){document.documentElement.lang=f.language,document.documentElement.dir=f.direction;for(let[e,t]of m){if(!e.isConnected){m.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=f.language}var ne=0;async function re(e){let t=++ne;try{if(!await f.setLanguage(e)||t!==ne)return;try{localStorage.setItem(i,f.language)}catch{}window.nixampLanguage?.set(f.language).catch(()=>{})}catch{te()}}async function ie(){let e=o(null,navigator.languages);try{e=o(await window.nixampLanguage?.get()??localStorage.getItem(`nixamp.ui.language`),navigator.languages)}catch{}for(let e of document.querySelectorAll(`[data-ui-language]`))e.replaceChildren(...r.map(e=>{let t=new Option(e.label,e.code);return t.lang=e.code,t.dir=`auto`,t})),e.addEventListener(`change`,()=>{re(e.value)});y(document),te(),f.onChange(te),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&y(e);for(let e of m.keys())e.isConnected||m.delete(e)}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener(`storage`,e=>{e.key===`nixamp.ui.language`&&f.setLanguage(o(e.newValue,navigator.languages)).catch(()=>{})}),window.nixampLanguage?.subscribe(e=>{e!==f.language&&f.setLanguage(e).catch(()=>{})});try{await f.setLanguage(e)}catch{}}var ae={play:`<span aria-hidden="true">▶</span>`,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>`};function oe(e,t){e.innerHTML=ae[t]}function se(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 ce(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function b(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var le=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function x(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&le.has(e.slice(n+1).toLowerCase())}function ue(){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 S=new WeakMap;function de(e,t=!0){let n=e.contains(document.activeElement);S.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function C(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){S.delete(e),e.replaceChildren(...t);return}let n=S.has(e);if(S.set(e,t),n)return;let r=()=>{let t=S.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}S.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var w=new WeakMap,fe=new WeakSet;function pe(e,t){let n=new Map([...e.children].map(e=>[e.dataset.liveKey,e])),r=new Set(t.map(e=>e.dataset.liveKey)),i=!1;for(let r of t){let t=n.get(r.dataset.liveKey);t?t!==r&&!t.isEqualNode(r)&&(t.contains(document.activeElement)||t.querySelector(`details[open]`)?i=!0:t.replaceWith(r)):e.append(r)}for(let[e,t]of n)r.has(e)||(t.contains(document.activeElement)?i=!0:t.remove());if(i?w.set(e,t):w.delete(e),fe.has(e))return;fe.add(e);let a=()=>{let t=w.get(e);t&&pe(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function me(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 T(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 he(e,t,n=`Live`){let r=e[t];if(!r){let e=me(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${me(r.title)}`:me(r.title),a=T(r.folder??``),o=T(r.group??``).join(` › `),s=[...o?[o]:[],...a],c=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,l=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:c,position:`Playlist · ${l.findIndex(({at:e})=>e===t)+1} of ${l.length}`,fullTitle:c?`${c} › ${i}`:i}}var ge=[[/\.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`]],_e=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function E(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of _e)if(t.test(e.mimeType))return n}let t=ve(e.src);for(let[e,n]of ge)if(e.test(t))return n;return`unknown`}function ve(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function ye(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 be(e,t){let n=E(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 xe(e,t){let n=t.capabilities??ye(),r=be({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 u(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-9KD7WXBu.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await u(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-n4DFtkJH.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await u(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 Se=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`]),Ce=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function D(e){let t=e.lastIndexOf(`.`);return t>0&&Ce.has(e.slice(t+1).toLowerCase())}function O(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&Se.has(e.slice(n+1).toLowerCase())}function we(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function Te(e){return e.filter(e=>O(e.name,e.type)).sort((e,t)=>we(Ee(e),Ee(t))).map(e=>({title:b(e.name),artist:``,album:De(Ee(e)),duration:0,url:URL.createObjectURL(e),video:x(e.name,e.type),objectUrl:!0,...D(e.name)?{kind:`mpegts`}:{}}))}function Ee(e){return e.webkitRelativePath||e.name}function De(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function Oe(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var k=2048;function A(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 ke(e,t){return e||t===`hls`||t===`mpegts`}var Ae=class{elements;handlers;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;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(je(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 jinglePlaying(){return!!this.jingle&&!this.jingle.paused&&!this.jingle.ended}async playJingle(e){this.jingle!==e&&this.stopJingle(),this.jingle=e,this.ensureGraph(e);try{if(await e.play(),this.context?.state===`suspended`)throw new DOMException(`Audio needs an interaction`,`NotAllowedError`)}catch(t){throw e.pause(),e.currentTime=0,t}}stopJingle(){this.jingle?.pause(),this.jingle=null}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=k,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.output.gain.value=+!this.translated,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.translated=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.stopJingle(),this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:E({src:e.url})),r=ke(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||A(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 xe(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:`)||A(a),t&&await this.play()}async play(){this.stopJingle(),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.stopJingle(),this.playBlocked=!1,this.active.pause()}async resumeAfterInteraction(){this.playBlocked?await this.play():this.playing&&this.context?.state===`suspended`&&await this.context.resume()}stop(){this.stopJingle(),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 je(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 Me(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function Ne(e,t){return{...t,tracks:t.tracks??e.tracks}}function Pe(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 Fe(e,t,n=``){let r=`${e===``?``:Pe(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function Ie(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 Le(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:Pe(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var Re=null;function ze(e){if(!e&&Re!==null)return Re;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||(Re=n),n}catch{return!1}}function Be(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return Fe(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function Ve(e){if(typeof e!=`object`||!e)return null;let t=e,n=Me(),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 He(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var Ue=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return He(this.base,e)}url(e){let t=Fe(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}=Le(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(Fe(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=Ve(We(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(Fe(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=Ve(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=ze()){return Be(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function We(e){try{return JSON.parse(e)}catch{return null}}async function Ge(e,t,n=``){try{let r=await fetch(Fe(e,`/api/state`,n),{signal:t});return r.ok?Ve(await r.json()):null}catch{return null}}function Ke(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 qe(e,t=``,n){let r;try{r=await fetch(Fe(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 Je(e,t,n=``){try{let r=await fetch(Fe(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 Ye(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 Xe=.14,Ze=.02;function Qe(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 $e(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 et(e,t,n=Xe){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function tt(e,t,n=Ze){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function nt(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 rt(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 it(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function at(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??f.language,i)===r.toLocaleDateString(t.locale??f.language,i);return n.toLocaleString(t.locale??f.language,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function ot(e,t={}){let n=e.data,r=rt(n.away,n.awayScore),i=rt(n.home,n.homeScore),a=it(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=at(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 st=`nixamp.tv`,j=/\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 ct(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?lt(r):/\bSilk\b/.test(e)&&n===0?!0:j.test(e):lt(i)}function lt(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function ut(e){return e?12:100}function dt(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 ft=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,M=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,pt=/\.m3u8(\?.*)?$/i,mt=/\.(m3u|pls)(\?.*)?$/i;function ht(e){try{let t=new URL(e);return M.test(t.pathname+t.search)}catch{return!1}}function gt(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 _t(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||gt(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(!ft.test(a)&&!M.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 vt(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 yt(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=vt(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 mt.test(o)?{kind:`list`,url:n.toString(),label:gt(n.toString())}:ft.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:M.test(o)||pt.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var bt=`nixamp.panels`;function xt(){return{order:[],placement:{},collapsed:[],closed:[]}}var St=/^[a-z][a-z0-9-]{0,63}$/,Ct=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function wt(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&St.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function Tt(e){if(!e)return xt();let t;try{t=JSON.parse(e)}catch{return xt()}if(!t||typeof t!=`object`||Array.isArray(t))return xt();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))St.test(e)&&typeof t==`string`&&Ct.test(t)&&(r[e]=t);let i=e=>{let t=wt(e),n=t.includes(`parties-panel`)?t.filter(e=>e!==`onair-panel`):t;return[...new Set(n.map(e=>e===`onair-panel`?`parties-panel`:e))]};return!r[`parties-panel`]&&r[`onair-panel`]&&(r[`parties-panel`]=r[`onair-panel`]),delete r[`onair-panel`],{order:i(n.order),placement:r,collapsed:i(n.collapsed),closed:i(n.closed)}}function Et(e){return JSON.stringify(e)}function Dt(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 Ot(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function kt(e,t=16e3){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}var At=16e3,jt=3e4;function Mt(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function Nt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var Pt=`nixamp.captions`,Ft=`nixamp.captions.native-v2.language`,It=[{code:``,label:`Original (auto-detect)`},...r];function Lt(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return It.some(e=>e.code===t)?t:``}catch{return``}}function Rt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function zt(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function Bt(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 Vt(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 Ht(e){try{return e(Pt)!==`off`}catch{return!0}}function Ut(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Wt(e){let t=e?.status;return typeof t==`number`?[408,502,503,504].includes(t):e instanceof TypeError||e instanceof Error&&[`AbortError`,`TimeoutError`].includes(e.name)}function N(e,t){return Object.assign(Error(e),{status:t})}var Gt=12e3,Kt=class{options;context=null;gain=null;enabled=!1;generation=0;running=null;controller=null;next=[];sources=new Set;scheduledUntil=0;failures=0;seen=new Set;constructor(e){this.options=e}async enable(){this.enabled=!0,this.options.active(!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(),this.failures=0;for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.scheduledUntil=0,this.options.active(this.enabled)}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=[...this.next.filter(e=>!this.stale(e.line,e.lag)),...t].slice(-24),this.running===null&&this.run(this.generation))}stale(e,t){return(this.options.now?.()??Date.now())-t-e.until>Gt}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;){if(await this.waitForRoom(e,3),e!==this.generation)return;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 i=new Headers(t.init?.headers);if(new Headers(await this.options.authorization?.(n.signal,t.line)).forEach((e,t)=>i.set(t,e)),e!==this.generation)return;let a=await(this.options.fetcher??fetch)(t.url,{...t.init,signal:n.signal,headers:i});if(clearTimeout(r),e!==this.generation){await a.body?.cancel();return}if(!a.ok)throw N((await a.json().catch(()=>({}))).error||`Translated audio is unavailable.`,a.status);if(!a.body||!a.headers.get(`content-type`)?.startsWith(`audio/pcm`))throw Error(`The server returned no voice audio.`);let o=a.body.getReader(),s=new Uint8Array,c=0;try{for(;;){let t,{done:r,value:i}=await Promise.race([o.read(),new Promise((e,r)=>{t=setTimeout(()=>{n.abort(),o.cancel().catch(()=>{}),r(new DOMException(`Voice connection timed out`,`TimeoutError`))},12e3)})]).finally(()=>clearTimeout(t));if(e!==this.generation){await o.cancel();return}if(r)break;let a=new Uint8Array(s.length+i.length);a.set(s),a.set(i,s.length);let l=a.length-a.length%2;s=a.slice(l);for(let t=0;t<l;t+=6400){if(await this.waitForRoom(e,8),e!==this.generation){await o.cancel();return}let n=a.subarray(t,Math.min(l,t+6400));this.schedule(n),c+=n.length}}}finally{o.releaseLock()}if(!c||s.length)throw N(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!Wt(t)||++this.failures>=3)throw t;this.options.status(`Voice interrupted · waiting for the next translated phrase…`)}finally{clearTimeout(r)}}}catch(t){e===this.generation&&this.fail(t instanceof Error?t.message:`Translated audio stopped.`)}finally{this.running===e&&(this.running=null)}}async waitForRoom(e,t){for(;e===this.generation&&this.context&&this.scheduledUntil-this.context.currentTime>t;)if(await new Promise(e=>setTimeout(e,25)),!this.options.playing()){this.reset();return}}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.status(`Playing translated audio · a few seconds behind the video`)}},P=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,F=new WeakMap,qt=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t,n=5){this.stop();let r=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(F.has(e)||F.set(e,e.audioWorklet.addModule(P).catch(t=>{throw F.delete(e),t})),await F.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=i;let a=e.createGain();a.gain.value=0,t.connect(i),i.connect(a),a.connect(e.destination);let o=new Float32Array(e.sampleRate*n),s=0,c=new Float32Array,l=Date.now();i.port.onmessage=t=>{if(r!==this.generation)return;let i=0,a=t.data;for(;i<a.length;){let t=Math.min(o.length-s,a.length-i);if(o.set(a.subarray(i,i+t),s),s+=t,i+=t,s!==o.length)continue;let r=new Float32Array(16e3*n),u=e.sampleRate/16e3;for(let e=0;e<r.length;e++){let t=Math.floor(e*u),n=Math.max(t+1,Math.floor((e+1)*u)),i=0;for(let e=t;e<n;e++)i+=o[e]??0;r[e]=i/(n-t)}l+=n*1e3,Math.abs(Date.now()-l)>1500&&(l=Date.now(),c=new Float32Array);let d=new Float32Array(c.length+r.length);d.set(c),d.set(r,c.length),this.take({samples:d,at:l-d.length/16,until:l,freshAt:l-n*1e3}),c=d.slice(-32e3*n),s=0}},this.disconnect=()=>{i.port.onmessage=null,i.port.close(),t.disconnect(i),i.disconnect(),a.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},I=3,Jt=1,Yt=class e{failed;options;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;level=1;static loaded=new WeakMap;constructor(e,t={}){this.failed=e,this.options=t}async start(t,n){this.stop();let r=this.generation;try{if(this.options.process===!1){if(r!==this.generation)return!1;let e=t.createGain();return this.gain=e,e.gain.value=this.on?this.level*Jt:0,this.input=n,n.connect(e),e.connect(t.destination),!0}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,LyogQXVkaW8gdHJhbnNwb3J0IG9ubHk6IG5ldXJhbCBpbmZlcmVuY2UgcnVucyBpbiBhIGRlZGljYXRlZCB3b3JrZXIuIEEgYnJpZWYKICogc3RhbGwgZHJvcHMgc3RhbGUgZnJhbWVzIGFuZCByZWNvdmVyczsgaXQgbXVzdCBub3QgcGVybWFuZW50bHkgbXV0ZSBhbWJpZW5jZS4KICogTmV2ZXIgYnlwYXNzIHRvIHJhdyBpbnB1dCwgd2hpY2ggd291bGQgcmVzdG9yZSB0aGUgb3JpZ2luYWwgZGlhbG9ndWUuICovCmNvbnN0IEhPUCA9IDUxMjsKY29uc3QgTUFYX1BFTkRJTkcgPSAzMjsgLy8gQm91bmQgd29yayB0byBhYm91dCAzNDAgbXMgYXQgNDgga0h6Lgpjb25zdCBNQVhfQUdFID0gMTI7IC8vIEtlZXAgYXVkaWJsZSBhbWJpZW5jZSB3aXRoaW4gYWJvdXQgMTMwIG1zIG9mIHRoZSBzb3VyY2UuCmNvbnN0IFBSRUJVRkZFUiA9IDQ7CmNsYXNzIEJhY2tncm91bmRUcmFuc3BvcnQgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogIGNvbnN0cnVjdG9yKCkgewogICAgc3VwZXIoKTsKICAgIHRoaXMuY2hhbm5lbCA9IG51bGw7IHRoaXMuYWxpdmUgPSB0cnVlOyB0aGlzLnJlYWR5ID0gZmFsc2U7CiAgICB0aGlzLmlucHV0cyA9IFtdOwogICAgdGhpcy53cml0dGVuID0gMDsgdGhpcy5pZCA9IDA7IHRoaXMuaW5mbGlnaHQgPSAwOwogICAgdGhpcy5xdWV1ZSA9IFtdOyB0aGlzLm91dHB1dCA9IG51bGw7IHRoaXMucmVhZCA9IDA7CiAgICB0aGlzLnBvcnQub25tZXNzYWdlID0gZXZlbnQgPT4gewogICAgICBpZiAoZXZlbnQuZGF0YS5zdG9wKSB7IHRoaXMuYWxpdmUgPSBmYWxzZTsgdGhpcy5jaGFubmVsPy5jbG9zZSgpOyByZXR1cm47IH0KICAgICAgdGhpcy5jaGFubmVsID0gZXZlbnQuZGF0YS5wb3J0OwogICAgICB0aGlzLmNoYW5uZWwub25tZXNzYWdlID0gcmVzdWx0ID0+IHsKICAgICAgICBpZiAoIXRoaXMuYWxpdmUpIHJldHVybjsKICAgICAgICB0aGlzLmluZmxpZ2h0LS07CiAgICAgICAgY29uc3QgZnJhbWUgPSByZXN1bHQuZGF0YTsKICAgICAgICBpZiAoIU51bWJlci5pc1NhZmVJbnRlZ2VyKGZyYW1lLmlkKSB8fCAhQXJyYXkuaXNBcnJheShmcmFtZS5jaGFubmVscykgfHwgZnJhbWUuY2hhbm5lbHMubGVuZ3RoICE9PSAyCiAgICAgICAgICAgIHx8IGZyYW1lLmNoYW5uZWxzLnNvbWUoY2hhbm5lbCA9PiAhKGNoYW5uZWwgaW5zdGFuY2VvZiBGbG9hdDMyQXJyYXkpIHx8IGNoYW5uZWwubGVuZ3RoICE9PSBIT1ApKSB7IHRoaXMuZmFpbCgpOyByZXR1cm47IH0KICAgICAgICAvLyBMYXRlIGJhY2tncm91bmQgaXMgYXMgZGlzdHJhY3RpbmcgYXMgbWlzc2luZyBiYWNrZ3JvdW5kLiBEaXNjYXJkIGl0CiAgICAgICAgLy8gd2hpbGUga2VlcGluZyB0aGUgd29ya2VyIGFsaXZlIHRvIGhhbmRsZSB0aGUgbmV4dCBjdXJyZW50IGZyYW1lLgogICAgICAgIGlmIChmcmFtZS5pZCA8IHRoaXMuaWQgLSBNQVhfQUdFKSByZXR1cm47CiAgICAgICAgaWYgKHRoaXMucXVldWUubGVuZ3RoID49IE1BWF9QRU5ESU5HKSB0aGlzLnF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgdGhpcy5xdWV1ZS5wdXNoKGZyYW1lKTsKICAgICAgICBpZiAodGhpcy5xdWV1ZS5sZW5ndGggPj0gUFJFQlVGRkVSKSB0aGlzLnJlYWR5ID0gdHJ1ZTsKICAgICAgfTsKICAgICAgdGhpcy5jaGFubmVsLnN0YXJ0KCk7CiAgICB9OwogIH0KICBmYWlsKCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyBlcnJvcjogdHJ1ZSB9KTsgfQogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzKSB7CiAgICBjb25zdCBvdXQgPSBvdXRwdXRzWzBdOwogICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm4gZmFsc2U7CiAgICBjb25zdCBpbnB1dCA9IGlucHV0c1swXTsKICAgIGlmICghaW5wdXQ/LlswXSB8fCAhdGhpcy5jaGFubmVsKSByZXR1cm4gdHJ1ZTsKICAgIGlmICghWzEsIDIsIDQsIDYsIDhdLmluY2x1ZGVzKGlucHV0Lmxlbmd0aCkpIHsgdGhpcy5mYWlsKCk7IHJldHVybiBmYWxzZTsgfQogICAgaWYgKHRoaXMuaW5wdXRzLmxlbmd0aCAhPT0gaW5wdXQubGVuZ3RoKSB7CiAgICAgIGlmICh0aGlzLmlucHV0cy5sZW5ndGgpIHRoaXMuaWQrKzsgLy8gRGlzY2FyZCBhIHBhcnRpYWwgZnJhbWUgb24gYSBsYXlvdXQgY2hhbmdlLgogICAgICB0aGlzLmlucHV0cyA9IGlucHV0Lm1hcCgoKSA9PiBuZXcgRmxvYXQzMkFycmF5KEhPUCkpOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgY29uc3QgY291bnQgPSBpbnB1dFswXS5sZW5ndGg7CiAgICBmb3IgKGxldCBjaGFubmVsID0gMDsgY2hhbm5lbCA8IGlucHV0Lmxlbmd0aDsgY2hhbm5lbCsrKSB0aGlzLmlucHV0c1tjaGFubmVsXS5zZXQoaW5wdXRbY2hhbm5lbF0sIHRoaXMud3JpdHRlbik7CiAgICB0aGlzLndyaXR0ZW4gKz0gY291bnQ7CiAgICBpZiAodGhpcy53cml0dGVuID09PSBIT1ApIHsKICAgICAgaWYgKHRoaXMuaW5mbGlnaHQgPCBNQVhfUEVORElORykgewogICAgICAgIGNvbnN0IGNoYW5uZWxzID0gdGhpcy5pbnB1dHM7IHRoaXMuaW5mbGlnaHQrKzsKICAgICAgICB0aGlzLmNoYW5uZWwucG9zdE1lc3NhZ2UoeyBpZDogdGhpcy5pZCwgY2hhbm5lbHMgfSwgY2hhbm5lbHMubWFwKG9uZSA9PiBvbmUuYnVmZmVyKSk7CiAgICAgICAgdGhpcy5pbnB1dHMgPSBpbnB1dC5tYXAoKCkgPT4gbmV3IEZsb2F0MzJBcnJheShIT1ApKTsKICAgICAgfQogICAgICAvLyBTa2lwIGV4Y2VzcyB3b3JrIGluc3RlYWQgb2YgYnVpbGRpbmcgYSBiYWNrbG9nIG9yIGtpbGxpbmcgdGhlIGJyYW5jaC4KICAgICAgdGhpcy5pZCsrOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgaWYgKCF0aGlzLnJlYWR5KSByZXR1cm4gdHJ1ZTsKICAgIGlmICghdGhpcy5vdXRwdXQgfHwgdGhpcy5yZWFkID09PSBIT1ApIHsKICAgICAgd2hpbGUgKHRoaXMucXVldWUubGVuZ3RoICYmIHRoaXMucXVldWVbMF0uaWQgPCB0aGlzLmlkIC0gTUFYX0FHRSkgdGhpcy5xdWV1ZS5zaGlmdCgpOwogICAgICB0aGlzLm91dHB1dCA9IHRoaXMucXVldWUuc2hpZnQoKT8uY2hhbm5lbHMgPz8gbnVsbDsgdGhpcy5yZWFkID0gMDsKICAgIH0KICAgIGlmICghdGhpcy5vdXRwdXQpIHsgdGhpcy5yZWFkeSA9IGZhbHNlOyByZXR1cm4gdHJ1ZTsgfQogICAgZm9yIChsZXQgY2hhbm5lbCA9IDA7IGNoYW5uZWwgPCBvdXQubGVuZ3RoOyBjaGFubmVsKyspIG91dFtjaGFubmVsXS5zZXQodGhpcy5vdXRwdXRbY2hhbm5lbF0uc3ViYXJyYXkodGhpcy5yZWFkLCB0aGlzLnJlYWQgKyBjb3VudCkpOwogICAgdGhpcy5yZWFkICs9IGNvdW50OwogICAgcmV0dXJuIHRydWU7CiAgfQp9CnJlZ2lzdGVyUHJvY2Vzc29yKCJuaXhhbXAtYmFja2dyb3VuZCIsIEJhY2tncm91bmRUcmFuc3BvcnQpOwo=`,``+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-Hz7oaQ8X.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],channelCount:8,channelCountMode:`clamped-max`,channelInterpretation:`speakers`});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.level*I:0,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?this.level*(this.options.process===!1?Jt:I):0)}setLevel(e){Number.isFinite(e)&&(this.level=Math.max(0,Math.min(2,e)),this.gain&&(this.gain.gain.value=this.on?this.level*(this.options.process===!1?Jt:I):0))}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()}if(!this.node&&this.input&&this.gain)try{this.input.disconnect(this.gain)}catch{}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},Xt=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t){this.stop();let n=new AbortController;this.controller=n;let r=async()=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e3),a=await(this.options.fetcher??fetch)(`/api/v1/speech/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,language:t}),signal:AbortSignal.any([n.signal,r.signal])}).finally(()=>clearTimeout(i));if(!a.ok||!a.body)throw N((await a.json().catch(()=>({}))).error||`Live translation is unavailable.`,a.status);return a.body},i=await r();if(this.controller!==n){await i.cancel();return}this.consume(i,n,r)}clearClips(){for(let e of this.clips.values())if(!e.ended)try{e.controller.error(new DOMException(`Playback stopped`,`AbortError`))}catch{}this.clips.clear()}stop(){this.controller?.abort(),this.controller=null,this.clearClips()}audio(e){let t=this.clips.get(e);if(!t||t.taken)throw N(`The live audio segment expired. Catching up…`,503);return t.taken=!0,new Response(t.stream,{headers:{"content-type":`audio/pcm`}})}async consume(e,t,n){let r=0;for(;!t.signal.aborted;){let i=Date.now();try{await this.read(e,t);return}catch(a){if(t.signal.aborted||this.controller!==t)return;Date.now()-i>6e4&&(r=0),this.options.reconnecting?.(),this.clearClips();let o=a;for(;!t.signal.aborted;){if(!Wt(o)||r>=5){this.stop(),this.options.failed(o instanceof Error?o.message:`Live audio was interrupted.`);return}if(this.options.status(`Live audio disconnected · reconnecting…`),await new Promise(e=>{let n=()=>{clearTimeout(i),t.signal.removeEventListener(`abort`,n),e()},i=setTimeout(n,500*2**r++);t.signal.addEventListener(`abort`,n,{once:!0})}),t.signal.aborted)return;try{e=await n();break}catch(e){o=e}}}}}async read(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t.signal.addEventListener(`abort`,a,{once:!0});try{for(;!t.signal.aborted;){let e,{done:o,value:s}=await Promise.race([n.read(),new Promise((t,n)=>{e=setTimeout(()=>{n(N(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw N(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
2
2
 
3
- `))>=0;){let e=i.slice(0,c);i=i.slice(c+2),e.startsWith(`data: `)&&this.event(JSON.parse(e.slice(6)))}if(i.length>128e3)throw Error(`Invalid live audio response.`)}}finally{t.signal.removeEventListener(`abort`,a),await n.cancel().catch(()=>{}),n.releaseLock()}}event(e){if(e.type===`error`)throw N(e.error,e.retryable?503:400);if(e.type===`status`){this.options.status(`Live translated audio · ${e.listeners} ${e.listeners===1?`listener`:`listeners`}`);return}let t=`nixamp-shared:${e.id}`;if(e.type===`line`){for(let[e,t]of this.clips)t.ended&&(t.taken||Date.now()-t.until>12e3)&&this.clips.delete(e);for(;this.clips.size>=24;){let e=this.clips.entries().next().value;e[1].ended||e[1].controller.error(N(`Catching up with live audio…`,503)),this.clips.delete(e[0])}let n,r=new ReadableStream({start:e=>{n=e},cancel:()=>{let e=this.clips.get(t);e&&(e.ended=!0),this.clips.delete(t)}});this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t);return}let n=this.clips.get(t);if(!n||n.ended)return;if(e.type===`end`){n.ended=!0,n.controller.close();return}let r=Uint8Array.from(atob(e.data),e=>e.charCodeAt(0));if(n.bytes+=r.length,n.bytes>2097152)throw Error(`The live audio segment was too large.`);n.controller.enqueue(r)}},L=e=>new Intl.NumberFormat(f.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),R=e=>document.getElementById(e),Zt=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=R(`translation-purchase`);plan=R(`translation-plan`);coin=R(`translation-coin`);buy=R(`translation-checkout`);note=R(`translation-purchase-note`);checkoutLink=R(`translation-checkout-link`);constructor(e){this.options=e,R(`translation-purchase-close`).addEventListener(`click`,()=>this.dialog.close()),this.dialog.addEventListener(`close`,()=>{this.timer&&clearTimeout(this.timer),this.timer=null,this.opener?.focus({preventScroll:!0})}),R(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),R(`translation-check-payment`).addEventListener(`click`,()=>void this.check()),window.addEventListener(`pagehide`,()=>{this.timer&&clearTimeout(this.timer)}),setInterval(()=>{this.options.account()&&(!this.access||this.access.required)&&this.refresh()},3e4)}status(e){this.note.textContent!==e&&(this.note.textContent=e)}loaded(){return this.access!==null}loadingMessage(){return this.problem||`Checking free sessions and audio credit…`}ready(){let e=this.access;return e?.required===!1||!!(e&&((e.free?.remaining??0)>0||e.free?.activeUntil&&Date.parse(e.free.activeUntil)>Date.now()||e.balanceMicros>0&&e.expires&&Date.parse(e.expires)>Date.now()))}async startSession(e){if(this.access?.required===!1)return;let t=await fetch(`/api/v1/translation-passes/session`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({resource:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();if(!t.ok)throw Error(n.error||`This free session could not be started.`);this.refresh()}button(){let e=document.createElement(`button`);return e.type=`button`,e.textContent=`$`,_(e,`title`,()=>p(`Buy translated audio`)),_(e,`aria-label`,()=>p(`Buy translated audio`)),e.setAttribute(`aria-haspopup`,`dialog`),e.setAttribute(`aria-controls`,`translation-purchase`),e.dataset.translationBuy=``,e.addEventListener(`click`,()=>this.open(e)),e}open(e){this.opener=e,this.dialog.open||this.dialog.showModal(),this.status(``),this.refresh().then(()=>{this.order&&this.dialog.open&&this.check()})}async refresh(){let e=this.options.account();this.problem=``,this.account!==e&&(this.account=e,this.access=null,this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0);try{let t=await fetch(`/api/v1/translation-passes`,{signal:AbortSignal.timeout(15e3)}),n=await t.json();if(this.account!==e||this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Purchases are unavailable.`);this.access=n;let r=this.access.coins??[];[...this.coin.options].map(e=>e.value).join()!==r.join()&&document.activeElement!==this.coin&&this.coin.replaceChildren(...r.map(e=>new Option(e.replaceAll(`_`,` · `),e)));let i=this.access.plans??[];this.plan.options.length||this.plan.replaceChildren(...i.map(e=>{let t=new Option(``,e.id);return g(t,()=>`${e.name} · ${L(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${p(`Audio credit`)}: ${L(a.balanceMicros)}${a.expires?` · ${new Date(a.expires).toLocaleString(f.language)}`:``}`:``,s=this.access.free,c=()=>a.required&&s?f.language===`en`?`${s.remaining} of ${s.limit} free sessions left today${s.activeUntil?` · free session active`:``}`:`${p(`Free sessions`)}: ${f.number(s.remaining)}/${f.number(s.limit)}${s.activeUntil?` · ✓`:``}`:``;g(R(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(R(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(R(`translation-free-description`),()=>s?`Each account gets ${s.limit} free sessions a day, shared across paid panels and upgrades. Each lasts while you listen, within daily usage limits. Reconnect within ${s.reconnectSeconds} seconds to keep the same session. Resets at ${new Date(s.resets).toLocaleString(f.language)} (midnight UTC). Free time is used before purchased credit.`:``),R(`translation-sign-in`).hidden=!!e,this.buy.disabled=!e||!this.access.available||this.loading,!this.access.available&&this.dialog.open&&this.status(this.access.required?`Checkout is temporarily unavailable. Free sessions and existing credit still work.`:`This server sponsors translated audio; no purchase is required.`);let l=new URLSearchParams(location.search).get(`translation_order`),u=this.access.orders?.find(e=>e.id===l||e.id===this.order)??this.access.orders?.[0];u&&!this.order&&(this.order=u.id,this.link(u.url)),l&&!this.order&&/^[a-f0-9-]{36}$/i.test(l)&&e&&(this.order=l,this.check()),this.options.changed(),this.order&&!this.dialog.open&&!this.checking&&this.check()}catch(e){this.problem=e instanceof Error?e.message:`Audio credit could not be checked. Use Buy to retry.`,this.dialog.open&&this.status(this.problem),this.options.changed()}}describe(){let e=this.access?.plans.find(e=>e.id===this.plan.value);if(!e)return;let t=Math.floor(e.priceCents/100/((.66/60+.05)*5));R(`translation-plan-description`).textContent=`${L(e.priceCents*1e4)} credit. Expires ${e.days===1?`24 hours`:`${e.days} days`} after payment. About ${t} minutes at 1,000 spoken characters/minute; usage varies. No automatic renewal.`}link(e){if(!/^https:\/\/coinpayportal\.com\/pay\/[a-f0-9-]{36}$/i.test(e))throw Error(`Invalid checkout address.`);this.checkoutLink.href=e,this.checkoutLink.hidden=!1,R(`translation-check-payment`).hidden=!1}async purchase(){if(this.loading||!this.account)return;let e=this.account,t=`${this.plan.value}|${this.coin.value}`;(!this.requestKey||this.selected!==t)&&(this.requestKey=crypto.randomUUID(),this.selected=t),this.loading=!0,this.buy.disabled=!0,this.status(`Preparing secure checkout…`);try{let t=await fetch(`/api/v1/translation-passes/checkout`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({plan:this.plan.value,coin:this.coin.value,requestKey:this.requestKey}),signal:AbortSignal.timeout(2e4)}),n=await t.json();if(this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Checkout could not be opened.`);this.order=n.id,this.link(n.url),this.status(`Open secure checkout to pay. Your video keeps playing in this tab. Credit appears after payment confirmation.`),this.poll()}catch(e){this.status(e instanceof Error?e.message:`Checkout could not be opened.`)}finally{this.loading=!1,this.buy.disabled=!this.account||!this.access?.available}}poll(){this.timer&&clearTimeout(this.timer),this.dialog.open&&this.order&&(this.timer=setTimeout(()=>void this.check(),5e3))}async check(){if(!this.order||!this.account||this.checking)return;this.checking=!0;let e=this.order,t=this.account;try{let n=await fetch(`/api/v1/translation-passes/orders/${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(2e4)}),r=await n.json();if(this.account!==t||this.order!==e)return;if(!n.ok)throw Error(r.error||`Payment status could not be checked.`);if(r.status===`paid`){this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0,R(`translation-check-payment`).hidden=!0,this.status(`Payment confirmed. Enable Translate audio whenever you are ready.`);let e=new URL(location.href);e.searchParams.delete(`translation_order`),history.replaceState(history.state,``,e),await this.refresh();return}this.status(r.status===`pending`?`Waiting for payment confirmation…`:`Payment ${r.status}. Check again if you have already sent it.`),r.status===`pending`&&this.poll()}catch(e){this.status(e instanceof Error?e.message:`Payment status could not be checked.`)}finally{this.checking=!1}}},Qt=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}},$t=class{options;tracker=new Qt;generation=0;pending=null;committedUntil=null;running=null;controller=null;translating=null;translationController=null;recognitionFailures=0;translationFailures=0;translations=[];constructor(e){this.options=e}reset(){this.generation++,this.controller?.abort(),this.translationController?.abort(),this.pending=null,this.running=null,this.translating=null,this.recognitionFailures=this.translationFailures=0,this.translations=[],this.committedUntil=null,this.tracker.reset()}push(e){this.committedUntil??=e.freshAt,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 N(i.error||`Audio translation is unavailable.`,r.status);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;this.pending=null;try{if(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(kt(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;this.recognitionFailures=0;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=o.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),l=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),u=[],d=()=>{u.length&&(c.push({channel:this.options.channel(),at:t.at+u[0].start*1e3,until:t.at+u.at(-1).end*1e3,text:u.map(e=>e.text).join(` `).trim(),language:s,speaker:o.id,voiceProfile:a.profile}),u=[])};for(let e of l)u.length&&e.start-u.at(-1).end>=.45&&d(),u.push(e),(/[.!?。!?]$/.test(e.text)||u.map(e=>e.text).join(` `).length>=400)&&d();u.length&&(i<r.length-1||t.until-(t.at+u.at(-1).end*1e3)>=350||t.until-(t.at+u[0].start*1e3)>=3e3)&&d()}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(!c.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...c.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:c,language:s,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!Wt(t)||++this.recognitionFailures>=3)throw t;this.options.status(`Speech recognition interrupted · listening for the next phrase…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.running===e&&(this.running=null)}}async translate(e){this.translating=e;try{for(;this.translations.length&&e===this.generation;){let t=this.translations.shift();try{let{lines:n}=t,{language:r,target:i,until:a}=t;if(Date.now()-a>12e3)continue;let o=new AbortController;if(this.translationController=o,i&&r!==i){if(!r)throw N(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:n.map(e=>e.text),from:r,to:i})},AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]));if(e.texts.length!==n.length||e.texts.some(e=>!e.trim()))throw N(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((t,n)=>({...t,original:t.text,sourceLanguage:r,language:i,text:e.texts[n]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>en(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!Wt(t)||++this.translationFailures>=3)throw t;this.options.status(`Translation interrupted · catching up with live speech…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.translating===e&&(this.translating=null)}}};function en(e){let t=e.text.trim();if(!t)return[];let n=[],r=t;for(;r.length>600;){let e=r.lastIndexOf(` `,600),t=e>300?e:600;n.push(r.slice(0,t)),r=r.slice(t).trimStart()}r&&n.push(r);let i=0;return n.map(n=>{let r=e.at+(e.until-e.at)*i/t.length;return i+=n.length+1,{...e,text:n,at:r,until:Math.min(e.until,e.at+(e.until-e.at)*i/t.length)}})}var tn=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,nn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,rn=/\s+(?:vs\.?|v\.?|at|@)\s+/i,an=/^(?: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 on(e){let t=e.replace(nn,``).replace(nn,``).trim().split(rn);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!an.test(t)})}function sn(e){let t=String(e??``).trim();return t===``?!1:on(t.replace(tn,``))||on(t)}function cn(e,t){e.classList.add(`long-string-scroller`),t.classList.add(`long-string-scroller-content`),t.title=t.textContent??``;let n=0,r=0,i=0,a=0,o=!1,s=null,c=()=>{n=0;let r=a+(i-a)*.22;if(a=Math.abs(i-r)<.5?i:r,t.style.setProperty(`--path-shift`,`${a}px`),Math.abs(i-a)>=.5){n=requestAnimationFrame(c);return}o&&(o=!1,delete t.dataset.pan,t.style.removeProperty(`--path-shift`),s=setTimeout(()=>{s=null,e.style.removeProperty(`min-height`)},280))},l=()=>{n||=requestAnimationFrame(c)};e.addEventListener(`pointerenter`,n=>{n.pointerType===`mouse`&&(s!==null&&(clearTimeout(s),s=null),e.style.minHeight=`${e.getBoundingClientRect().height}px`,o=!1,t.dataset.pan=`true`)}),e.addEventListener(`pointermove`,n=>{if(t.dataset.pan!==`true`)return;r=n.clientX;let a=e.scrollWidth-e.clientWidth;if(a<=0)return;let o=e.getBoundingClientRect(),s=Math.max(0,Math.min(1,(r-o.left)/Math.max(1,o.width))),c=s*s*(3-2*s);i=-a*c,l()}),e.addEventListener(`pointerleave`,()=>{i=0,o=!0,l()})}var ln=`nixamp.remote`,un=`nixamp.defaultServer`,dn=`nixamp.volume`,fn=`nixamp.listenHere`,pn=1e4,mn=!1;function z(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function hn(){let e=new URLSearchParams(location.search).get(`embed`)===`1`;document.body.classList.toggle(`classroom-embed`,e);let t=null;try{t=localStorage.getItem(st)}catch{}let n=ct(navigator.userAgent,location.search,navigator.maxTouchPoints,t);if(document.body.classList.toggle(`tv`,n),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(st,n?`1`:`0`)}catch{}let r=document.getElementById(`tv-toggle`);r&&(g(r,()=>n?`TV mode: on`:p(`TV mode`)),r.title=n?`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.`,r.addEventListener(`click`,()=>{try{localStorage.setItem(st,n?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let i=ut(n),a={status:z(`status`),source:z(`source`),install:z(`install`),video:z(`video`),audio:z(`audio`),title:z(`title-line`),album:z(`album-line`),meta:z(`meta-line`),metaBlurb:z(`meta-blurb`),liveLine:z(`live-line`),downloadNow:z(`download-now`),wayInHere:z(`way-in-here`),embed:z(`embed`),embedFrame:z(`embed-frame`),linkForm:z(`link-form`),linkUrl:z(`link-url`),linkServer:z(`link-server`),linkGoLive:z(`link-go-live`),goLiveNow:z(`go-live-now`),elapsed:z(`elapsed`),total:z(`total`),seek:z(`seek`),fullscreen:z(`fullscreen`),copyNow:z(`copy-now`),copyNixamp:z(`copy-nixamp`),canvas:z(`spectrum`),glyphs:z(`glyphs`),levels:z(`levels`),playlist:z(`playlist`),livePlaylist:z(`live-playlist`),livePlaylistPanel:z(`live-playlist-panel`),playlistPager:z(`playlist-pager`),crumbs:z(`crumbs`),filter:z(`filter`),playlistTitle:z(`playlist-panel`),note:z(`note`),linkNote:z(`link-note`),logList:z(`log-list`),files:z(`files`),folder:z(`folder`),remoteUrl:z(`remote-url`),remoteServer:z(`remote-server`),remoteForm:z(`remote-form`),remoteState:z(`remote-state`),disconnect:z(`disconnect`),browse:z(`browse`),panelsToggle:z(`panels-toggle`),panelsPanel:z(`panels-panel`),panelsList:z(`panels-list`),panelsSave:z(`panels-save`),panelsReset:z(`panels-reset`),accountForm:z(`account-form`),accountEmail:z(`account-email`),accountPassword:z(`account-password`),accountSubmit:z(`account-submit`),accountToggle:z(`account-toggle`),accountProviders:z(`account-providers`),accountPanel:z(`account-panel`),accountElsewhere:z(`account-elsewhere`),welcome:z(`welcome`),welcomeCreate:z(`welcome-create`),welcomeBrowse:z(`welcome-browse`),welcomeHide:z(`welcome-hide`),accountSignOut:z(`account-signout`),accountNote:z(`account-note`),personaForm:z(`persona-form`),personaHandle:z(`persona-handle`),personaVoice:z(`persona-voice`),personaProfile:z(`persona-profile`),personaNote:z(`persona-note`),adminPanel:z(`admin-panel`),adminNote:z(`admin-note`),adminSaid:z(`admin-said`),adminConnections:z(`admin-connections`),publishPanel:z(`publish-panel`),publishNote:z(`publish-note`),publishList:z(`publish-list`),adminRestream:z(`admin-restream`),adminReplace:z(`admin-replace`),adminSource:z(`admin-source`),adminName:z(`admin-name`),adminAdd:z(`admin-add`),homeNote:z(`home-note`),loadHome:z(`load-home`),directory:z(`directory`),recentNote:z(`recent-note`),recentList:z(`recent-list`),followingNote:z(`following-note`),followingList:z(`following-list`),serversPanel:z(`servers-panel`),serversNote:z(`servers-note`),serversList:z(`servers-list`),favoritesPanel:z(`favorites-panel`),favoritesNote:z(`favorites-note`),favoritesList:z(`favorites-list`),favHere:z(`fav-here`),partiesPanel:z(`parties-panel`),partiesNote:z(`parties-note`),partiesList:z(`parties-list`),partyForm:z(`party-form`),partyCode:z(`party-code`),partyJoin:z(`party-join`),connectionsNote:z(`connections-note`),connectionsList:z(`connections-list`),catalogsPanel:z(`catalogs-panel`),catalogsNote:z(`catalogs-note`),catalogsForm:z(`catalogs-form`),catalogSource:z(`catalog-source`),catalogName:z(`catalog-name`),catalogsList:z(`catalogs-list`),catalogsCrumbs:z(`catalogs-crumbs`),catalogsFilter:z(`catalogs-filter`),catalogsEntries:z(`catalogs-entries`),notifyPanel:z(`notify-panel`),notifyNote:z(`notify-note`),notifyWeb:z(`notify-web`),notifyEmail:z(`notify-email`),notifySms:z(`notify-sms`),notifyPhone:z(`notify-phone`),notifyPhoneForm:z(`notify-phone-form`),notifyPhoneNote:z(`notify-phone-note`),directoryNote:z(`directory-note`),directoryList:z(`directory-list`),sharePanel:z(`share-panel`),trollboxPanel:z(`trollbox-panel`),trollboxNote:z(`trollbox-note`),trollboxList:z(`trollbox-list`),trollboxForm:z(`trollbox-form`),trollboxInput:z(`trollbox-input`),trollboxMic:z(`trollbox-mic`),trollboxEdit:z(`trollbox-edit`),trollboxEditLabel:z(`trollbox-edit-label`),transcriptPanel:z(`transcript-panel`),transcriptNote:z(`transcript-note`),transcriptOn:z(`transcript-on`),transcriptLanguage:z(`transcript-language`),transcriptAudio:z(`transcript-audio`),transcriptVoiceSettings:z(`transcript-voice-settings`),transcriptBackground:z(`transcript-background`),transcriptBackgroundLevel:z(`transcript-background-level`),transcriptBackgroundValue:z(`transcript-background-value`),transcriptAudioNote:z(`transcript-audio-note`),transcriptSpeakers:z(`transcript-speakers`),transcriptList:z(`transcript-list`),subtitle:z(`subtitle`),shareNote:z(`share-note`),shareLink:z(`share-link`),shareCopy:z(`share-copy`),sharePhone:z(`share-phone`),shareSend:z(`share-send`),liveControls:z(`live-controls`),goLive:z(`go-live`),stopLive:z(`stop-live`),shareTo:z(`share-to`),listenOnly:z(`listen-only`),listenHere:z(`listen-here`),volume:z(`volume`),volumeToggle:z(`volume-toggle`),prev:z(`prev`),playPause:z(`play-pause`),transport:z(`transport`),stop:z(`stop`),next:z(`next`),shareNow:z(`share-now`),refreshPlayer:z(`refresh-player`),appVersion:z(`app-version`)};a.appVersion.textContent=`nixamp 0.28.20`;let o=(e,t)=>{oe(e,t)};o(a.copyNixamp,`link`);let s=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,c=`local`,l=``,u=[],d=``,m=!0,h=``;function v(e){try{return new URL(e).origin}catch{return e}}let ee=!1,y=``,te=0,ne=new Map,re=e=>ne.get(U(e))??null;function ie(e,t){let n=n=>{ee=n,y=``,a.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),a.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,o(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`,o(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:K?`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 ae=``,b=[],le=0,x=Me(),ue=`idle`,S=``,w=`Pick files, or connect to a nixamp running somewhere else.`,fe=!1,T=-1,ge=null,_e=0,E=null;function ve(e){return e?/^https?:\/\//i.test(e)?e:P.url(e):``}let ye=0,be=0,xe=!1,Se=()=>!N.needsInteraction&&(be>0||xe);async function Ce(e){be+=1,B();try{return await e()}finally{--be,B()}}let D=null,O=null,we=``,Ee=null,De=``,k=null,A=null,ke=0;function je(){a.embed.hidden||(a.embedFrame.src=`about:blank`),a.embed.hidden=!0}let Pe=null,Re=``,ze=null;function Be(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Re=i,ze&&clearTimeout(ze),ze=null,!r){if(Pe?.key===i)return;Pe=null}if(c!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(P.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Re!==i)return;Pe={key:i,match:r.match??null},B();let a=Pe.match;a?.kind===`fixture`&&it(a)!==`post`&&(ze=setTimeout(()=>{ze=null,!(Re!==i||N.source===``&&!E)&&Be(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Ve=!1,He=``,We=``,Xe=null,Ze=``,rt=``,at=``,j=Array(24).fill(0),lt=Array(24).fill(0),ft=[],M=()=>c===`remote`&&!a.listenHere.checked,pt=()=>c===`remote`&&!a.adminPanel.hidden,mt=!1,gt=()=>pt()||c===`remote`&&mt;function vt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:a.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function St(){if(c!==`remote`||k)return null;if(D?.catalog&&D.entry)return{kind:`entry`,catalog:D.catalog,entry:D.entry};if(E)return{kind:`channel`,id:E.id,name:E.name};let e=x.tracks[I()];return e&&(N.source!==``||M())?{kind:`track`,index:I(),name:Qt(e)}:null}async function Ct(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;w=`Putting ${n} on the air…`,B();try{let r=``,i=``,a=!0;{let t=e.kind===`folder`?`/api/folders/live`: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(P.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),s=await o.json().catch(()=>({}));if(!o.ok){w=o.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:s.error??`${n} would not go on the air.`,B();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(pt()&&(Ve?await fetch(P.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await wo(!0)),await eo(),$(),i!==``&&E?.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 lo({id:i,name:n,video:a},!0,t)}let o=vo(r),s=He?` Call ${We||`the line`} and key ${He} to talk about it.`:``;o===``?w=`${n} is on the air and you are watching it.${s}`:(await _o(o,t,`✓`),w=`${n} is on the air and you are watching it. Link copied.${s}`),B()}catch{w=`could not reach the server`,B()}finally{t.disabled=!1}}function wt(e,t=`Join party`){o(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);g(n,()=>` ${p(t)}`),e.append(n),_(e,`title`,()=>p(/join/i.test(t)?`Join live`:t))}wt(a.partyJoin);function Wt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,o(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(),Ct(e(),n)}),n}let N=new Ae({audio:a.audio,video:a.video},{readable:e=>P.owns(e),onTime:(e,t)=>{let n=b[le];c===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),B()},onEnded:()=>{uo()||qn()||gn()||c===`remote`&&T<0&&!M()||bn(1)},onState:()=>B(),onBusy:e=>{xe!==e&&(xe=e,B())},onError:e=>{if(!uo()&&!(ke!==0&&Date.now()-ke<2e3)){if(A&&e===`this browser cannot play that format`){let e=A.url;if(A=null,ke=Date.now(),gt()){w=`That site will not let a page play it directly; going live with it on ${l||`the server`} instead.`,B(),a.linkUrl.value=e,Qn();return}w=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,B();return}w=e,B(),so()}}}),Gt=()=>M()&&!N.jinglePlaying,P=new Ue({onSnapshot:e=>{let t=e.tracks!==void 0||x.index!==e.index;if(x=Ne(x,e),y.startsWith(`track:`)&&x.tracks.length>0){let e=Number(y.slice(6));if(y=``,Number.isInteger(e)&&e>=0&&e<x.tracks.length){let t=te;vn(e).then(()=>{t>0&&(N.seek(t),setTimeout(()=>N.seek(t),600))})}}Gt()&&(j=e.bars.length>0?e.bars:j,lt=tt(lt,j)),B(),t&&O&&ao(O)},onStatus:(e,t)=>{ue=e,S=t??``,B()}}),F=()=>c===`remote`?x.tracks.length:b.length,I=()=>c===`remote`?M()||T<0?x.index:Math.min(T,Math.max(0,x.tracks.length-1)):le,Jt=()=>{let e=O?.server.nowPlaying||`Live`;return(!Ee||Ee.tracks!==x.tracks||Ee.index!==x.index||Ee.fallback!==e)&&(Ee={tracks:x.tracks,index:x.index,fallback:e,value:he(x.tracks,x.index,e)}),Ee.value},L=()=>c===`remote`&&!E&&D?.kind===`live`,R=()=>L()?Jt().fullTitle:en(),Qt=e=>{let t=ce(e);return e.folder?`${e.folder} / ${t}`:t},en=()=>{if(E){let e=E.id,t=O?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||E.name}if(k)return k.label;if(L())return Jt().title;let e=c===`remote`?x.tracks[I()]:b[I()];return e?Qt(e):p(`Nothing loaded.`)},tn=()=>{if(E)return`live on this server`;if(k)return`playing here, in this browser`;if(L()){let{context:e,position:t}=Jt();return[e,t,`live on ${l||`this server`}`].filter(Boolean).join(` · `)}return(c===`remote`?x.tracks[I()]:b[I()])?.album||`—`};function nn(){if(c!==`remote`||E===null&&D?.kind!==`live`){a.liveLine.hidden=!0,a.liveLine.replaceChildren(),delete a.liveLine.dataset.drawn;return}let e=l||`this server`,t=E?E.name:Jt().fullTitle,n=[E?`Live on ${e}: `:`Live from ${e}, now playing: `,To(t)],r=E?O?.channels.find(e=>e.id===E?.id)?.code??``:Ve?He:``;r&&n.push(`. To talk about it, call `,To(We||`the line`),` and key `,To(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);a.liveLine.dataset.drawn!==i&&(a.liveLine.dataset.drawn=i,a.liveLine.hidden=!1,a.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let rn=()=>M()?x.tracks[I()]?.duration??0:N.duration,an=()=>M()?x.position:N.position,on=()=>M()?x.playing:N.playing;async function hn(e){if(c===`remote`){if(M()){await P.send({type:`play`,index:e});return}await vn(e);return}let t=b[e];t&&(le=e,E=null,D={kind:`file`},await Ce(()=>N.load(t,!0)),Hn(t.video),Un(),B())}function gn(){return!ge||ge.length<2?!1:(_e=(_e+1)%ge.length,hn(ge[_e]),!0)}function _n(e){e.length!==0&&(ge=[...e],_e=0,hn(ge[0]))}async function vn(e){let t=x.tracks[e];t&&(T=e,E=null,D={kind:`file`},Be(t.title,`auto`),await Ce(()=>N.load({title:Qt(t),artist:t.artist,album:t.album,duration:t.duration,url:P.media(e,0),video:t.video===!0,objectUrl:!1},!0)),Hn(t.video===!0),Un())}async function yn(){if(N.needsInteraction){await N.play(),B();return}if(M()){await P.send({type:`toggle`});return}F()!==0&&(N.playing?N.pause():N.position>0?await N.play():await hn(I()),B())}async function bn(e){ge=null;let t=F();if(t!==0){if(M()){await P.send({type:e>0?`next`:`prev`});return}await hn((I()+e+t)%t)}}async function xn(){if(ge=null,je(),k=null,A=null,M()){await P.send({type:`stop`});return}E=null,D=null,N.stop(),j=Array(24).fill(0),lt=[...j],B()}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)))],wn=``;function Tn(){let e=[],t=``,n=null,r=E?O?.channels.find(e=>e.id===E?.id):void 0;E&&r?.ended&&De!==E.id&&(De=E.id,Mr(`${E.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=N.source===``&&!E&&!(M()&&x.tracks[I()]);if(!i){E&&r?.ended?e.push(`ENDED`):E?e.push(D?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):D?.kind===`vod`?e.push(`ON DEMAND`):D?.kind===`live`?e.push(`LIVE`):c===`remote`&&M()?e.push(`ON THE SERVER`):e.push(`FILE`),!a.video.hidden&&a.video.videoWidth>0?e.push(`${a.video.videoWidth}×${a.video.videoHeight}`):a.video.hidden?e.push(`audio`):e.push(`video`),r?(e.push(r.via===`pull`?`${r.listeners} watching`:`${r.listeners} listening · over ${r.via}`),r.startedAt>0&&e.push(`on air ${se(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),pt()&&r.error&&e.push(r.error)):c===`remote`&&!E?(x.tracks[I()]&&F()>0&&e.push(`${L()?`library track`:`track`} ${I()+1} of ${F()}`),M()&&O&&e.push(`${O.server.playing?`playing`:`stopped`} on ${l||`the server`}`)):c===`local`&&F()>0&&e.push(`track ${I()+1} of ${F()}`),D?.catalog!==void 0&&(D.kind===`channel`?E!==null:D.kind===`vod`&&N.source!==``)&&D?.catalog&&(e.push(D.entry?.group?`${D.catalog.name} › ${D.entry.group}`:D.catalog.name),t=D.entry?.logo??``),t===``&&E&&(t=ve(r?.art??E.art));let i=Pe?.key===Re?Pe.match:null;if(i?.kind===`fixture`)n=ot(i),e.unshift(n.status,...n.chips);else if(i){i.image&&(t=i.image);let n=i.data;if(i.kind===`title`){i.year&&e.push(String(i.year));let t=typeof n.rating==`number`?n.rating:null;t&&e.push(`★ ${t.toFixed(1)}`);let r=Array.isArray(n.genres)?n.genres.slice(0,2).map(String):[];r.length&&e.push(r.join(` · `));let a=typeof n.runtimeMin==`number`?n.runtimeMin:0;a&&e.push(`${a} min`)}else if(i.kind===`channel`){let t=typeof n.country==`string`?n.country:``,r=Array.isArray(n.categories)?n.categories.slice(0,2).map(String):[],i=typeof n.network==`string`?n.network:``;t&&e.push(t),r.length&&e.push(r.join(` · `)),i&&e.push(i)}}if(E&&D?.link){let t=``;try{t=new URL(D.link.url).hostname.replace(/^www\./,``)}catch{}e.push(D.link.extractor&&D.link.extractor!==`direct`&&D.link.extractor!==`generic`?`${D.link.extractor} · ${t}`:t||`link`)}Ve&&He&&M()&&!E&&D?.kind!==`live`&&e.push(We?`☎ ${We} · key ${He}`:`☎ code ${He}`)}let o=Pe?.key===Re?Pe.match:null,s=!i&&!n&&o?.summary?o.summary:``,u=e.map(e=>/^on air \d/.test(e)?`on air`:e),d=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${u.join(`|`)}|${s}`;if(d===wn){let t=a.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}wn=d,a.meta.hidden=e.length===0,a.metaBlurb.textContent=s,a.metaBlurb.hidden=s===``;let f=[];if(n){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let r=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,r.push(i),n?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),r.push(t)}if(e.logo!==``){let n=document.createElement(`img`);n.className=`meta-team-logo`,n.alt=``,n.src=e.logo,n.addEventListener(`error`,()=>{n.hidden=!0}),t?r.unshift(n):r.push(n)}return r},r=document.createElement(`span`);r.className=`meta-dash`,r.textContent=`–`,e.replaceChildren(...t(n.away,!0),r,...t(n.home,!1)),f.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=o?.kind===`title`&&t===o.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let t of e){let e=document.createElement(`span`);e.className=/^on air \d/.test(t)?`meta-chip meta-chip-clock`:n?.state===`in`&&t===n.status?`meta-chip chip-live`:`meta-chip`,e.textContent=t,f.push(e)}a.meta.replaceChildren(...f)}function B(){let e=F(),t=on(),n=Se();g(a.status,()=>p(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),a.status.dataset.playing=n?`loading`:String(t),g(a.title,()=>en()),a.title.classList.toggle(`with-context`,L()),a.album.classList.toggle(`with-context`,L()),(L()||E)&&Un(),nn(),Tn(),a.goLiveNow.hidden=!gt()||E!==null||L()||St()===null;let r=t?`${R()} · ${s}`:s;document.title!==r&&(document.title=r),a.copyNow.hidden=N.source===``,a.copyNixamp.hidden=Vi()===``,a.shareNow.hidden=Bi()===``,yi(),Mi(),a.downloadNow.hidden=!(E&&D?.link?.download),Yn(),a.album.textContent=tn();let i=an(),o=rn();a.elapsed.textContent=se(i),a.total.textContent=o>0?se(o):`--:--`,fe||(a.seek.value=String(o>0?Math.round(i/o*1e3):0),a.seek.disabled=o<=0||M()),a.playPause.textContent=t?`❚❚`:`▶`,_(a.playPause,`aria-label`,()=>p(t?`Pause`:`Play`)),_(a.seek,`aria-valuetext`,()=>`${se(N.position)} ${f.language===`en`?`of`:`/`} ${se(N.duration)}`),_(a.volume,`aria-valuetext`,()=>f.number(Number(a.volume.value)/100,{style:`percent`})),_(a.playlistTitle,`data-title`,()=>c===`remote`?`Files on ${l||`this server`} (${e.toLocaleString(f.language)})`:`${p(`Playlist`)} (${f.number(e)})`),g(a.source,()=>c===`remote`?`connected · ${l||P.address.replace(/^https?:\/\//,``)||`—`}`:b.length>0?`local · ${b.length} files`:p(`no source`)),Vn(),g(a.remoteState,()=>c===`remote`?`${ue}${S?` — ${S}`:``}`:p(`not connected`)),a.remoteState.dataset.status=c===`remote`?ue:`idle`,a.disconnect.hidden=c!==`remote`;let u=N.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:c===`remote`&&x.note!==``?x.note:w;a.note.textContent=u,a.note.hidden=u===``,a.linkNote.textContent=u,a.linkNote.hidden=u===``,Mr(u),Fn(),a.glyphs.textContent=j.map(Cn).join(``);let[d,m]=Gt()?x.levels:N.levels();a.levels.textContent=Sn(d,m)}let En=``,V=``,Dn=0;function On(e){de(a.playlist),V=e,Dn=0,En=``,Fn()}function kn(e,t,n,r,i){if(a.playlistPager.hidden=n<=1,n<=1){a.playlistPager.replaceChildren();return}let o=(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`,()=>{de(a.playlist),Dn=t,En=``,Fn()}),i},s=document.createElement(`span`);s.className=`pager-where`,g(s,()=>`${r+1}–${i} of ${e.toLocaleString(f.language)}`),a.playlistPager.replaceChildren(o(`‹ Previous`,t-1,`The page before this one`),s,o(`Next ›`,t+1,`The page after this one`))}function An(e){if(a.crumbs.hidden=!e,!e)return;let t=V===``?[]:V.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`,()=>On(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))}),a.crumbs.replaceChildren(...r)}function jn(e,t,n){let r=document.createElement(`li`);r.className=`folder`;let i=document.createElement(`span`);i.className=`name`,i.textContent=`${e}/`;let a=document.createElement(`span`);a.className=`count`,a.textContent=`${t} file${t===1?``:`s`}`,r.append(i,a);let s=document.createElement(`button`);if(s.type=`button`,s.className=`row-main`,s.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),s.append(i,a),r.replaceChildren(s),s.addEventListener(`click`,t=>{t.stopPropagation(),On(V===``?e:`${V}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,o(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),_n(n)}),r.append(i)}return c===`remote`&&n.length>0&&gt()&&r.append(Wt(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let Mn=null,Nn=``,Pn=(e,t)=>{t.title=t.textContent??``,cn(e,t)};function Fn(){let e=E?O?.channels.find(e=>e.id===E?.id):void 0,t=e?.playlist;if(a.livePlaylistPanel.hidden=!(E&&t&&t.length>0),E&&t&&t.length>0){let n=t.map((t,n)=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`n`,i.textContent=String(n+1).padStart(2,` `);let a=t.lastIndexOf(`/`),o=document.createElement(`span`);o.className=`name row-file`,o.textContent=a<0?t:t.slice(a+1);let s=document.createElement(`span`);s.className=`row-path`,s.textContent=t;let c=document.createElement(`span`);c.className=`row-label`;let l=document.createElement(`span`);l.className=`row-value`,l.append(o);let u=document.createElement(`span`);return u.className=`row-value`,u.append(s),c.append(l),Pn(l,o),Pn(u,s),r.append(i,c),r.setAttribute(`aria-readonly`,`true`),r.title=e.live===!1?`Part of this on-demand show`:`Live queue (read-only)`,n===(e.entry??0)&&r.setAttribute(`aria-current`,`true`),r});C(a.livePlaylist,...n)}else a.livePlaylist.replaceChildren();let n=c===`remote`?x.tracks:b,r=`${c}:${E?.id??``}:${t?.join(`|`)??``}:${e?.entry??0}:${V}:${a.filter.value}:${Dn}:${gt()}:${a.adminPanel.hidden}`;if(En&&Mn===n&&Nn===r){In();return}Mn=n,Nn=r;let s=c===`remote`?x.tracks.map(e=>({name:ce(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):b.map(e=>({name:ce(e),seconds:e.duration,group:``,folder:``,remote:!1})),l=a.filter.value.trim().toLowerCase(),u=s.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>l===``||`${e.folder}/${e.name}`.toLowerCase().includes(l)),d=e=>l!==``||V===``||e===V||e.startsWith(`${V}/`),f=e=>e===V,p=e=>{let t=V===``?e:e.slice(V.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},m=new Map;for(let e of u){if(!d(e.folder)||f(e.folder))continue;let t=p(e.folder);t!==``&&m.set(t,(m.get(t)??0)+1)}let h=u.filter(e=>f(e.folder)&&d(e.folder)),g=[...m].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),_=dt(g.length+h.length,Dn,i);Dn=_.page;let v=g.slice(_.from,_.to),ee=h.slice(Math.max(0,_.from-g.length),Math.max(0,_.to-g.length)),y=`${c}:${V}:${l}:${_.page}/${i}:${g.join(`,`)}:${h.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(y!==En){En=y,An(l===``&&(g.length>0||V!==``)),kn(g.length+h.length,_.page,_.pages,_.from,_.to);let e=[];for(let[t,n]of v){let r=V===``?t:`${V}/${t}`,i=u.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(jn(t,n,i))}let t=``,n=h.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(Ln(r.group)));let i=document.createElement(`li`);i.className=`row`,i.dataset.index=String(r.index);let a=document.createElement(`span`);a.className=`n`,a.textContent=String(r.index+1).padStart(2,` `);let s=r.folder?`${r.folder} / ${r.name}`:r.name,l=document.createElement(`span`);l.className=`name row-file`,l.textContent=r.name;let u=document.createElement(`span`);u.className=`row-path`,u.textContent=r.folder?`${r.folder}/${r.name}`:r.name;let d=document.createElement(`span`);d.className=`row-label`;let f=document.createElement(`span`);f.className=`row-value`,f.append(l);let p=document.createElement(`span`);p.className=`row-value`,p.append(u),d.append(f,p),Pn(f,l),Pn(p,u);let m=document.createElement(`span`);m.className=`time`,m.textContent=r.seconds>0?se(r.seconds):`--:--`;let h=document.createElement(`button`);h.type=`button`,h.className=`row-main`,h.setAttribute(`aria-label`,`Play ${s}${r.seconds>0?`, ${se(r.seconds)}`:``}`),h.append(a,d,m),i.append(h);let g=document.createElement(`span`);g.className=`row-play-glyph`,o(g,`play`),i.append(g),c===`remote`&&gt()&&E===null&&!L()&&i.append(Wt(()=>({kind:`track`,index:r.index,name:s}),s)),i.classList.add(`file-row`),i.append(p),e.push(i)}C(a.playlist,...e)}In()}function In(){let e=E?O?.channels.find(e=>e.id===E?.id):void 0;if(e?.playlist&&e.playlist.length>0){let t=e.entry??0;for(let e of Array.from(a.playlist.children)){let n=e,r=Number(n.dataset.index),i=Number.isInteger(r)&&r===t;n.classList.toggle(`selected`,i),n.classList.toggle(`playing`,!1),i?n.setAttribute(`aria-current`,`true`):n.removeAttribute(`aria-current`)}return}let t=I(),n=on();for(let e of Array.from(a.playlist.children)){let r=e,i=Number(r.dataset.index),a=Number.isInteger(i)&&i===t;r.classList.toggle(`selected`,a),r.classList.toggle(`playing`,a&&n),a?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}}function Ln(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!==``&&!a.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`,r=>{r.stopPropagation(),go(t,n,()=>Rn(e),()=>Fn())}),t.append(n)}return t}async function Rn(e){try{let t=await fetch(P.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();return H(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`),t.ok}catch{return H(`could not reach the server`),!1}}function zn(){let e=a.canvas,t=Math.min(2,globalThis.devicePixelRatio||1),n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);n>0&&r>0&&(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);if(Gt())lt=tt(lt,j);else{let e=N.read();e.length>0&&(ft.length!==25&&(ft=Qe(24,e.length)),j=et(j,$e(e,ft)),lt=tt(lt,j))}if(i){let t=getComputedStyle(document.documentElement);nt(i,{width:e.width,height:e.height},j,lt,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(on()||N.jinglePlaying){a.glyphs.textContent=j.map(Cn).join(``);let[e,t]=Gt()?x.levels:N.levels();a.levels.textContent=Sn(e,t)}if(on()){a.elapsed.textContent=se(an());let e=rn();!fe&&e>0&&(a.seek.value=String(Math.round(an()/e*1e3)))}requestAnimationFrame(zn)}let Bn=``;function Vn(){if(c!==`remote`){a.wayInHere.hidden=!0,Bn=``;return}let e=pt()&&!ee,t=ae||P.address,n=e?null:re(P.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Bn)return;Bn=r;let[i,o]=ie({name:l||`this server`,view:t,admin:n});i.hidden=!e,o.hidden=e,a.wayInHere.replaceChildren(i,o),a.wayInHere.hidden=!1}function Hn(e){a.video.hidden=!e,a.fullscreen.hidden=!e,je(),k=null,A=null}function Un(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=E?ve(O?.channels.find(e=>e.id===E?.id)?.art??E.art):``,t=JSON.stringify([en(),tn(),e]);t!==we&&(we=t,navigator.mediaSession.metadata=new MediaMetadata({title:en(),album:tn(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void yn()),navigator.mediaSession.setActionHandler(`pause`,()=>void yn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void bn(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void bn(-1)))}document.addEventListener(`click`,()=>{N.resumeAfterInteraction().catch(()=>{})}),a.filter.addEventListener(`input`,()=>{Dn=0,En=``,Fn()}),a.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())}),a.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(ge=null,hn(n))}),a.fullscreen.addEventListener(`click`,()=>{let e=a.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),a.prev.addEventListener(`click`,()=>void bn(-1)),a.next.addEventListener(`click`,()=>void bn(1)),a.stop.addEventListener(`click`,()=>void xn()),a.playPause.addEventListener(`click`,()=>void yn());async function Wn(e){let t=yt(e,vt());if(!t){if(!gt()){w=c===`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.`,B();return}await Jn(e);return}if(E=null,N.stop(),t.kind===`embed`){D={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},Hn(!1),a.embedFrame.src=t.src,a.embed.hidden=!1,k={url:e,label:t.label,kind:`embed`},w=`Playing ${t.label} here, in this browser.`,B();return}if(t.kind===`list`){await Gn(e,t.label);return}D={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await Ce(()=>N.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),Hn(t.video),k={url:e,label:t.label,kind:`direct`},w=`Playing ${t.label} here, in this browser.`,B()}async function Gn(e,t){w=`Reading ${t}…`,B();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){w=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,B();return}let r=_t(n,e);if(r.entries.length===0){w=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,B();return}A={url:e,title:r.title||t,entries:r.entries,at:0},await Kn()}async function Kn(){let e=A,t=e?.entries[e.at];if(!e||!t)return;let n=ht(t.url);D={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await Ce(()=>N.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),A!==null&&(Hn(n),k={url:e.url,label:e.title,kind:`direct`},A=e,w=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,B())}function qn(){let e=A;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Kn(),!0)}async function Jn(e){if(c!==`remote`){w=`Pick a server to go live on, or connect to one, to put a link on the air.`,B();return}w=`Asking ${l||`the server`} to fetch ${e}…`,B(),await Ce(async()=>{let t,n={};try{t=await fetch(P.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{w=`could not reach the server`;return}if(!t.ok||!n.channel){w=n.error??`that link would not play.`;return}try{await fetch(P.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await lo({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&&(w=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),B()}a.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.linkUrl.value.trim();t!==``&&Wn(t)});function Yn(){let e=c===`remote`?P.address:``,t=u.filter(t=>v(t.url)!==v(e)),n=JSON.stringify({here:e,name:l,carries:m,others:t});if(n===d||document.activeElement===a.linkServer)return;d=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${l||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)}a.linkServer.replaceChildren(...r),a.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,a.linkServer.hidden=t.length===0}function Xn(){let e=c===`remote`?v(P.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!u.some(t=>v(t.url)===e)){let n=document.createElement(`option`);n.value=P.address,n.textContent=l||e,t.push(n)}for(let e of u){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}a.remoteServer.replaceChildren(...t);let r=u.find(t=>v(t.url)===e);a.remoteServer.value=r?.url??``}async function Zn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;u=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Yn(),Xn()}catch{}}async function Qn(){let e=a.linkUrl.value.trim()||k?.url||``;if(e===``){w=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,B();return}let t=a.linkServer.value;if(t!==``&&(c!==`remote`||v(t)!==v(P.address))){let n=u.find(e=>e.url===t)?.name??t;h=e,w=`Connecting to ${n} to go live with it…`,B(),$n(t);return}if(c!==`remote`){w=u.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.`,B();return}if(!m){w=`${l||`This server`} has no ffmpeg, so it cannot carry a link.`+(u.length>0?` Pick a server to go live on, beside the link.`:``),B();return}if(!gt()){w=`Sign in to nixamp.com to go live here, or use the server's control link.`,B();return}await Jn(e)}function $n(e){let t=a.linkUrl.value.trim();ee=!0,y=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit(),a.linkUrl.value=t}a.linkGoLive.addEventListener(`click`,()=>{Qn()}),a.linkServer.addEventListener(`change`,()=>{let e=a.linkServer.value;e!==``&&$n(e)}),a.downloadNow.addEventListener(`click`,()=>{let e=D?.link;if(!e||c!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(P.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),w=`Fetching it through the server; your browser will save it when it arrives.`,B()}),a.goLiveNow.addEventListener(`click`,()=>{let e=St();e&&Ct(e,a.goLiveNow)}),a.seek.addEventListener(`input`,()=>{fe=!0}),a.seek.addEventListener(`change`,()=>{let e=rn();e>0&&N.seek(Number(a.seek.value)/1e3*e),fe=!1}),a.volume.addEventListener(`input`,()=>{let e=Number(a.volume.value)/100;N.volume=e,a.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),a.volumeToggle.textContent=e===0?`🔇`:`🔊`,_(a.volumeToggle,`aria-label`,()=>p(e===0?`Unmute`:`Mute`));try{localStorage.setItem(dn,String(e))}catch{}}),a.volumeToggle.addEventListener(`click`,()=>{let e=Number(a.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(dn));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}a.volume.value=e?String(t):`0`,a.volume.dispatchEvent(new Event(`input`))}),a.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let er=e=>{e.addEventListener(`change`,()=>{let t=Te(Array.from(e.files??[]));if(t.length===0){w=`Nothing playable in that selection.`,B();return}Oe(b),b=t,le=0,c=`local`,P.close(),io(!1),w=``,hn(0)})};er(a.files),er(a.folder),a.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.remoteUrl.value,{base:n,key:r}=Le(t);if(n===``){w=`That is not an address.`,B();return}(async()=>{ue=`connecting`,B();let e=Ye(n);if(e){ue=`error`,S=e,w=e,h=``,c=`local`,B();return}if(await Je(n,void 0,r)===null){ue=`error`;let e=Ke(n);S=e?`needs the server's name`:`not answering`,w=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,h=``,c=`local`,B();return}let i=await qe(n,r);if(i){ue=`error`,S=i,w=i,h=``,c=`local`,B();return}c=`remote`,w=``;try{localStorage.setItem(ln,t.trim())}catch{}P.connect(t),io(!0),ea(),fr(),eo(),B()})()}),a.remoteServer.addEventListener(`change`,()=>{let e=a.remoteServer.value;e!==``&&(ee=!1,y=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit())});let tr=``,nr=null,rr=async(e=!1)=>{a.directory.hidden=!1,e||(a.directoryNote.textContent=`Looking for live streams…`,C(a.directoryList)),nr||=setInterval(()=>{!a.directory.hidden&&document.visibilityState===`visible`&&rr(!0)},pn);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??[],u=t.map(e=>({name:e.name,url:e.url})),Yn();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:K});if(e&&i===tr)return;tr=i,hr(r.recent??[])}catch{e||(a.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(C(a.directoryList),t.length===0){a.directoryNote.textContent=`Nobody is streaming right now.`;return}a.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 s=[`${e.tracks.toLocaleString(f.language)} files to browse`];e.playing!==!1&&e.nowPlaying?s.push(`playing ${e.nowPlaying}`):s.push(`player idle`),e.code&&s.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=s.join(` · `),i.title=i.textContent,n.append(r,i);let c=e.admin??re(e.url),l=(t,n=``)=>{ee=t,y=n,a.remoteUrl.value=t?e.url:c??e.url,a.directory.hidden=!0,document.body.classList.remove(`route-directory`),a.remoteForm.requestSubmit()},u=document.createElement(`ul`);u.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 s=e.lineup?.find(e=>e.name===t);if(s?.art&&/^https?:\/\//i.test(s.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=s.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}s?.about&&(r.title=s.about);let d=document.createElement(`button`);d.type=`button`,d.className=`icon`,o(d,`party`),d.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),d.title=`Join live: ${t} on ${e.name}`,d.addEventListener(`click`,()=>l(!0,`channel:${t}`));let f=document.createElement(`button`);f.type=`button`,f.className=`icon`,o(f,`link`),f.setAttribute(`aria-label`,`Copy live room link for ${t}`),f.title=`Copy a nixamp link to this live room`;let p=`${globalThis.location.origin}/?url=${encodeURIComponent(e.url)}&play=${encodeURIComponent(`channel:${s?.id??t}`)}`;f.addEventListener(`click`,e=>{e.stopPropagation(),_o(p,f,`✓`)});let m=document.createElement(`button`);m.type=`button`,m.className=`icon`,o(m,`copy`),m.setAttribute(`aria-label`,`Copy raw stream URL for ${t}`),m.title=`Copy the raw stream URL for VLC or another player`;let h=e.url;try{let n=new URL(e.url);n.pathname=`/api/channels/${encodeURIComponent(s?.id??t)}`,h=n.toString()}catch{}if(m.addEventListener(`click`,e=>{e.stopPropagation(),_o(h,m,`✓`)}),n.append(r,d,f,m),s?.startedBy&&K&&s.startedBy===K&&c){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,o(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),l(!1,`channel:${s?.id??t}`)}),n.append(e)}u.append(n)}let[d,p]=ie({name:e.name,view:e.url,admin:c},()=>{a.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(n,d,p),K&&t.append(Ar(e.url,e.name)),e.ownerId&&K&&e.ownerId!==K&&t.append(ma(e.ownerId,e.name)),u.childElementCount>0&&t.append(u),e.ownerId&&K&&e.ownerId===K){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(()=>({}));a.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{a.directoryNote.textContent=`could not reach the directory`}finally{await rr()}})()}),t.append(n)}a.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!a.directory.hidden&&rr(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),rr()}let ir=null,ar=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,or=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,sr=``,cr=``,lr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===sr)return;sr=t,a.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)}a.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,``],[ar(t.network),`network-${t.network}`],[or(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)}a.adminConnections.append(e)}};function H(e){a.adminSaid.textContent=e,a.adminSaid.hidden=e===``}let ur=async()=>{try{let e=await fetch(P.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;a.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,lr(t.connections??[]),dr(t.publish??[],(t.channels??[]).map(e=>e.id)),Co(t.home??``,t.root??``),$()}catch{a.adminNote.textContent=`lost touch with the server`}};function dr(e,t){a.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===cr)return;if(cr=n,e.length===0){C(a.publishList);return}let r=e.length-t.length;a.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,C(a.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`,g(o,()=>p(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let fr=async()=>{if(c!==`remote`){a.adminPanel.hidden=!0,a.publishPanel.hidden=!0,ir&&clearInterval(ir),ir=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(P.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(ee&&(e=!1),mt=i&&!e,a.adminPanel.hidden=!e,$a(e),h!==``){let e=h;h=``,gt()?Jn(e):(w=`Sign in to nixamp.com to go live here.`,B())}if(ir&&clearInterval(ir),ir=null,$(),ea(),eo(),a.listenOnly.hidden=e,!e){a.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}a.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,ur(),ir=setInterval(()=>void ur(),2e3)};function pr(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)}`;H(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(P.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}:{}})}),o=await i.json();if(!i.ok){H(o.error??`that did not work`);return}H(`${o.channel?.name||t||e} is on the air.`),a.adminSource.value=``,a.adminName.value=``,eo(),$()}catch{H(`could not reach the server`)}})()}a.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=a.adminSource.value.trim();t&&pr(t,a.adminName.value.trim())}),a.adminAdd.addEventListener(`click`,()=>{let e=a.adminSource.value.trim();if(!e)return;H(`Reading ${e}…`);let t=a.adminReplace.checked,n=a.adminName.value.trim();(async()=>{try{let r=await fetch(P.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();H(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&&(a.adminSource.value=``,a.adminName.value=``,eo(),$())}catch{H(`could not reach the server`)}})()});let mr=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`},hr=e=>{let t=[],n=K?e.filter(e=>e.ownerId&&e.ownerId!==K):[];if(a.recentNote.hidden=n.length===0,n.length===0){C(a.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 ${mr(e.endedAt)}`:`ended ${mr(e.endedAt)}`,r.append(i,a),n.append(r,ma(e.ownerId,e.name)),t.push(n)}C(a.recentList,...t)},gr=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 _r(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?`▶ ${gr(e.party.positionNow)}`:`❚❚ ${gr(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`);o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.className=`party-row`,n.className=`party-name`,n.title=i.textContent,i.hidden=!0;let s=document.createElement(`details`);s.className=`party-actions`;let c=document.createElement(`summary`);return c.textContent=`⋯`,_(c,`aria-label`,()=>`${p(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let vr=[],yr=[],br=!1,xr=null,Sr=``;function Cr(){let e=new Map,t=(t,n,r)=>{if(!r.length)return;let i=e.get(t);if(i){let e=new Set(i.rows.map(e=>e.dataset.liveKey));i.rows.push(...r.filter(t=>!e.has(t.dataset.liveKey)))}else e.set(t,{name:n,rows:r})},n=c===`remote`&&O?v(P.address):``;for(let e of vr){let r=v(e.url);if(!r||r===n)continue;let i=[],o=(t,n)=>{let o=document.createElement(`li`);o.dataset.liveKey=`${r}:${t}`,o.className=`party-row`;let s=document.createElement(`span`);s.className=`party-name`,s.textContent=n,s.title=n;let c=document.createElement(`button`);c.type=`button`,wt(c),_(c,`aria-label`,()=>`${p(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{ee=!0,y=t,a.remoteUrl.value=e.url,a.remoteForm.requestSubmit()}),o.append(s,c),i.push(o)};e.playing!==!1&&e.nowPlaying&&o(`live`,me(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);o(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&O&&t(n,O.server.name||l||n,oo(O));for(let e of yr){let n=e.party.origin;try{n=new URL(e.links.partyUrl||e.party.partyUrl).origin}catch{}let r=e.party.origin;try{r=new URL(n).hostname}catch{}let i=_r(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...a.partiesList.children].map(e=>[e.dataset.liveKey,e])),i=[];for(let[t,n]of e){let e=r.get(t);if(!e){e=document.createElement(`li`),e.dataset.liveKey=t,e.className=`party-server`;let n=document.createElement(`h3`),r=document.createElement(`ul`);r.className=`party-rows`,e.append(n,r)}let a=e.querySelector(`h3`);a.textContent!==n.name&&(a.textContent=n.name),pe(e.querySelector(`ul`),n.rows),i.push(e)}pe(a.partiesList,i),a.partiesNote.hidden=e.size>0,e.size||g(a.partiesNote,()=>p(br?`No parties live right now.`:`Loading…`))}async function wr(){if(e||(Sr!==K&&(xr?.abort(),xr=null,yr=[],Sr=K,Cr()),xr))return;let t=new AbortController;xr=t;let n=K,r=setTimeout(()=>t.abort(),8e3),i=async e=>{let n=await fetch(e,{signal:t.signal,cache:`no-store`});return{ok:n.ok,status:n.status,body:n.ok?await n.json():null}};try{let[e,r]=await Promise.allSettled([i(`/api/directory`),n?i(`/api/v1/watch-parties`):Promise.resolve(null)]);if(xr!==t||n!==K||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(vr=e.value.body.streams??[],br=!0,a.directory.dataset.available=String(vr.length>0),Za()),r.status===`fulfilled`&&r.value&&(r.value.ok?(yr=r.value.body.parties??[],br=!0):[401,403].includes(r.value.status)&&(yr=[])),Cr(),!br&&!O&&g(a.partiesNote,()=>p(`Could not refresh parties.`))}finally{clearTimeout(r),xr===t&&(xr=null)}}a.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){w=n.error??`No party found with that invite code.`,B();return}a.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{w=`Could not look up that party. Try again.`,B()}})()});async function Tr(){if(!K){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];a.connectionsNote.hidden=t.length===0,a.connectionsList.hidden=t.length===0,C(a.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`,g(a,()=>p(`Disconnect`)),a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Tr()})()}),t.append(n,a),t}))}catch{a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0}}let Er=new Set,U=e=>{try{return new URL(e).origin}catch{return e}},Dr=e=>[...Er].some(t=>U(t)===U(e));async function Or(){if(!K){Er=new Set,a.favoritesPanel.hidden=!0,jr();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){a.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];Er=new Set(t.map(e=>e.url)),a.favoritesPanel.hidden=t.length===0,a.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,C(a.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,...ie({name:e.name||e.url,view:e.url,admin:re(e.url)}),Ar(e.url,e.name)),t}))}catch{a.favoritesPanel.hidden=!0}jr()}async function kr(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){w=n?`Could not save that favourite.`:`Could not remove that favourite.`,B();return}}catch{w=`could not reach nixamp.com`,B();return}if(n)Er.add(e);else for(let t of[...Er])U(t)===U(e)&&Er.delete(t);await Or()}function Ar(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Dr(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=>U(t)===U(e))??e;kr(Dr(e)?i:e,t,!Dr(e)).then(r)}),n}function jr(){let e=c===`remote`?P.shareLink:``;if(a.favHere.hidden=!(K&&e),a.favHere.hidden)return;let t=Dr(e);a.favHere.textContent=t?`♥`:`♡`,a.favHere.dataset.on=t?`yes`:`no`,a.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,a.favHere.setAttribute(`aria-label`,a.favHere.title)}o(a.copyNow,`copy`),a.copyNow.addEventListener(`click`,()=>{_o(N.source,a.copyNow,`✓`)});function Mr(e){if(e===``||e===at)return;at=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),g(n,()=>r.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}));let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),a.logList.prepend(t);a.logList.children.length>100;)a.logList.lastElementChild?.remove()}let Nr=3e3,W=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,Pr=``,Fr=``,Ir=null,Lr=!1,Rr=new Set,zr=``,Br=null,Vr=!1,Hr=Ht(e=>localStorage.getItem(e)),G=Lt(e=>localStorage.getItem(e)),Ur=new Set,Wr=new Set,Gr=null,Kr=``,qr=``,K=``,Jr=(()=>{try{let e=sessionStorage.getItem(`nixamp.translationSession`);if(e&&/^listener-[a-f0-9-]{36}$/.test(e))return e;let t=`listener-${crypto.randomUUID()}`;return sessionStorage.setItem(`nixamp.translationSession`,t),t}catch{return`listener-${crypto.randomUUID()}`}})(),Yr=null,q=!1,Xr=``,Zr=!1,Qr=!1,$r=``,ei=0,ti=!1,ni=!1;try{a.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let ri=new Yt(()=>{ni=!0,ti&&(a.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),ii=()=>{let e=Number(a.transcriptBackgroundLevel.value);ri.setLevel(e/100),a.transcriptBackgroundValue.value=`${e}%`,_(a.transcriptBackgroundLevel,`aria-valuetext`,()=>f.number(e/100,{style:`percent`})),a.transcriptBackgroundLevel.disabled=!a.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(a.transcriptBackgroundLevel.value=e)}catch{}ii(),a.transcriptBackgroundLevel.addEventListener(`input`,()=>{ii();try{localStorage.setItem(`nixamp.backgroundLevel`,a.transcriptBackgroundLevel.value)}catch{}});let J=new Zt({account:()=>W===``?K:``,changed:()=>Li()});z(`translation-buy-tools`).append(J.button()),J.refresh();let ai=new Xt({reconnecting:()=>Y.reset(),line:(e,t)=>{pi=0,mi.push(e),Fi(),Y.push(e,t,0)},status:e=>{a.transcriptAudioNote.textContent=e},failed:e=>{Xr=e,qr=e,q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci(),a.transcriptAudioNote.textContent=`${e} Original audio restored.`,J.refresh()}}),Y=new Kt({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(ai.audio(String(e))):fetch(e,t)),playing:()=>N.playing,volume:()=>N.volume,active:e=>{ti=e,N.translatedAudio(e),ri.active(e&&N.playing&&a.transcriptBackground.checked)},status:e=>{a.transcriptAudioNote.textContent=e+(ni&&ti?` · background unavailable`:``)},failed:()=>{qr=a.transcriptAudioNote.textContent||`Translated audio stopped.`,q=!1,a.transcriptAudio.checked=!1,ci()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!K||W!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!Yr||Yr.channel!==t.channel||Yr.expires<Date.now()+2e4||Yr.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.`);Yr={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return Yr.remaining-=t.text.length,{authorization:`Bearer ${Yr.token}`}}}),oi=new $t({fetcher:(e,t)=>{let n=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&n.set(`x-nixamp-translation-session`,Jr),fetch(e,{...t,headers:n})},language:()=>G,speakers:()=>a.transcriptAudio.checked,voices:()=>Gr?.voices??[],channel:()=>Jr,status:e=>{!Zr&&!q&&(Xr=e),a.transcriptNote.textContent=e},failed:()=>{q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci()},lines:e=>{pi=0,mi.push(...e),Fi(),ui(),a.transcriptAudio.checked&&Y.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:G,channel:Jr,speaker:e.speaker,voice:oi.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),si=new qt(e=>{Zr&&N.playing&&oi.push(e)});function ci(){ei++,Zr=!1,Qr=!1,$r=``,si.stop(),oi.reset(),ai.stop(),ri.stop(),Y.reset(),C(a.transcriptSpeakers)}async function li(){if((Zr||Qr)&&$r===N.mediaKey)return;ci();let e=ei;Qr=!0,$r=N.mediaKey;try{if(!K||W!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=N.audioInput();if(ni=!1,a.transcriptAudio.checked&&a.transcriptBackground.checked&&ri.start(t.context,t.node).then(t=>{t&&e===ei&&ri.active(ti&&N.playing&&a.transcriptBackground.checked)}),a.transcriptAudio.checked&&c===`remote`&&E)await ai.start(zi(),G),J.refresh();else{if(a.transcriptAudio.checked&&await J.startSession(Jr),e!==ei)return;await si.start(t.context,t.node,a.transcriptAudio.checked?2:5)}if(e!==ei)return;Zr=!0,q=!0,pi=0,gi??=setInterval(Fi,250),a.transcriptNote.textContent=a.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==ei)return;q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci(),Xr=t instanceof Error?t.message:`This audio could not be captured.`,a.transcriptNote.textContent=Xr}finally{e===ei&&(Qr=!1)}}function ui(){let e=[...oi.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(a.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id;let n=document.createElement(`span`),r=t.id.split(`-`)[1];g(n,()=>`${p(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,_(i,`aria-label`,()=>`${p(`Speaker voices`)}: ${r}`);for(let e of Gr?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,Y.reset()}),e.append(i),a.transcriptSpeakers.append(e)}a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked;for(let e of a.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[a.audio,a.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(N.showingVideo?a.video:a.audio)&&ci()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(N.showingVideo?a.video:a.audio)&&q&&Hr&&N.playing&&li()});e.addEventListener(`volumechange`,()=>{Y.setVolume()})}let di=``,fi=null,pi=zt(6,!1),mi=[],hi=[],gi=null;function _i(){if(c!==`remote`)return null;let{base:e}=Le(yo());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=E?E.id:D?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function vi(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${W}/api/v1/trollbox?${n.toString()}`}function yi(){let e=_i(),t=e?`${e.server}|${e.channel}`:``;t!==Pr&&(Pr=t,Fr=``,Rr.clear(),a.trollboxList.replaceChildren(),Ir&&clearTimeout(Ir),Ir=null,a.trollboxPanel.hidden=e===null,a.trollboxForm.hidden=!0,Ti(!1),e&&(g(a.trollboxNote,()=>`The room for ${en()||e.channel}. Loading…`),xi()))}function bi(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);g(n,()=>Number.isNaN(r.getTime())?``:r.toLocaleTimeString(f.language,{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,a.dir=`auto`,a.translate=!1,t.append(n,i,a),t}async function xi(){let e=_i(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===Pr&&!Lr){Lr=!0;try{let n=await fetch(vi(e,Fr)),r=await n.json().catch(()=>({}));if(t!==Pr)return;if(!n.ok){a.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!Rr.has(e.id));for(let e of i)Rr.add(e.id),a.trollboxList.append(bi(e)),Fr=e.createdAt;for(;a.trollboxList.children.length>200;)a.trollboxList.firstElementChild?.remove();let o=r.you??``,s=zr!==o;zr=o,s&&(Yr=null,Li()),a.trollboxForm.hidden=o===``,a.trollboxEditLabel.hidden=o===``||!Si,o===``&&Ti(!1),g(a.trollboxNote,()=>o===``?W===``?`The room for ${en()||e.channel}. Sign in to say something.`:`The room for ${en()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${en()||e.channel}.`)}catch{t===Pr&&(a.trollboxNote.textContent=`The trollbox is not answering.`)}finally{Lr=!1,t===Pr&&(Ir=setTimeout(()=>{document.visibilityState===`visible`?xi():Ir=setTimeout(()=>void xi(),Nr)},Nr))}}}a.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=_i(),n=a.trollboxInput.value.trim();t&&n!==``&&(a.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${W}/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){a.trollboxNote.textContent=r.error??`that did not send`;return}a.trollboxInput.value=``,Rr.has(r.message.id)||(Rr.add(r.message.id),a.trollboxList.append(bi(r.message)),Fr=r.message.createdAt)}catch{a.trollboxNote.textContent=`The trollbox is not answering.`}finally{a.trollboxInput.disabled=!1}})())});let Si=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Ci=Si?Mt(e=>MediaRecorder.isTypeSupported(e)):``;a.trollboxMic.hidden=!Si;function wi(e){a.trollboxNote.textContent=e,Mr(e)}function Ti(e){let t=Br;if(!t)return;Br=null,clearTimeout(t.stop),clearInterval(t.tick),a.trollboxMic.setAttribute(`aria-pressed`,`false`),a.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(()=>Di(new Blob(t.chunks,{type:t.recorder.mimeType||Ci||`audio/webm`}),t.startedAt))}async function Ei(){if(Br||Vr||zr===``||!_i())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){wi(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,Ci?{mimeType:Ci}:{})}catch{for(let t of e.getTracks())t.stop();wi(`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();Br={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>Ti(!0),jt),tick:setInterval(()=>{a.trollboxMic.textContent=Nt(r,Date.now())},500)},t.start(250),a.trollboxMic.setAttribute(`aria-pressed`,`true`),a.trollboxMic.textContent=Nt(r,r),wi(`Listening. Tap the mic again when you have said it (${Math.round(jt/1e3)} s at most).`)}async function Di(e,t){let n=_i();if(n&&zr!==``){if(Date.now()-t<400||e.size===0){wi(`That was too short to hear. Tap, say it, then tap again.`);return}Vr=!0,a.trollboxMic.disabled=!0,a.trollboxMic.textContent=`…`,wi(`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),o=i.createBufferSource();o.buffer=r,o.connect(i.destination),o.start();let s=kt((await i.startRendering()).getChannelData(0),At),c=a.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(`${W}/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){wi(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){wi(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=a.trollboxInput.value.trimEnd();a.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),wi(`Heard: “${p}”. Send it, or fix it first.`);return}_i()&&!Rr.has(f.message.id)&&(Rr.add(f.message.id),a.trollboxList.append(bi(f.message)),Fr=f.message.createdAt),wi(`Said: “${f.message.body}”`)}catch{wi(`That recording could not be read here.`)}finally{Vr=!1,a.trollboxMic.disabled=!1,a.trollboxMic.textContent=`🎤`}}}a.trollboxMic.addEventListener(`click`,()=>{Br?Ti(!0):Ei()});try{a.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}a.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,a.trollboxEdit.checked?`on`:`off`)}catch{}wi(a.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Oi(){try{let e=await fetch(`${W}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`Could not read your profile.`;return}a.personaHandle.value=t.chosen?t.handle??``:``,_(a.personaHandle,`placeholder`,()=>t.handle||p(`handle`)),a.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,a.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;a.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${ki(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${ki(t.voice??``)}${n}.`}catch{a.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function ki(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`}a.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.personaHandle.value.trim(),n={voice:a.personaVoice.value,profile:a.personaProfile.value.trim()};t!==``&&(n.handle=t),a.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${W}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`that did not save`;return}await Oi()}catch{a.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&Br&&Ti(!0)});function Ai(){return c===`remote`&&E?{id:E.id,name:E.name,hls:E.video&&vt()}:N.loaded||k?{id:Jr,name:en()||`This audio`,hls:!1}:null}function ji(){ci(),Yr=null,Ur.clear(),Wr.clear(),fi?.close(),fi=null,gi&&clearInterval(gi),gi=null,mi=[],hi=[],a.transcriptList.replaceChildren(),a.subtitle.hidden=!0,a.subtitle.textContent=``}function Mi(){let e=Ai(),t=`${e?.id??``}|${N.mediaKey}|${Hr}|${G}|${a.transcriptAudio.checked}|${q}|${K}`;if(t!==di){if(di=t,ji(),a.transcriptPanel.hidden=!1,a.transcriptOn.checked=Hr&&(!!E||q||a.transcriptAudio.checked),a.transcriptLanguage.options.length===0)for(let e of It){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),g(t,()=>e.code?e.label:p(`Original (auto-detect)`)),a.transcriptLanguage.append(t)}if(a.transcriptLanguage.value=G,Li(),Ri(),!e){a.transcriptNote.textContent=`Play something to see its captions.`;return}if(!Hr){a.transcriptNote.textContent=`Captions are off.`;return}if(Xr){a.transcriptNote.textContent=Xr;return}a.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,a.transcriptAudio.checked||q?N.playing?li():a.transcriptNote.textContent=`Press Play to start listening.`:c===`remote`&&E?Ni(e,t):a.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Ni(e,t){let n=6,r=G?`?language=${encodeURIComponent(G)}`:``;try{let i=await fetch(P.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),o=await i.json().catch(()=>({}));if(t!==di)return;if(!i.ok){a.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){K&&W===``?(q=!0,Mi()):a.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=o.backlog??n}catch{t===di&&(a.transcriptNote.textContent=`The server did not answer about captions.`);return}pi=zt(n,e.hls);let i=new EventSource(P.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));fi=i;let o=(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}`;Ur.has(e)||(Ur.add(e),Ur.size>600&&Ur.delete(Ur.values().next().value),mi.push(n),t&&a.transcriptAudio.checked&&Wr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==di)return;let i=JSON.parse(r.data);pi=zt(i.backlog??n,e.hls),o(i.lines??[]);let s=It.find(e=>e.code===i.language)?.label??i.language,c=It.find(e=>e.code===G)?.label??G;if(a.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:G?`${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=`${W||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,a.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==di)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=It.find(e=>e.code===i)?.label??i,c=It.find(e=>e.code===G)?.label??G;a.transcriptNote.textContent=G?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===di&&i.readyState===EventSource.CLOSED&&(a.transcriptNote.textContent=`Captions stopped; the server went away.`)}),gi=setInterval(Fi,250)}function Pi(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),g(n,()=>Ut(e.at));let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text,r.dir=`auto`,r.translate=!1,(e.language||e.sourceLanguage)&&(r.lang=e.language||e.sourceLanguage);let i=Rt(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 Fi(){let e=Date.now(),{ready:t,still:n}=Bt(mi,e,pi);mi=n;for(let e of t)if(hi.push(e),a.transcriptList.append(Pi(e)),Wr.delete(e)&&a.transcriptAudio.checked&&G){let t=new URLSearchParams({at:String(e.at),language:G,voice:`auto`});Y.push(e,P.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),pi)}for(;hi.length>200;)hi.shift();for(;a.transcriptList.children.length>200;)a.transcriptList.firstElementChild?.remove();let r=Vt(hi,e,pi),i=a.transcriptList.children,o=r?hi.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===o);let s=N.playing&&r!==null&&!a.video.hidden&&a.video.offsetHeight>0;a.subtitle.hidden=!s,s&&r&&(a.subtitle.textContent!==r.text&&(a.subtitle.textContent=r.text),a.subtitle.style.top=`${a.video.offsetTop+a.video.offsetHeight-a.subtitle.offsetHeight-10}px`)}a.transcriptOn.addEventListener(`change`,()=>{Hr=a.transcriptOn.checked,q=Hr&&(!E||a.transcriptAudio.checked),Hr||(a.transcriptAudio.checked=!1,Y.disable());try{localStorage.setItem(Pt,Hr?`on`:`off`)}catch{}Mi()}),a.transcriptLanguage.addEventListener(`change`,()=>{Xr=``,qr=``,G=Lt(()=>a.transcriptLanguage.value),!G&&a.transcriptAudio.checked&&(a.transcriptAudio.checked=!1,q=!1,Y.disable());try{G?localStorage.setItem(Ft,G):localStorage.removeItem(Ft)}catch{}Mi()});function Ii(){if(G)return G;let e=navigator.language.split(`-`)[0]||`en`;return It.some(t=>t.code===e)&&Gr?.languages.includes(e)?e:`en`}function Li(){let e=K!==``&&W===``,t=e&&J.loaded()&&!!Ai()&&!!Gr?.languages.includes(Ii());a.transcriptAudio.disabled=!t,a.transcriptVoiceSettings.contains(document.activeElement)||(a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked),t?a.transcriptAudio.checked||g(a.transcriptAudioNote,()=>qr||p(`Original audio.`)):(a.transcriptAudio.checked=!1,Y.disable(),a.transcriptAudioNote.textContent=e?Ai()?J.loaded()?qr||(Gr?`Audio translation is unavailable for this language.`:`Loading voices…`):J.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function Ri(){if(!K||W!==``)return;let e=`/api/v1/speech/voices`;if(Kr!==e){Kr=e,Gr=null,qr=``,Li();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(Kr!==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.`);Gr=n}catch(t){if(Kr!==e)return;qr=t instanceof Error?t.message:`Translated audio is unavailable.`}Li()}}a.transcriptBackground.addEventListener(`change`,()=>{ii();try{localStorage.setItem(`nixamp.backgroundSound`,a.transcriptBackground.checked?`on`:`off`)}catch{}if(ri.stop(),ni=!1,a.transcriptBackground.checked&&a.transcriptAudio.checked&&N.playing){let e=ei,t=N.audioInput();ri.start(t.context,t.node).then(t=>{t&&e===ei&&ri.active(ti&&N.playing&&a.transcriptBackground.checked)})}}),a.transcriptAudio.addEventListener(`change`,()=>{if(Xr=``,qr=``,Wr.clear(),a.transcriptAudio.checked&&!J.ready()){a.transcriptAudio.checked=!1,J.open(a.transcriptAudio);return}if(a.transcriptAudio.checked){G=Ii();try{localStorage.setItem(Ft,G)}catch{}Hr=!0,q=!0,Y.enable()}else q=!1,Y.disable();Mi()});function zi(){if(k)return k.url;if(c!==`remote`)return``;let{base:e,key:t}=Le(yo());if(e===``)return``;if(E)return Fe(e,`/api/channels/${encodeURIComponent(E.id)}`,t);if(D?.kind===`live`)return Fe(e,`/api/live`,t);if(N.source===``)return``;try{let n=new URL(N.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function Bi(){let e=zi();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function Vi(){return c===`remote`?E?vo(`channel:${E.id}`):D?.kind===`live`||L()?vo(`live`):``:``}a.shareNow.addEventListener(`click`,()=>{let e=Bi();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${R()} on nixamp`,url:e}).catch(()=>void 0);return}_o(e,a.shareNow,`Copied`)}),a.copyNixamp.addEventListener(`click`,()=>{let e=Vi();e!==``&&_o(e,a.copyNixamp,`✓`)}),a.favHere.addEventListener(`click`,()=>{let e=yo()||P.shareLink;if(!e)return;let t=[...Er].find(t=>U(t)===U(e))??e;kr(Dr(e)?t:e,l||P.address,!Dr(e)).then(jr)});let Hi=n?i:200,Ui=[],X=null,Z=null,Wi=``,Gi=[],Ki=0,qi=null,Ji=0,Yi=null,Xi=null,Zi=new Map;function Qi(e,t){Ji++,Yi?.abort(),qi&&clearTimeout(qi),qi=null,de(a.catalogsList),de(a.catalogsEntries),X=e,Z=t,Wi=``,a.catalogsFilter.value=``,Gi=[],Ki=0,a.catalogsEntries.setAttribute(`aria-busy`,`false`),na(),e&&t!==null&&sa(0)}function $i(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`}function ea(){let e=P.url(`/api/catalogs`);if(Xi?.url===e)return Xi.promise;let t=ta(e).finally(()=>{Xi?.promise===t&&(Xi=null)});return Xi={url:e,promise:t},t}async function ta(e){if(c!==`remote`){a.catalogsPanel.hidden=!0;return}let t;try{t=await fetch(e)}catch{e===P.url(`/api/catalogs`)&&(a.catalogsPanel.hidden=!0);return}if(c===`remote`&&e===P.url(`/api/catalogs`)){if(!t.ok){a.catalogsPanel.hidden=!0;return}Ui=(await t.json().catch(()=>({}))).catalogs??[],X&&=Ui.find(e=>e.id===X?.id)??null,X||(Z=null),a.catalogsPanel.hidden=!1,na()}}function na(){let e=!a.adminPanel.hidden;a.catalogsForm.hidden=!e;let t=Ui.reduce((e,t)=>e+t.live,0),n=Ui.reduce((e,t)=>e+t.vod,0);a.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`,ra();let r=X!==null&&Z!==null;if(a.catalogsList.hidden=r,a.catalogsFilter.hidden=!r,a.catalogsEntries.hidden=!r,r){ca();return}if(X){aa(X);return}C(a.catalogsList,...Ui.map(t=>ia(t,e)))}function ra(){let e=X!==null;if(a.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`,()=>Qi(null,null),!1),n(),t(X?.name??``,()=>Qi(X,null),Z===null)];Z!==null&&r.push(n(),t(Z===``?`All groups`:Z,()=>void 0,!0)),a.catalogsCrumbs.replaceChildren(...r)}function ia(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`,g(a,()=>[`${e.entries.toLocaleString(f.language)} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString(f.language)} live`,`${e.vod.toLocaleString(f.language)} on demand`,`refreshed ${$i(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.setAttribute(`aria-label`,`Browse ${e.name}`),o.addEventListener(`click`,()=>{Qi(e,null)}),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`,()=>{ua(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,g(r,()=>p(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&go(n,r,()=>da(e),()=>void ea())}),n.append(t,r)}return n}async function aa(e){let t=P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),n=`${t}:${e.refreshedAt}:${e.entries}`,r;a.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=Zi.get(n);e||(Zi.size>=20&&Zi.delete(Zi.keys().next().value),e=fetch(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),Zi.set(n,e)),r=await e}catch{if(Zi.delete(n),X?.id!==e.id||Z!==null||t!==P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`),w=`Could not read the groups in ${e.name}.`,B();return}if(X?.id!==e.id||Z!==null||t!==P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`);let i=[oa(`All groups`,``,e.entries,e.live,e.vod),...r.map(e=>oa(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];C(a.catalogsList,...i)}function oa(e,t,n,r,i){let a=document.createElement(`li`),o=document.createElement(`span`);o.className=`server-label`;let s=document.createElement(`span`);s.className=`name`,s.textContent=e;let c=document.createElement(`span`);c.className=`detail`,g(c,()=>`${n.toLocaleString(f.language)} · ${r.toLocaleString(f.language)} live · ${i.toLocaleString(f.language)} on demand`),o.append(s,c);let l=document.createElement(`button`);return l.type=`button`,l.className=`button`,l.textContent=`Open`,l.setAttribute(`aria-label`,`Open ${e}`),l.addEventListener(`click`,()=>{Qi(X,t)}),a.append(o,l),a}async function sa(e){let t=X,n=Z;if(!t||n===null)return;let r=++Ji;Yi?.abort();let i=new AbortController;Yi=i;let o=P.url(`/api/catalogs`);a.catalogsEntries.setAttribute(`aria-busy`,`true`);let s=new URLSearchParams({group:n,q:Wi,offset:String(e),limit:String(Hi)}),c;try{let e=await fetch(P.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${s}`),{signal:i.signal});if(!e.ok)throw Error(String(e.status));c=await e.json()}catch{if(i.signal.aborted||r!==Ji)return;a.catalogsEntries.setAttribute(`aria-busy`,`false`),w=`Could not read ${t.name}.`,ca(),B();return}r===Ji&&X?.id===t.id&&Z===n&&o===P.url(`/api/catalogs`)&&(a.catalogsEntries.setAttribute(`aria-busy`,`false`),Ki=c.total??0,Gi=e===0?c.entries??[]:[...Gi,...c.entries??[]],ca())}function ca(){let e=X;if(!e)return;let t=Gi.map(t=>{let n=document.createElement(`li`);n.className=`row`;let r=document.createElement(`span`);r.className=`name`,r.textContent=t.title;let i=document.createElement(`span`);i.className=t.live?`catalog-tag catalog-live`:`catalog-tag`,i.textContent=t.live?`LIVE`:t.duration>0?se(t.duration):`VOD`;let a=document.createElement(`button`);if(a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Play ${t.title}`),a.append(r,i),n.append(a),a.addEventListener(`click`,()=>{la(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,o(r,`copy`),r.title=`Copy this entry's URL`,r.setAttribute(`aria-label`,`Copy the URL of ${t.title}`),r.addEventListener(`click`,n=>{n.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/stream`;_o(P.url(i),r,`✓`)}),n.append(r)}return gt()&&n.append(Wt(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(Gi.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=Wi?`Nothing called "${Wi}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(Gi.length<Ki){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,g(n,()=>`Show more (${Gi.length.toLocaleString(f.language)} of ${Ki.toLocaleString(f.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),de(a.catalogsEntries,!1),n.disabled=!0,sa(Gi.length)}),e.append(n),t.push(e)}C(a.catalogsEntries,...t)}async function la(e,t,n){n?.classList.add(`loading`),w=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await Ce(async()=>{let n,i={};try{n=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{w=`could not reach the server`;return}if(!n.ok){w=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await lo({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){E=null,T=-1,D={kind:`vod`,...r},Be(a,`title`),await N.load({title:a,artist:``,album:``,duration:0,url:P.url(i.url),video:!0,objectUrl:!1},!0),Hn(!0),w=`Playing ${a}.`;return}w=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),B()}}async function ua(e){H(`Reading ${e.name} again…`);try{let t=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));H(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString(f.language)} entries.`:n.error??`that did not work`)}catch{H(`could not reach the server`)}ea()}async function da(e){try{let t=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(H(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return H(`could not reach the server`),!1}return X?.id===e.id&&(X=null,Z=null),!0}a.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.catalogSource.value.trim(),n=a.catalogName.value.trim();t&&(async()=>{H(`Reading ${n||t}…`);try{let e=await fetch(P.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){H(r.error??`that did not work`);return}H(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString(f.language)} entries.`),a.catalogSource.value=``,a.catalogName.value=``}catch{H(`could not reach the server`)}ea()})()}),a.catalogsFilter.addEventListener(`input`,()=>{Ji++,Yi?.abort(),qi&&clearTimeout(qi),qi=setTimeout(()=>{qi=null,Wi=a.catalogsFilter.value.trim(),sa(0)},250)});let fa=async()=>{C(a.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){a.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ne=new Map(t.map(e=>[U(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),a.serversPanel.hidden=!1,a.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 o=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=ie({name:e.name,view:o,admin:o});Je(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=ka()===U(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`,()=>{Aa(l?``:U(e.url)),fa()});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 fa()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),a.serversList.append(t)}}catch{a.serversPanel.hidden=!0}},pa=async()=>{C(a.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){a.followingNote.hidden=!0;return}let t=(await e.json()).following??[];a.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 o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,g(o,()=>p(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),a.followingList.children.length===0&&(a.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(n,o),a.followingList.append(t)}}catch{a.followingNote.hidden=!0}},ma=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,g(n,()=>p(`Follow`)),n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{g(n,()=>e?`Following`:p(`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),pa())}catch{}finally{n.disabled=!1}})()}),n},ha=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},ga=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,_a=async()=>{if(!ga())return a.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return a.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return a.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 a.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:ha(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 a.notifyNote.textContent=`This device will be told.`,!0}catch{return a.notifyNote.textContent=`Could not set this device up.`,!1}},va=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{}},ya=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();a.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(a.notifyPhone.value=n.phone)}catch{a.notifyPhoneNote.textContent=`could not reach nixamp.com`}},ba=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();a.notifyEmail.checked=t.wantsEmail!==!1,a.notifySms.checked=t.wantsSms===!0,a.notifyPhone.value=t.phone??``;let n=ga()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;a.notifyWeb.checked=t.wantsWeb!==!1&&n,a.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};a.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(a.notifyWeb.checked){let e=await _a();a.notifyWeb.checked=e,await ya({wantsWeb:e});return}await va(),await ya({wantsWeb:!1}),a.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),a.notifyEmail.addEventListener(`change`,()=>{ya({wantsEmail:a.notifyEmail.checked})}),a.notifySms.addEventListener(`change`,()=>{(async()=>{if(a.notifySms.checked&&!a.notifyPhone.value.trim()){a.notifyPhoneNote.textContent=`Add a phone number first.`,a.notifySms.checked=!1;return}await ya({wantsSms:a.notifySms.checked})})()}),a.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),ya({phone:a.notifyPhone.value.trim()})});let xa=!1,Sa=!1,Ca=`nixamp.welcome`,wa=()=>{let e=!1;try{e=localStorage.getItem(Ca)===`hidden`}catch{}a.welcome.hidden=!Sa||K!==``||e},Ta=e=>{let t=e!==null;J.refresh(),Kr=``,Yr=null,t||(q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci()),Mi(),a.notifyPanel.hidden=!t,t?(ba(),pa(),fa()):(a.serversPanel.hidden=!0,a.followingNote.hidden=!0,C(a.followingList),a.recentNote.hidden=!0,a.recentList.replaceChildren()),a.accountForm.hidden=t,a.accountProviders.hidden=t||a.accountProviders.childElementCount===0,a.accountSignOut.hidden=!t,a.personaForm.hidden=!t,a.personaNote.hidden=!t,t&&Oi(),a.accountNote.textContent=t?`Signed in as ${e}.`:xa?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,g(a.accountSubmit,()=>p(xa?`Create account`:`Sign in`)),g(a.accountToggle,()=>xa?`I have one`:p(`Create one`)),a.accountPassword.autocomplete=xa?`new-password`:`current-password`,wa()},Ea=async()=>{let e=[];Sa=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Sa=!0,e=(await t.json()).providers??[])}catch{}a.accountProviders.replaceChildren(),a.accountProviders.hidden=e.length===0,a.accountPanel.hidden=!Sa,a.accountElsewhere.hidden=Sa,wa();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}`,a.accountProviders.append(e)}},Da=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();K=e.ok?t.account?.id??``:``,Ta(e.ok?t.account?.email??`you`:null)}catch{K=``,Ta(null)}if(P.session=``,K!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));P.session=e.ok&&typeof t.token==`string`?t.token:``}catch{P.session=``}c===`remote`&&fr()}Or(),wr(),Tr(),ja();let e=await Oa();if(rt!==``){let t=rt;rt=``,e?y=`golive:${t}`:Wn(t)}};async function Oa(){if(K===``||c===`remote`||Ze!==``)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=ka(),n=[...e].sort((e,n)=>Number(U(n.url)===t)-Number(U(e.url)===t));for(let e of n)if(await Je(e.url,void 0,e.key)!==null)return c!==`remote`&&(ee=!1,y=``,a.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,w=`Connecting to ${e.name}, your server…`,B(),a.remoteForm.requestSubmit(),!0);return!1}function ka(){try{return localStorage.getItem(un)??``}catch{return``}}function Aa(e){try{e===``?localStorage.removeItem(un):localStorage.setItem(un,e)}catch{}}function ja(){if(Ze===``)return;let e=Ze;Ze=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit()}a.accountToggle.addEventListener(`click`,()=>{xa=!xa,Ta(null)}),a.welcomeCreate.addEventListener(`click`,()=>{xa=!0,Ta(null),a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),a.accountEmail.focus({preventScroll:!0})}),a.welcomeBrowse.addEventListener(`click`,()=>{a.directory.hidden?a.browse.click():a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Ca,`hidden`)}catch{}a.welcome.hidden=!0}),a.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.accountEmail.value.trim(),n=a.accountPassword.value;(async()=>{a.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${xa?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){a.accountNote.textContent=r.error??`that did not work`;return}K=r.account?.id??``,a.accountPassword.value=``,Ta(r.account?.email??t),fr(),ja()}catch{a.accountNote.textContent=`could not reach nixamp.com`}finally{a.accountSubmit.disabled=!1}})()}),a.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}K=``,Ta(null),wr(),P.close(),T=-1,c=`local`,ue=`idle`,S=``,a.remoteUrl.value=``,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,a.listenOnly.hidden=!0,io(!1);try{localStorage.removeItem(ln)}catch{}w=`Signed out, and disconnected from the server.`,fr(),B()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Ze=t,y=e.get(`play`)??``,te=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t,w=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(a.linkUrl.value=n,t!==``&&y===``?y=`link:${n}`:t===``&&(rt=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=Ie(r);t?(Ze=t.view,y=t.what,te=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t.view,w=`Opening the stream you were sent…`):(a.linkUrl.value=r,rt=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Ma=[`zone-top`,`zone-main`],Na=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Pa=e=>e.parentElement&&Ma.includes(e.parentElement.id)?e.parentElement:null,Fa=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Ia=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Na(e)&&Pa(e)!==null),La=e=>e.dataset.title??e.id,Ra=new Map,za=Ia().map((e,t)=>(Ra.set(e.id,{zone:Pa(e)?.id??``,col:Fa(e),index:t}),e.id)),Q=xt();try{Q=Tt(localStorage.getItem(bt))}catch{}let Ba=()=>Q.order.length>0||Object.keys(Q.placement).length>0;function Va(){Q.order=Ia().map(e=>e.id);try{localStorage.setItem(bt,Et(Q))}catch{}}function Ha(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 Ua(){if(e)return;for(let e of Ia()){let t=Q.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Ma.includes(i.id)&&Ha(e,i,r===`a`||r===`b`?r:``)}let t=Dt(Ia().map(e=>e.id),Q.order);for(let e of Ma){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(Na),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((e,n)=>t.indexOf(e.id)-t.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of Ia())e.toggleAttribute(`data-collapsed`,Q.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Q.closed.includes(e.id))}function Wa(e,t){e.toggleAttribute(`data-collapsed`,t),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),Q.collapsed=Ot(Q.collapsed,e.id,t),Va(),Za()}function Ga(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===a.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===a.partiesPanel&&!t&&wr(),t&&n&&a.panelsToggle.focus({preventScroll:!0}),Q.closed=Ot(Q.closed,e.id,t),Va(),Za()}function Ka(e,t,n){let r=Pa(t);r&&e!==t&&(Ha(e,r,Fa(t)),n?t.after(e):t.before(e),Q.placement[e.id]=`${r.id}:${Fa(t)}`,Va(),Za())}let qa=null,Ja=()=>{for(let e of Ia())e.classList.remove(`drop-before`,`drop-after`)},Ya=(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 Xa(){for(let e of Ia()){let t=La(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=Ya(`≡`,`Move ${La(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=Ia().filter(t=>Pa(t)===Pa(e)&&Fa(t)===Fa(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(Ka(e,r,t.key===`ArrowDown`),i.focus({preventScroll:!0}))}),i.classList.add(`grip`),i.draggable=!0,i.addEventListener(`dragstart`,t=>{qa=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),i.addEventListener(`dragend`,()=>{qa=null,e.classList.remove(`dragging`),Ja()});let a=Ya(`▁`,`Shade ${La(e)} to its title`,()=>Wa(e,!e.hasAttribute(`data-collapsed`)));a.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let o=Ya(`✕`,`Hide ${La(e)}; the Panels list turns it back on`,()=>Ga(e,!0));e.id===`transcript-panel`&&r.append(J.button()),r.append(i,a,o),e.prepend(r),e.addEventListener(`dragover`,t=>{if(!qa||qa===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;Ja(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!qa||qa===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);Ja(),Ka(qa,e,n)})}}function Za(){if(a.panelsPanel.hidden||a.panelsList.contains(document.activeElement))return;let e=Ia().filter(e=>e!==a.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,`aria-label`,()=>`${La(e)} on`),i.addEventListener(`change`,()=>Ga(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,g(a,()=>La(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&&e.dataset.available!==`true`?`nothing to show right now`:``,t.append(r,o),t});a.panelsList.replaceChildren(...e)}function Qa(){Q=xt();for(let e of za){let t=document.getElementById(e),n=Ra.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(Ha(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Q.order=[...za],Ua(),Q=xt();try{localStorage.removeItem(bt)}catch{}Za()}function $a(e){if(!e||Ba())return;let t=Pa(a.adminPanel);if(!t)return;let n=[...t.children].filter(Na).find(e=>Fa(e)===Fa(a.adminPanel));n&&n!==a.adminPanel&&n.before(a.adminPanel),a.adminPanel.removeAttribute(`data-collapsed`),a.adminPanel.removeAttribute(`data-closed`)}a.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=a.panelsPanel.hidden||a.panelsPanel.hasAttribute(`data-closed`)||a.panelsPanel.hasAttribute(`data-collapsed`);a.panelsPanel.hidden=!t,a.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(a.panelsPanel.hasAttribute(`data-closed`)&&Ga(a.panelsPanel,!1),a.panelsPanel.hasAttribute(`data-collapsed`)&&Wa(a.panelsPanel,!1),Za(),a.panelsPanel.showPopover?.(),a.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):a.panelsPanel.hidePopover?.()}),a.panelsPanel.addEventListener(`toggle`,()=>{let e=a.panelsPanel.matches(`:popover-open`);a.panelsToggle.setAttribute(`aria-expanded`,String(e&&!a.panelsPanel.hasAttribute(`data-collapsed`))),e||(a.panelsPanel.hidden=!0)}),a.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof a.panelsPanel.hidePopover!=`function`&&(a.panelsPanel.hidden=!0,a.panelsToggle.setAttribute(`aria-expanded`,`false`),a.panelsToggle.focus({preventScroll:!0}))}),a.panelsReset.addEventListener(`click`,Qa),a.panelsSave.addEventListener(`click`,()=>{Va();let e=a.panelsSave.textContent??`Save setup`;a.panelsSave.textContent=`Saved`,window.setTimeout(()=>{a.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{Xa(),Za()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),Xa(),Ua(),Ea(),Da(),fr(),Zn(),a.browse.addEventListener(`click`,()=>{if(!a.directory.hidden){a.directory.hidden=!0;return}rr(),a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.disconnect.addEventListener(`click`,()=>{P.close(),a.listenOnly.hidden=!0,T=-1,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,_(a.catalogsPanel,`data-title`,()=>p(`Catalogs on this server`)),l=``,ae=``,jr(),io(!1),c=`local`,ue=`idle`,S=``,B()});async function eo(){if(c!==`remote`||P.shareLink===``){a.sharePanel.hidden=!0;return}a.sharePanel.hidden=!1;let e=yo(),t=globalThis.location.origin;a.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,a.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,a.sharePhone.hidden=!0,a.shareSend.hidden=!0,a.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(P.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ae=r.url,a.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Ve=r.live,He=r.live?r.code:``,We=n,a.liveControls.hidden=a.adminPanel.hidden||!r.possible,a.goLive.hidden=r.live,a.stopLive.hidden=!r.live,a.sharePhone.hidden=!1,!r.live){a.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){a.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,a.shareSend.hidden=!1;return}a.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),To(n),document.createTextNode(` and key `),To(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),a.shareSend.hidden=!1}}let to=null,no=null,ro=0,io=e=>{to&&clearInterval(to),to=null,ro+=1,no?.abort(),no=null,O=null,Cr(),e&&($(),to=setInterval(()=>{document.visibilityState===`visible`&&$()},2e3))};async function $(){if(c!==`remote`||no)return;let e=new AbortController;no=e;let t=ro,n=P.url(`/api/streams`),r=setTimeout(()=>e.abort(),8e3);try{let r=await fetch(n,{signal:e.signal,cache:`no-store`});if(!r.ok)return;let i=await r.json();if(e.signal.aborted||t!==ro||c!==`remote`||n!==P.url(`/api/streams`))return;m=i.server.carries!==!1,i.server.name&&i.server.name!==l&&(l=i.server.name,a.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${l}`),jr()),O=i,bo(i),B(),ao(i)}catch{}finally{clearTimeout(r),no===e&&(no=null)}}function ao(e){Cr(),E&&Fn()}function oo(e){let t=Jt(),n=e.restreams??[],r=[],i=e.server.playing,o=!a.adminPanel.hidden;i&&r.push(xo({key:`live`,title:me(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${me(e.server.nowPlaying)}`:`nothing loaded`,i&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:`Join party`,onPlay:()=>{i&&co(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:vo(`live`)}:{},direct:i?P.url(`/api/live`):``}));for(let e of n)r.push(xo({key:`restream:${e.at}`,title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{hn(e.at)},link:``,direct:P.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=P.url(`/api/channels/${encodeURIComponent(t.id)}`),i=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&i.push(`☎ ${t.code}`),t.redials&&i.push(`redialled ${t.redials}×`),o&&t.error&&i.push(t.error),r.push(xo({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{lo({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:vo(`channel:${t.id}`),direct:n,onRestart:(o||mt&&K!==``&&t.startedBy===K)&&t.via===`pull`?()=>{po(t.id,t.name)}:void 0,onStop:o||mt&&K!==``&&t.startedBy===K?()=>ho(t.id,t.name):void 0,onRename:o||mt&&K!==``&&t.startedBy===K?()=>{mo(t.id,t.name)}:void 0}))}return r}async function so(){if(c===`remote`)try{if((await fetch(P.media(I(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;w=K===``?`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.`,K===``&&a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),B()}catch{}}async function co(e){T=-1,E=null,D={kind:`live`},Be(e,`auto`),await Ce(()=>N.load({title:e||`Live`,artist:``,album:``,duration:0,url:P.url(`/api/live`),video:!0,objectUrl:!1},!0)),Hn(!0),w=`Watching what this server is playing. Everyone here sees the same thing.`,B()}async function lo(e,t=!0,n){T=-1,E=e,t&&(ye=0),t&&(D=n??{kind:`channel`}),t&&Be(e.name,D?.link||sn(e.name)?`auto`:`channel`);let r=e.video&&vt(),i=e.video&&(e.playlist?.length??0)>1;await Ce(()=>N.load({title:e.name,artist:``,album:``,duration:0,url:P.url(r||i?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),Hn(e.video),E===e&&(w=`Watching ${e.name}, live on this server.`),B()}function uo(){let e=E;return e?Xe?!0:ye>=5?(w=`${e.name} stopped, and did not come back.`,E=null,D=null,B(),!0):(ye+=1,w=`${e.name} started over; rejoining…`,B(),Xe=setTimeout(()=>{Xe=null,E===e&&lo(e,!1)},2e3),!0):!1}function fo(e){a.partiesNote.hidden=!1,a.partiesNote.textContent=e,H(e)}async function po(e,t){fo(`Restarting ${t}…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));fo(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{fo(`could not reach the server`)}$()}async function mo(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){fo(`Renaming ${t}…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));fo(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{fo(`could not reach the server`)}E?.id===e&&(E={...E,name:r}),$(),B()}}async function ho(e,t){fo(`Taking ${t} off the air…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));if(fo(n.ok?`${t} is off the air.`:r.error??`that did not work`),!n.ok)return!1}catch{return fo(`could not reach the server`),!1}return E?.id===e&&(E=null,N.stop()),!0}function go(e,t,n,r){if(e.classList.contains(`removing`))return;t.disabled=!0,t.setAttribute(`aria-busy`,`true`);let i=document.createElement(`span`);i.className=`delete-spinner`,i.setAttribute(`role`,`status`),i.setAttribute(`aria-label`,`Removing`),i.textContent=``,t.after(i),n().then(n=>{if(!n){i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`);return}e.classList.add(`removing`),window.setTimeout(()=>{e.remove(),r?.()},260)}).catch(()=>{i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`)})}async function _o(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{w=e,B();return}n===`✓`||n===`✓`?o(t,`check`):g(t,()=>p(n)),setTimeout(()=>{t.innerHTML=r},1200)}function vo(e,t=0){let n=yo();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 yo(){if(ae!==``)return ae;let e=c===`remote`?P.shareLink:``;return/\/admin\//.test(e)?``:e}function bo(e){if(y===``)return;let t=y;if(t===`live`){y=``,e.server.playing?co(e.server.nowPlaying):(w=`Nothing is playing on this server right now.`,B());return}if(t.startsWith(`link:`)){y=``,Wn(t.slice(5));return}if(t.startsWith(`golive:`)){y=``,a.linkUrl.value=t.slice(7),fr().then(()=>Qn());return}if(t.startsWith(`track:`)){y=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&hn(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&&(y=``,lo({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function xo(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${v(P.address)}:${e.key}`;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 s=document.createElement(`button`);s.type=`button`,s.className=`button`,wt(s,e.playLabel??`Join party`),s.hidden=e.key.startsWith(`channel:`)&&E?.id===e.key.slice(8),s.addEventListener(`click`,e.onPlay),a.append(s);let c=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,o(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(c(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;_o(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(c(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{_o(e.direct??``,t,`✓`)})),e.onRestart&&a.append(c(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(c(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(c(`remove`,`Remove: take it off the air`,n=>{go(t,n,e.onStop,()=>void $())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,_(s,`aria-label`,()=>`${p(e.playLabel??`Join party`)}: ${e.title}`);let l=document.createElement(`details`);l.className=`party-actions`;let u=document.createElement(`summary`);return u.textContent=`⋯`,_(u,`aria-label`,()=>`${p(`Show more`)}: ${e.title}`),a.removeChild(s),l.append(u,a),t.append(n,s),a.childElementCount&&t.append(l),t}let So=``;function Co(e,t){So=e;let n=e!==``&&t===e;a.loadHome.hidden=e===``,a.homeNote.hidden=e===``,e!==``&&(a.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,a.loadHome.disabled=!1)}a.loadHome.addEventListener(`click`,()=>{So!==``&&(a.loadHome.disabled=!0,H(`Reading this server's files…`),(async()=>{try{let e=await fetch(P.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:So})}),t=await e.json();H(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{H(`could not reach the server`)}finally{a.loadHome.disabled=!1}})())});let wo=async e=>{a.goLive.disabled=!0,a.stopLive.disabled=!0,a.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(P.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();a.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{a.shareNote.textContent=`could not reach the server`}finally{a.goLive.disabled=!1,a.stopLive.disabled=!1,await eo()}};a.goLive.addEventListener(`click`,()=>void wo(!0)),a.stopLive.addEventListener(`click`,()=>void wo(!1));function To(e){let t=document.createElement(`b`);return t.textContent=e,t}a.shareCopy.addEventListener(`click`,()=>{a.shareLink.select(),navigator.clipboard?.writeText(a.shareLink.value).then(()=>{a.shareNote.textContent=`Copied. Send it to anybody.`},()=>{a.shareNote.textContent=`Copy it from the box above.`})}),a.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=a.shareTo.value.trim();t!==``&&(async()=>{a.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:yo()})}),n=await e.json();a.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(a.shareTo.value=``)}catch{a.shareNote.textContent=`could not send that`}})()}),a.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(fn,a.listenHere.checked?`1`:`0`)}catch{}c===`remote`&&(async()=>{a.listenHere.checked?(await P.send({type:`stop`}),await vn(x.index)):(N.stop(),T=-1),B()})()}),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===a.transport)switch(e.key){case` `:e.preventDefault(),yn();return;case`s`:xn();return;case`n`:case`ArrowRight`:bn(1);return;case`p`:case`ArrowLeft`:bn(-1);return;case`ArrowDown`:e.preventDefault(),hn(Math.min(F()-1,I()+1));return;case`ArrowUp`:e.preventDefault(),hn(Math.max(0,I()-1));return}});let Eo=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Eo=e,a.install.hidden=!1}),a.install.addEventListener(`click`,()=>{Eo?.prompt(),Eo=null,a.install.hidden=!0});try{let e=localStorage.getItem(dn);e!==null&&(a.volume.value=String(Math.round(Number(e)*100)),N.volume=Number(e));let t=localStorage.getItem(ln);t&&(a.remoteUrl.value=t),localStorage.getItem(fn)===`0`&&(a.listenHere.checked=!1)}catch{}(async()=>{if(a.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await Je(e)===null)return;let t=await Ge(e);t&&t.trackCount!==0&&(a.remoteUrl.value=e,c=`remote`,w=``,P.connect(e),io(!0),ea(),B())})(),wr();let Do=()=>{document.visibilityState===`visible`&&!a.partiesPanel.hasAttribute(`data-closed`)&&wr()},Oo=setInterval(Do,2e3);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(wr(),$())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(Oo),to&&clearInterval(to),xr?.abort(),no?.abort(),xr=null,no=null,ro+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(Oo),Oo=setInterval(Do,2e3),Do(),c===`remote`&&io(!0))}),(()=>{if(mn||Ze!==``)return;let e=()=>N.source!==``||N.playing||Se()||E!==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=()=>{mn=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||N.playJingle(n).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,N.playJingle(n).then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),B(),requestAnimationFrame(zn)}hn(),ie(),ue(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{e as n,u as t};
3
+ `))>=0;){let e=i.slice(0,c);i=i.slice(c+2),e.startsWith(`data: `)&&this.event(JSON.parse(e.slice(6)))}if(i.length>128e3)throw Error(`Invalid live audio response.`)}}finally{t.signal.removeEventListener(`abort`,a),await n.cancel().catch(()=>{}),n.releaseLock()}}event(e){if(e.type===`error`)throw N(e.error,e.retryable?503:400);if(e.type===`status`){this.options.status(`Live translated audio · ${e.listeners} ${e.listeners===1?`listener`:`listeners`}`);return}let t=`nixamp-shared:${e.id}`;if(e.type===`line`){for(let[e,t]of this.clips)t.ended&&(t.taken||Date.now()-t.until>12e3)&&this.clips.delete(e);for(;this.clips.size>=24;){let e=this.clips.entries().next().value;e[1].ended||e[1].controller.error(N(`Catching up with live audio…`,503)),this.clips.delete(e[0])}let n,r=new ReadableStream({start:e=>{n=e},cancel:()=>{let e=this.clips.get(t);e&&(e.ended=!0),this.clips.delete(t)}});this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t);return}let n=this.clips.get(t);if(!n||n.ended)return;if(e.type===`end`){n.ended=!0,n.controller.close();return}let r=Uint8Array.from(atob(e.data),e=>e.charCodeAt(0));if(n.bytes+=r.length,n.bytes>2097152)throw Error(`The live audio segment was too large.`);n.controller.enqueue(r)}},L=e=>new Intl.NumberFormat(f.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),R=e=>document.getElementById(e),Zt=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=R(`translation-purchase`);plan=R(`translation-plan`);coin=R(`translation-coin`);buy=R(`translation-checkout`);note=R(`translation-purchase-note`);checkoutLink=R(`translation-checkout-link`);constructor(e){this.options=e,R(`translation-purchase-close`).addEventListener(`click`,()=>this.dialog.close()),this.dialog.addEventListener(`close`,()=>{this.timer&&clearTimeout(this.timer),this.timer=null,this.opener?.focus({preventScroll:!0})}),R(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),R(`translation-check-payment`).addEventListener(`click`,()=>void this.check()),window.addEventListener(`pagehide`,()=>{this.timer&&clearTimeout(this.timer)}),setInterval(()=>{this.options.account()&&(!this.access||this.access.required)&&this.refresh()},3e4)}status(e){this.note.textContent!==e&&(this.note.textContent=e)}loaded(){return this.access!==null}loadingMessage(){return this.problem||`Checking free sessions and audio credit…`}ready(){let e=this.access;return e?.required===!1||!!(e&&((e.free?.remaining??0)>0||e.free?.activeUntil&&Date.parse(e.free.activeUntil)>Date.now()||e.balanceMicros>0&&e.expires&&Date.parse(e.expires)>Date.now()))}async startSession(e){if(this.access?.required===!1)return;let t=await fetch(`/api/v1/translation-passes/session`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({resource:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();if(!t.ok)throw Error(n.error||`This free session could not be started.`);this.refresh()}button(){let e=document.createElement(`button`);return e.type=`button`,e.textContent=`$`,_(e,`title`,()=>p(`Buy translated audio`)),_(e,`aria-label`,()=>p(`Buy translated audio`)),e.setAttribute(`aria-haspopup`,`dialog`),e.setAttribute(`aria-controls`,`translation-purchase`),e.dataset.translationBuy=``,e.addEventListener(`click`,()=>this.open(e)),e}open(e){this.opener=e,this.dialog.open||this.dialog.showModal(),this.status(``),this.refresh().then(()=>{this.order&&this.dialog.open&&this.check()})}async refresh(){let e=this.options.account();this.problem=``,this.account!==e&&(this.account=e,this.access=null,this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0);try{let t=await fetch(`/api/v1/translation-passes`,{signal:AbortSignal.timeout(15e3)}),n=await t.json();if(this.account!==e||this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Purchases are unavailable.`);this.access=n;let r=this.access.coins??[];[...this.coin.options].map(e=>e.value).join()!==r.join()&&document.activeElement!==this.coin&&this.coin.replaceChildren(...r.map(e=>new Option(e.replaceAll(`_`,` · `),e)));let i=this.access.plans??[];this.plan.options.length||this.plan.replaceChildren(...i.map(e=>{let t=new Option(``,e.id);return g(t,()=>`${e.name} · ${L(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${p(`Audio credit`)}: ${L(a.balanceMicros)}${a.expires?` · ${new Date(a.expires).toLocaleString(f.language)}`:``}`:``,s=this.access.free,c=()=>a.required&&s?f.language===`en`?`${s.remaining} of ${s.limit} free sessions left today${s.activeUntil?` · free session active`:``}`:`${p(`Free sessions`)}: ${f.number(s.remaining)}/${f.number(s.limit)}${s.activeUntil?` · ✓`:``}`:``;g(R(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(R(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(R(`translation-free-description`),()=>s?`Each account gets ${s.limit} free sessions a day, shared across paid panels and upgrades. Each lasts while you listen, within daily usage limits. Reconnect within ${s.reconnectSeconds} seconds to keep the same session. Resets at ${new Date(s.resets).toLocaleString(f.language)} (midnight UTC). Free time is used before purchased credit.`:``),R(`translation-sign-in`).hidden=!!e,this.buy.disabled=!e||!this.access.available||this.loading,!this.access.available&&this.dialog.open&&this.status(this.access.required?`Checkout is temporarily unavailable. Free sessions and existing credit still work.`:`This server sponsors translated audio; no purchase is required.`);let l=new URLSearchParams(location.search).get(`translation_order`),u=this.access.orders?.find(e=>e.id===l||e.id===this.order)??this.access.orders?.[0];u&&!this.order&&(this.order=u.id,this.link(u.url)),l&&!this.order&&/^[a-f0-9-]{36}$/i.test(l)&&e&&(this.order=l,this.check()),this.options.changed(),this.order&&!this.dialog.open&&!this.checking&&this.check()}catch(e){this.problem=e instanceof Error?e.message:`Audio credit could not be checked. Use Buy to retry.`,this.dialog.open&&this.status(this.problem),this.options.changed()}}describe(){let e=this.access?.plans.find(e=>e.id===this.plan.value);if(!e)return;let t=Math.floor(e.priceCents/100/((.66/60+.05)*5));R(`translation-plan-description`).textContent=`${L(e.priceCents*1e4)} credit. Expires ${e.days===1?`24 hours`:`${e.days} days`} after payment. About ${t} minutes at 1,000 spoken characters/minute; usage varies. No automatic renewal.`}link(e){if(!/^https:\/\/coinpayportal\.com\/pay\/[a-f0-9-]{36}$/i.test(e))throw Error(`Invalid checkout address.`);this.checkoutLink.href=e,this.checkoutLink.hidden=!1,R(`translation-check-payment`).hidden=!1}async purchase(){if(this.loading||!this.account)return;let e=this.account,t=`${this.plan.value}|${this.coin.value}`;(!this.requestKey||this.selected!==t)&&(this.requestKey=crypto.randomUUID(),this.selected=t),this.loading=!0,this.buy.disabled=!0,this.status(`Preparing secure checkout…`);try{let t=await fetch(`/api/v1/translation-passes/checkout`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({plan:this.plan.value,coin:this.coin.value,requestKey:this.requestKey}),signal:AbortSignal.timeout(2e4)}),n=await t.json();if(this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Checkout could not be opened.`);this.order=n.id,this.link(n.url),this.status(`Open secure checkout to pay. Your video keeps playing in this tab. Credit appears after payment confirmation.`),this.poll()}catch(e){this.status(e instanceof Error?e.message:`Checkout could not be opened.`)}finally{this.loading=!1,this.buy.disabled=!this.account||!this.access?.available}}poll(){this.timer&&clearTimeout(this.timer),this.dialog.open&&this.order&&(this.timer=setTimeout(()=>void this.check(),5e3))}async check(){if(!this.order||!this.account||this.checking)return;this.checking=!0;let e=this.order,t=this.account;try{let n=await fetch(`/api/v1/translation-passes/orders/${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(2e4)}),r=await n.json();if(this.account!==t||this.order!==e)return;if(!n.ok)throw Error(r.error||`Payment status could not be checked.`);if(r.status===`paid`){this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0,R(`translation-check-payment`).hidden=!0,this.status(`Payment confirmed. Enable Translate audio whenever you are ready.`);let e=new URL(location.href);e.searchParams.delete(`translation_order`),history.replaceState(history.state,``,e),await this.refresh();return}this.status(r.status===`pending`?`Waiting for payment confirmation…`:`Payment ${r.status}. Check again if you have already sent it.`),r.status===`pending`&&this.poll()}catch(e){this.status(e instanceof Error?e.message:`Payment status could not be checked.`)}finally{this.checking=!1}}},Qt=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}},$t=class{options;tracker=new Qt;generation=0;pending=null;committedUntil=null;running=null;controller=null;translating=null;translationController=null;recognitionFailures=0;translationFailures=0;translations=[];constructor(e){this.options=e}reset(){this.generation++,this.controller?.abort(),this.translationController?.abort(),this.pending=null,this.running=null,this.translating=null,this.recognitionFailures=this.translationFailures=0,this.translations=[],this.committedUntil=null,this.tracker.reset()}push(e){this.committedUntil??=e.freshAt,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 N(i.error||`Audio translation is unavailable.`,r.status);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;this.pending=null;try{if(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(kt(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;this.recognitionFailures=0;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=o.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),l=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),u=[],d=()=>{u.length&&(c.push({channel:this.options.channel(),at:t.at+u[0].start*1e3,until:t.at+u.at(-1).end*1e3,text:u.map(e=>e.text).join(` `).trim(),language:s,speaker:o.id,voiceProfile:a.profile}),u=[])};for(let e of l)u.length&&e.start-u.at(-1).end>=.45&&d(),u.push(e),(/[.!?。!?]$/.test(e.text)||u.map(e=>e.text).join(` `).length>=400)&&d();u.length&&(i<r.length-1||t.until-(t.at+u.at(-1).end*1e3)>=350||t.until-(t.at+u[0].start*1e3)>=3e3)&&d()}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(!c.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...c.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:c,language:s,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!Wt(t)||++this.recognitionFailures>=3)throw t;this.options.status(`Speech recognition interrupted · listening for the next phrase…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.running===e&&(this.running=null)}}async translate(e){this.translating=e;try{for(;this.translations.length&&e===this.generation;){let t=this.translations.shift();try{let{lines:n}=t,{language:r,target:i,until:a}=t;if(Date.now()-a>12e3)continue;let o=new AbortController;if(this.translationController=o,i&&r!==i){if(!r)throw N(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:n.map(e=>e.text),from:r,to:i})},AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]));if(e.texts.length!==n.length||e.texts.some(e=>!e.trim()))throw N(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((t,n)=>({...t,original:t.text,sourceLanguage:r,language:i,text:e.texts[n]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>en(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!Wt(t)||++this.translationFailures>=3)throw t;this.options.status(`Translation interrupted · catching up with live speech…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.translating===e&&(this.translating=null)}}};function en(e){let t=e.text.trim();if(!t)return[];let n=[],r=t;for(;r.length>600;){let e=r.lastIndexOf(` `,600),t=e>300?e:600;n.push(r.slice(0,t)),r=r.slice(t).trimStart()}r&&n.push(r);let i=0;return n.map(n=>{let r=e.at+(e.until-e.at)*i/t.length;return i+=n.length+1,{...e,text:n,at:r,until:Math.min(e.until,e.at+(e.until-e.at)*i/t.length)}})}var tn=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,nn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,rn=/\s+(?:vs\.?|v\.?|at|@)\s+/i,an=/^(?: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 on(e){let t=e.replace(nn,``).replace(nn,``).trim().split(rn);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!an.test(t)})}function sn(e){let t=String(e??``).trim();return t===``?!1:on(t.replace(tn,``))||on(t)}function cn(e,t){e.classList.add(`long-string-scroller`),t.classList.add(`long-string-scroller-content`),t.title=t.textContent??``;let n=0,r=0,i=0,a=0,o=!1,s=null,c=()=>{n=0;let r=a+(i-a)*.22;if(a=Math.abs(i-r)<.5?i:r,t.style.setProperty(`--path-shift`,`${a}px`),Math.abs(i-a)>=.5){n=requestAnimationFrame(c);return}o&&(o=!1,delete t.dataset.pan,t.style.removeProperty(`--path-shift`),s=setTimeout(()=>{s=null,e.style.removeProperty(`min-height`)},280))},l=()=>{n||=requestAnimationFrame(c)};e.addEventListener(`pointerenter`,n=>{n.pointerType===`mouse`&&(s!==null&&(clearTimeout(s),s=null),e.style.minHeight=`${e.getBoundingClientRect().height}px`,o=!1,t.dataset.pan=`true`)}),e.addEventListener(`pointermove`,n=>{if(t.dataset.pan!==`true`)return;r=n.clientX;let a=e.scrollWidth-e.clientWidth;if(a<=0)return;let o=e.getBoundingClientRect(),s=Math.max(0,Math.min(1,(r-o.left)/Math.max(1,o.width))),c=s*s*(3-2*s);i=-a*c,l()}),e.addEventListener(`pointerleave`,()=>{i=0,o=!0,l()})}var ln=`nixamp.remote`,un=`nixamp.defaultServer`,dn=`nixamp.volume`,fn=`nixamp.listenHere`,pn=1e4,mn=!1;function z(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function hn(){let e=new URLSearchParams(location.search).get(`embed`)===`1`;document.body.classList.toggle(`classroom-embed`,e);let t=null;try{t=localStorage.getItem(st)}catch{}let n=ct(navigator.userAgent,location.search,navigator.maxTouchPoints,t);if(document.body.classList.toggle(`tv`,n),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(st,n?`1`:`0`)}catch{}let r=document.getElementById(`tv-toggle`);r&&(g(r,()=>n?`TV mode: on`:p(`TV mode`)),r.title=n?`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.`,r.addEventListener(`click`,()=>{try{localStorage.setItem(st,n?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let i=ut(n),a={status:z(`status`),source:z(`source`),install:z(`install`),video:z(`video`),audio:z(`audio`),title:z(`title-line`),album:z(`album-line`),meta:z(`meta-line`),metaBlurb:z(`meta-blurb`),liveLine:z(`live-line`),downloadNow:z(`download-now`),wayInHere:z(`way-in-here`),embed:z(`embed`),embedFrame:z(`embed-frame`),linkForm:z(`link-form`),linkUrl:z(`link-url`),linkServer:z(`link-server`),linkGoLive:z(`link-go-live`),goLiveNow:z(`go-live-now`),elapsed:z(`elapsed`),total:z(`total`),seek:z(`seek`),fullscreen:z(`fullscreen`),copyNow:z(`copy-now`),copyNixamp:z(`copy-nixamp`),canvas:z(`spectrum`),glyphs:z(`glyphs`),levels:z(`levels`),playlist:z(`playlist`),livePlaylist:z(`live-playlist`),livePlaylistPanel:z(`live-playlist-panel`),playlistPager:z(`playlist-pager`),crumbs:z(`crumbs`),filter:z(`filter`),playlistTitle:z(`playlist-panel`),note:z(`note`),linkNote:z(`link-note`),logList:z(`log-list`),files:z(`files`),folder:z(`folder`),remoteUrl:z(`remote-url`),remoteServer:z(`remote-server`),remoteForm:z(`remote-form`),remoteState:z(`remote-state`),disconnect:z(`disconnect`),browse:z(`browse`),panelsToggle:z(`panels-toggle`),panelsPanel:z(`panels-panel`),panelsList:z(`panels-list`),panelsSave:z(`panels-save`),panelsReset:z(`panels-reset`),accountForm:z(`account-form`),accountEmail:z(`account-email`),accountPassword:z(`account-password`),accountSubmit:z(`account-submit`),accountToggle:z(`account-toggle`),accountProviders:z(`account-providers`),accountPanel:z(`account-panel`),accountElsewhere:z(`account-elsewhere`),welcome:z(`welcome`),welcomeCreate:z(`welcome-create`),welcomeBrowse:z(`welcome-browse`),welcomeHide:z(`welcome-hide`),accountSignOut:z(`account-signout`),accountNote:z(`account-note`),personaForm:z(`persona-form`),personaHandle:z(`persona-handle`),personaVoice:z(`persona-voice`),personaProfile:z(`persona-profile`),personaNote:z(`persona-note`),adminPanel:z(`admin-panel`),adminNote:z(`admin-note`),adminSaid:z(`admin-said`),adminConnections:z(`admin-connections`),publishPanel:z(`publish-panel`),publishNote:z(`publish-note`),publishList:z(`publish-list`),adminRestream:z(`admin-restream`),adminReplace:z(`admin-replace`),adminSource:z(`admin-source`),adminName:z(`admin-name`),adminAdd:z(`admin-add`),homeNote:z(`home-note`),loadHome:z(`load-home`),directory:z(`directory`),recentNote:z(`recent-note`),recentList:z(`recent-list`),followingNote:z(`following-note`),followingList:z(`following-list`),serversPanel:z(`servers-panel`),serversNote:z(`servers-note`),serversList:z(`servers-list`),favoritesPanel:z(`favorites-panel`),favoritesNote:z(`favorites-note`),favoritesList:z(`favorites-list`),favHere:z(`fav-here`),partiesPanel:z(`parties-panel`),partiesNote:z(`parties-note`),partiesList:z(`parties-list`),partyForm:z(`party-form`),partyCode:z(`party-code`),partyJoin:z(`party-join`),connectionsNote:z(`connections-note`),connectionsList:z(`connections-list`),catalogsPanel:z(`catalogs-panel`),catalogsNote:z(`catalogs-note`),catalogsForm:z(`catalogs-form`),catalogSource:z(`catalog-source`),catalogName:z(`catalog-name`),catalogsList:z(`catalogs-list`),catalogsCrumbs:z(`catalogs-crumbs`),catalogsFilter:z(`catalogs-filter`),catalogsEntries:z(`catalogs-entries`),notifyPanel:z(`notify-panel`),notifyNote:z(`notify-note`),notifyWeb:z(`notify-web`),notifyEmail:z(`notify-email`),notifySms:z(`notify-sms`),notifyPhone:z(`notify-phone`),notifyPhoneForm:z(`notify-phone-form`),notifyPhoneNote:z(`notify-phone-note`),directoryNote:z(`directory-note`),directoryList:z(`directory-list`),sharePanel:z(`share-panel`),trollboxPanel:z(`trollbox-panel`),trollboxNote:z(`trollbox-note`),trollboxList:z(`trollbox-list`),trollboxForm:z(`trollbox-form`),trollboxInput:z(`trollbox-input`),trollboxMic:z(`trollbox-mic`),trollboxEdit:z(`trollbox-edit`),trollboxEditLabel:z(`trollbox-edit-label`),transcriptPanel:z(`transcript-panel`),transcriptNote:z(`transcript-note`),transcriptOn:z(`transcript-on`),transcriptLanguage:z(`transcript-language`),transcriptAudio:z(`transcript-audio`),transcriptVoiceSettings:z(`transcript-voice-settings`),transcriptBackground:z(`transcript-background`),transcriptBackgroundLevel:z(`transcript-background-level`),transcriptBackgroundValue:z(`transcript-background-value`),transcriptAudioNote:z(`transcript-audio-note`),transcriptSpeakers:z(`transcript-speakers`),transcriptList:z(`transcript-list`),subtitle:z(`subtitle`),shareNote:z(`share-note`),shareLink:z(`share-link`),shareCopy:z(`share-copy`),sharePhone:z(`share-phone`),shareSend:z(`share-send`),liveControls:z(`live-controls`),goLive:z(`go-live`),stopLive:z(`stop-live`),shareTo:z(`share-to`),listenOnly:z(`listen-only`),listenHere:z(`listen-here`),volume:z(`volume`),volumeToggle:z(`volume-toggle`),prev:z(`prev`),playPause:z(`play-pause`),transport:z(`transport`),stop:z(`stop`),next:z(`next`),shareNow:z(`share-now`),refreshPlayer:z(`refresh-player`),appVersion:z(`app-version`)};a.appVersion.textContent=`nixamp 0.28.22`;let o=(e,t)=>{oe(e,t)};o(a.copyNixamp,`link`);let s=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,c=`local`,l=``,u=[],d=``,m=!0,h=``;function v(e){try{return new URL(e).origin}catch{return e}}let ee=!1,y=``,te=0,ne=new Map,re=e=>ne.get(U(e))??null;function ie(e,t){let n=n=>{ee=n,y=``,a.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),a.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,o(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`,o(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:K?`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 ae=``,b=[],le=0,x=Me(),ue=`idle`,S=``,w=`Pick files, or connect to a nixamp running somewhere else.`,fe=!1,T=-1,ge=null,_e=0,E=null;function ve(e){return e?/^https?:\/\//i.test(e)?e:P.url(e):``}let ye=0,be=0,xe=!1,Se=()=>!N.needsInteraction&&(be>0||xe);async function Ce(e){be+=1,B();try{return await e()}finally{--be,B()}}let D=null,O=null,we=``,Ee=null,De=``,k=null,A=null,ke=0;function je(){a.embed.hidden||(a.embedFrame.src=`about:blank`),a.embed.hidden=!0}let Pe=null,Re=``,ze=null;function Be(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Re=i,ze&&clearTimeout(ze),ze=null,!r){if(Pe?.key===i)return;Pe=null}if(c!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(P.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Re!==i)return;Pe={key:i,match:r.match??null},B();let a=Pe.match;a?.kind===`fixture`&&it(a)!==`post`&&(ze=setTimeout(()=>{ze=null,!(Re!==i||N.source===``&&!E)&&Be(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Ve=!1,He=``,We=``,Xe=null,Ze=``,rt=``,at=``,j=Array(24).fill(0),lt=Array(24).fill(0),ft=[],M=()=>c===`remote`&&!a.listenHere.checked,pt=()=>c===`remote`&&!a.adminPanel.hidden,mt=!1,gt=()=>pt()||c===`remote`&&mt;function vt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:a.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function St(){if(c!==`remote`||k)return null;if(D?.catalog&&D.entry)return{kind:`entry`,catalog:D.catalog,entry:D.entry};if(E)return{kind:`channel`,id:E.id,name:E.name};let e=x.tracks[I()];return e&&(N.source!==``||M())?{kind:`track`,index:I(),name:Qt(e)}:null}async function Ct(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;w=`Putting ${n} on the air…`,B();try{let r=``,i=``,a=!0;{let t=e.kind===`folder`?`/api/folders/live`: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(P.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),s=await o.json().catch(()=>({}));if(!o.ok){w=o.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:s.error??`${n} would not go on the air.`,B();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(pt()&&(Ve?await fetch(P.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await wo(!0)),await eo(),$(),i!==``&&E?.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 lo({id:i,name:n,video:a},!0,t)}let o=vo(r),s=He?` Call ${We||`the line`} and key ${He} to talk about it.`:``;o===``?w=`${n} is on the air and you are watching it.${s}`:(await _o(o,t,`✓`),w=`${n} is on the air and you are watching it. Link copied.${s}`),B()}catch{w=`could not reach the server`,B()}finally{t.disabled=!1}}function wt(e,t=`Join party`){o(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);g(n,()=>` ${p(t)}`),e.append(n),_(e,`title`,()=>p(/join/i.test(t)?`Join live`:t))}wt(a.partyJoin);function Wt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,o(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(),Ct(e(),n)}),n}let N=new Ae({audio:a.audio,video:a.video},{readable:e=>P.owns(e),onTime:(e,t)=>{let n=b[le];c===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),B()},onEnded:()=>{uo()||qn()||gn()||c===`remote`&&T<0&&!M()||bn(1)},onState:()=>B(),onBusy:e=>{xe!==e&&(xe=e,B())},onError:e=>{if(!uo()&&!(ke!==0&&Date.now()-ke<2e3)){if(A&&e===`this browser cannot play that format`){let e=A.url;if(A=null,ke=Date.now(),gt()){w=`That site will not let a page play it directly; going live with it on ${l||`the server`} instead.`,B(),a.linkUrl.value=e,Qn();return}w=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,B();return}w=e,B(),so()}}}),Gt=()=>M()&&!N.jinglePlaying,P=new Ue({onSnapshot:e=>{let t=e.tracks!==void 0||x.index!==e.index;if(x=Ne(x,e),y.startsWith(`track:`)&&x.tracks.length>0){let e=Number(y.slice(6));if(y=``,Number.isInteger(e)&&e>=0&&e<x.tracks.length){let t=te;vn(e).then(()=>{t>0&&(N.seek(t),setTimeout(()=>N.seek(t),600))})}}Gt()&&(j=e.bars.length>0?e.bars:j,lt=tt(lt,j)),B(),t&&O&&ao(O)},onStatus:(e,t)=>{ue=e,S=t??``,B()}}),F=()=>c===`remote`?x.tracks.length:b.length,I=()=>c===`remote`?M()||T<0?x.index:Math.min(T,Math.max(0,x.tracks.length-1)):le,Jt=()=>{let e=O?.server.nowPlaying||`Live`;return(!Ee||Ee.tracks!==x.tracks||Ee.index!==x.index||Ee.fallback!==e)&&(Ee={tracks:x.tracks,index:x.index,fallback:e,value:he(x.tracks,x.index,e)}),Ee.value},L=()=>c===`remote`&&!E&&D?.kind===`live`,R=()=>L()?Jt().fullTitle:en(),Qt=e=>{let t=ce(e);return e.folder?`${e.folder} / ${t}`:t},en=()=>{if(E){let e=E.id,t=O?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||E.name}if(k)return k.label;if(L())return Jt().title;let e=c===`remote`?x.tracks[I()]:b[I()];return e?Qt(e):p(`Nothing loaded.`)},tn=()=>{if(E)return`live on this server`;if(k)return`playing here, in this browser`;if(L()){let{context:e,position:t}=Jt();return[e,t,`live on ${l||`this server`}`].filter(Boolean).join(` · `)}return(c===`remote`?x.tracks[I()]:b[I()])?.album||`—`};function nn(){if(c!==`remote`||E===null&&D?.kind!==`live`){a.liveLine.hidden=!0,a.liveLine.replaceChildren(),delete a.liveLine.dataset.drawn;return}let e=l||`this server`,t=E?E.name:Jt().fullTitle,n=[E?`Live on ${e}: `:`Live from ${e}, now playing: `,To(t)],r=E?O?.channels.find(e=>e.id===E?.id)?.code??``:Ve?He:``;r&&n.push(`. To talk about it, call `,To(We||`the line`),` and key `,To(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);a.liveLine.dataset.drawn!==i&&(a.liveLine.dataset.drawn=i,a.liveLine.hidden=!1,a.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let rn=()=>M()?x.tracks[I()]?.duration??0:N.duration,an=()=>M()?x.position:N.position,on=()=>M()?x.playing:N.playing;async function hn(e){if(c===`remote`){if(M()){await P.send({type:`play`,index:e});return}await vn(e);return}let t=b[e];t&&(le=e,E=null,D={kind:`file`},await Ce(()=>N.load(t,!0)),Hn(t.video),Un(),B())}function gn(){return!ge||ge.length<2?!1:(_e=(_e+1)%ge.length,hn(ge[_e]),!0)}function _n(e){e.length!==0&&(ge=[...e],_e=0,hn(ge[0]))}async function vn(e){let t=x.tracks[e];t&&(T=e,E=null,D={kind:`file`},Be(t.title,`auto`),await Ce(()=>N.load({title:Qt(t),artist:t.artist,album:t.album,duration:t.duration,url:P.media(e,0),video:t.video===!0,objectUrl:!1},!0)),Hn(t.video===!0),Un())}async function yn(){if(N.needsInteraction){await N.play(),B();return}if(M()){await P.send({type:`toggle`});return}F()!==0&&(N.playing?N.pause():N.position>0?await N.play():await hn(I()),B())}async function bn(e){ge=null;let t=F();if(t!==0){if(M()){await P.send({type:e>0?`next`:`prev`});return}await hn((I()+e+t)%t)}}async function xn(){if(ge=null,je(),k=null,A=null,M()){await P.send({type:`stop`});return}E=null,D=null,N.stop(),j=Array(24).fill(0),lt=[...j],B()}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)))],wn=``;function Tn(){let e=[],t=``,n=null,r=E?O?.channels.find(e=>e.id===E?.id):void 0;E&&r?.ended&&De!==E.id&&(De=E.id,Mr(`${E.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=N.source===``&&!E&&!(M()&&x.tracks[I()]);if(!i){E&&r?.ended?e.push(`ENDED`):E?e.push(D?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):D?.kind===`vod`?e.push(`ON DEMAND`):D?.kind===`live`?e.push(`LIVE`):c===`remote`&&M()?e.push(`ON THE SERVER`):e.push(`FILE`),!a.video.hidden&&a.video.videoWidth>0?e.push(`${a.video.videoWidth}×${a.video.videoHeight}`):a.video.hidden?e.push(`audio`):e.push(`video`),r?(e.push(r.via===`pull`?`${r.listeners} watching`:`${r.listeners} listening · over ${r.via}`),r.startedAt>0&&e.push(`on air ${se(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),pt()&&r.error&&e.push(r.error)):c===`remote`&&!E?(x.tracks[I()]&&F()>0&&e.push(`${L()?`library track`:`track`} ${I()+1} of ${F()}`),M()&&O&&e.push(`${O.server.playing?`playing`:`stopped`} on ${l||`the server`}`)):c===`local`&&F()>0&&e.push(`track ${I()+1} of ${F()}`),D?.catalog!==void 0&&(D.kind===`channel`?E!==null:D.kind===`vod`&&N.source!==``)&&D?.catalog&&(e.push(D.entry?.group?`${D.catalog.name} › ${D.entry.group}`:D.catalog.name),t=D.entry?.logo??``),t===``&&E&&(t=ve(r?.art??E.art));let i=Pe?.key===Re?Pe.match:null;if(i?.kind===`fixture`)n=ot(i),e.unshift(n.status,...n.chips);else if(i){i.image&&(t=i.image);let n=i.data;if(i.kind===`title`){i.year&&e.push(String(i.year));let t=typeof n.rating==`number`?n.rating:null;t&&e.push(`★ ${t.toFixed(1)}`);let r=Array.isArray(n.genres)?n.genres.slice(0,2).map(String):[];r.length&&e.push(r.join(` · `));let a=typeof n.runtimeMin==`number`?n.runtimeMin:0;a&&e.push(`${a} min`)}else if(i.kind===`channel`){let t=typeof n.country==`string`?n.country:``,r=Array.isArray(n.categories)?n.categories.slice(0,2).map(String):[],i=typeof n.network==`string`?n.network:``;t&&e.push(t),r.length&&e.push(r.join(` · `)),i&&e.push(i)}}if(E&&D?.link){let t=``;try{t=new URL(D.link.url).hostname.replace(/^www\./,``)}catch{}e.push(D.link.extractor&&D.link.extractor!==`direct`&&D.link.extractor!==`generic`?`${D.link.extractor} · ${t}`:t||`link`)}Ve&&He&&M()&&!E&&D?.kind!==`live`&&e.push(We?`☎ ${We} · key ${He}`:`☎ code ${He}`)}let o=Pe?.key===Re?Pe.match:null,s=!i&&!n&&o?.summary?o.summary:``,u=e.map(e=>/^on air \d/.test(e)?`on air`:e),d=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${u.join(`|`)}|${s}`;if(d===wn){let t=a.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}wn=d,a.meta.hidden=e.length===0,a.metaBlurb.textContent=s,a.metaBlurb.hidden=s===``;let f=[];if(n){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let r=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,r.push(i),n?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),r.push(t)}if(e.logo!==``){let n=document.createElement(`img`);n.className=`meta-team-logo`,n.alt=``,n.src=e.logo,n.addEventListener(`error`,()=>{n.hidden=!0}),t?r.unshift(n):r.push(n)}return r},r=document.createElement(`span`);r.className=`meta-dash`,r.textContent=`–`,e.replaceChildren(...t(n.away,!0),r,...t(n.home,!1)),f.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=o?.kind===`title`&&t===o.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let t of e){let e=document.createElement(`span`);e.className=/^on air \d/.test(t)?`meta-chip meta-chip-clock`:n?.state===`in`&&t===n.status?`meta-chip chip-live`:`meta-chip`,e.textContent=t,f.push(e)}a.meta.replaceChildren(...f)}function B(){let e=F(),t=on(),n=Se();g(a.status,()=>p(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),a.status.dataset.playing=n?`loading`:String(t),g(a.title,()=>en()),a.title.classList.toggle(`with-context`,L()),a.album.classList.toggle(`with-context`,L()),(L()||E)&&Un(),nn(),Tn(),a.goLiveNow.hidden=!gt()||E!==null||L()||St()===null;let r=t?`${R()} · ${s}`:s;document.title!==r&&(document.title=r),a.copyNow.hidden=N.source===``,a.copyNixamp.hidden=Vi()===``,a.shareNow.hidden=Bi()===``,yi(),Mi(),a.downloadNow.hidden=!(E&&D?.link?.download),Yn(),a.album.textContent=tn();let i=an(),o=rn();a.elapsed.textContent=se(i),a.total.textContent=o>0?se(o):`--:--`,fe||(a.seek.value=String(o>0?Math.round(i/o*1e3):0),a.seek.disabled=o<=0||M()),a.playPause.textContent=t?`❚❚`:`▶`,_(a.playPause,`aria-label`,()=>p(t?`Pause`:`Play`)),_(a.seek,`aria-valuetext`,()=>`${se(N.position)} ${f.language===`en`?`of`:`/`} ${se(N.duration)}`),_(a.volume,`aria-valuetext`,()=>f.number(Number(a.volume.value)/100,{style:`percent`})),_(a.playlistTitle,`data-title`,()=>c===`remote`?`Files on ${l||`this server`} (${e.toLocaleString(f.language)})`:`${p(`Playlist`)} (${f.number(e)})`),g(a.source,()=>c===`remote`?`connected · ${l||P.address.replace(/^https?:\/\//,``)||`—`}`:b.length>0?`local · ${b.length} files`:p(`no source`)),Vn(),g(a.remoteState,()=>c===`remote`?`${ue}${S?` — ${S}`:``}`:p(`not connected`)),a.remoteState.dataset.status=c===`remote`?ue:`idle`,a.disconnect.hidden=c!==`remote`;let u=N.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:c===`remote`&&x.note!==``?x.note:w;a.note.textContent=u,a.note.hidden=u===``,a.linkNote.textContent=u,a.linkNote.hidden=u===``,Mr(u),Fn(),a.glyphs.textContent=j.map(Cn).join(``);let[d,m]=Gt()?x.levels:N.levels();a.levels.textContent=Sn(d,m)}let En=``,V=``,Dn=0;function On(e){de(a.playlist),V=e,Dn=0,En=``,Fn()}function kn(e,t,n,r,i){if(a.playlistPager.hidden=n<=1,n<=1){a.playlistPager.replaceChildren();return}let o=(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`,()=>{de(a.playlist),Dn=t,En=``,Fn()}),i},s=document.createElement(`span`);s.className=`pager-where`,g(s,()=>`${r+1}–${i} of ${e.toLocaleString(f.language)}`),a.playlistPager.replaceChildren(o(`‹ Previous`,t-1,`The page before this one`),s,o(`Next ›`,t+1,`The page after this one`))}function An(e){if(a.crumbs.hidden=!e,!e)return;let t=V===``?[]:V.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`,()=>On(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))}),a.crumbs.replaceChildren(...r)}function jn(e,t,n){let r=document.createElement(`li`);r.className=`folder`;let i=document.createElement(`span`);i.className=`name`,i.textContent=`${e}/`;let a=document.createElement(`span`);a.className=`count`,a.textContent=`${t} file${t===1?``:`s`}`,r.append(i,a);let s=document.createElement(`button`);if(s.type=`button`,s.className=`row-main`,s.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),s.append(i,a),r.replaceChildren(s),s.addEventListener(`click`,t=>{t.stopPropagation(),On(V===``?e:`${V}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,o(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),_n(n)}),r.append(i)}return c===`remote`&&n.length>0&&gt()&&r.append(Wt(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let Mn=null,Nn=``,Pn=(e,t)=>{t.title=t.textContent??``,cn(e,t)};function Fn(){let e=E?O?.channels.find(e=>e.id===E?.id):void 0,t=e?.playlist;if(a.livePlaylistPanel.hidden=!(E&&t&&t.length>0),E&&t&&t.length>0){let n=t.map((t,n)=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`n`,i.textContent=String(n+1).padStart(2,` `);let a=t.lastIndexOf(`/`),o=document.createElement(`span`);o.className=`name row-file`,o.textContent=a<0?t:t.slice(a+1);let s=document.createElement(`span`);s.className=`row-path`,s.textContent=t;let c=document.createElement(`span`);c.className=`row-label`;let l=document.createElement(`span`);l.className=`row-value`,l.append(o);let u=document.createElement(`span`);return u.className=`row-value`,u.append(s),c.append(l),Pn(l,o),Pn(u,s),r.classList.add(`file-row`),r.append(i,c,u),r.setAttribute(`aria-readonly`,`true`),r.title=e.live===!1?`Part of this on-demand show`:`Live queue (read-only)`,n===(e.entry??0)&&r.setAttribute(`aria-current`,`true`),r});C(a.livePlaylist,...n)}else a.livePlaylist.replaceChildren();let n=c===`remote`?x.tracks:b,r=`${c}:${E?.id??``}:${t?.join(`|`)??``}:${e?.entry??0}:${V}:${a.filter.value}:${Dn}:${gt()}:${a.adminPanel.hidden}`;if(En&&Mn===n&&Nn===r){In();return}Mn=n,Nn=r;let s=c===`remote`?x.tracks.map(e=>({name:ce(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):b.map(e=>({name:ce(e),seconds:e.duration,group:``,folder:``,remote:!1})),l=a.filter.value.trim().toLowerCase(),u=s.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>l===``||`${e.folder}/${e.name}`.toLowerCase().includes(l)),d=e=>l!==``||V===``||e===V||e.startsWith(`${V}/`),f=e=>e===V,p=e=>{let t=V===``?e:e.slice(V.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},m=new Map;for(let e of u){if(!d(e.folder)||f(e.folder))continue;let t=p(e.folder);t!==``&&m.set(t,(m.get(t)??0)+1)}let h=u.filter(e=>f(e.folder)&&d(e.folder)),g=[...m].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),_=dt(g.length+h.length,Dn,i);Dn=_.page;let v=g.slice(_.from,_.to),ee=h.slice(Math.max(0,_.from-g.length),Math.max(0,_.to-g.length)),y=`${c}:${V}:${l}:${_.page}/${i}:${g.join(`,`)}:${h.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(y!==En){En=y,An(l===``&&(g.length>0||V!==``)),kn(g.length+h.length,_.page,_.pages,_.from,_.to);let e=[];for(let[t,n]of v){let r=V===``?t:`${V}/${t}`,i=u.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(jn(t,n,i))}let t=``,n=h.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(Ln(r.group)));let i=document.createElement(`li`);i.className=`row`,i.dataset.index=String(r.index);let a=document.createElement(`span`);a.className=`n`,a.textContent=String(r.index+1).padStart(2,` `);let s=r.folder?`${r.folder} / ${r.name}`:r.name,l=document.createElement(`span`);l.className=`name row-file`,l.textContent=r.name;let u=document.createElement(`span`);u.className=`row-path`,u.textContent=r.folder?`${r.folder}/${r.name}`:r.name;let d=document.createElement(`span`);d.className=`row-label`;let f=document.createElement(`span`);f.className=`row-value`,f.append(l);let p=document.createElement(`span`);p.className=`row-value`,p.append(u),d.append(f,p),Pn(f,l),Pn(p,u);let m=document.createElement(`span`);m.className=`time`,m.textContent=r.seconds>0?se(r.seconds):`--:--`;let h=document.createElement(`button`);h.type=`button`,h.className=`row-main`,h.setAttribute(`aria-label`,`Play ${s}${r.seconds>0?`, ${se(r.seconds)}`:``}`),h.append(a,d,m),i.append(h);let g=document.createElement(`span`);g.className=`row-play-glyph`,o(g,`play`),i.append(g),c===`remote`&&gt()&&E===null&&!L()&&i.append(Wt(()=>({kind:`track`,index:r.index,name:s}),s)),i.classList.add(`file-row`),i.append(p),e.push(i)}C(a.playlist,...e)}In()}function In(){let e=E?O?.channels.find(e=>e.id===E?.id):void 0;if(e?.playlist&&e.playlist.length>0){let t=e.entry??0;for(let e of Array.from(a.playlist.children)){let n=e,r=Number(n.dataset.index),i=Number.isInteger(r)&&r===t;n.classList.toggle(`selected`,i),n.classList.toggle(`playing`,!1),i?n.setAttribute(`aria-current`,`true`):n.removeAttribute(`aria-current`)}return}let t=I(),n=on();for(let e of Array.from(a.playlist.children)){let r=e,i=Number(r.dataset.index),a=Number.isInteger(i)&&i===t;r.classList.toggle(`selected`,a),r.classList.toggle(`playing`,a&&n),a?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}}function Ln(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!==``&&!a.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`,r=>{r.stopPropagation(),go(t,n,()=>Rn(e),()=>Fn())}),t.append(n)}return t}async function Rn(e){try{let t=await fetch(P.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();return H(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`),t.ok}catch{return H(`could not reach the server`),!1}}function zn(){let e=a.canvas,t=Math.min(2,globalThis.devicePixelRatio||1),n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);n>0&&r>0&&(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);if(Gt())lt=tt(lt,j);else{let e=N.read();e.length>0&&(ft.length!==25&&(ft=Qe(24,e.length)),j=et(j,$e(e,ft)),lt=tt(lt,j))}if(i){let t=getComputedStyle(document.documentElement);nt(i,{width:e.width,height:e.height},j,lt,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(on()||N.jinglePlaying){a.glyphs.textContent=j.map(Cn).join(``);let[e,t]=Gt()?x.levels:N.levels();a.levels.textContent=Sn(e,t)}if(on()){a.elapsed.textContent=se(an());let e=rn();!fe&&e>0&&(a.seek.value=String(Math.round(an()/e*1e3)))}requestAnimationFrame(zn)}let Bn=``;function Vn(){if(c!==`remote`){a.wayInHere.hidden=!0,Bn=``;return}let e=pt()&&!ee,t=ae||P.address,n=e?null:re(P.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Bn)return;Bn=r;let[i,o]=ie({name:l||`this server`,view:t,admin:n});i.hidden=!e,o.hidden=e,a.wayInHere.replaceChildren(i,o),a.wayInHere.hidden=!1}function Hn(e){a.video.hidden=!e,a.fullscreen.hidden=!e,je(),k=null,A=null}function Un(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=E?ve(O?.channels.find(e=>e.id===E?.id)?.art??E.art):``,t=JSON.stringify([en(),tn(),e]);t!==we&&(we=t,navigator.mediaSession.metadata=new MediaMetadata({title:en(),album:tn(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void yn()),navigator.mediaSession.setActionHandler(`pause`,()=>void yn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void bn(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void bn(-1)))}document.addEventListener(`click`,()=>{N.resumeAfterInteraction().catch(()=>{})}),a.filter.addEventListener(`input`,()=>{Dn=0,En=``,Fn()}),a.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())}),a.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(ge=null,hn(n))}),a.fullscreen.addEventListener(`click`,()=>{let e=a.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),a.prev.addEventListener(`click`,()=>void bn(-1)),a.next.addEventListener(`click`,()=>void bn(1)),a.stop.addEventListener(`click`,()=>void xn()),a.playPause.addEventListener(`click`,()=>void yn());async function Wn(e){let t=yt(e,vt());if(!t){if(!gt()){w=c===`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.`,B();return}await Jn(e);return}if(E=null,N.stop(),t.kind===`embed`){D={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},Hn(!1),a.embedFrame.src=t.src,a.embed.hidden=!1,k={url:e,label:t.label,kind:`embed`},w=`Playing ${t.label} here, in this browser.`,B();return}if(t.kind===`list`){await Gn(e,t.label);return}D={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await Ce(()=>N.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),Hn(t.video),k={url:e,label:t.label,kind:`direct`},w=`Playing ${t.label} here, in this browser.`,B()}async function Gn(e,t){w=`Reading ${t}…`,B();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){w=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,B();return}let r=_t(n,e);if(r.entries.length===0){w=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,B();return}A={url:e,title:r.title||t,entries:r.entries,at:0},await Kn()}async function Kn(){let e=A,t=e?.entries[e.at];if(!e||!t)return;let n=ht(t.url);D={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await Ce(()=>N.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),A!==null&&(Hn(n),k={url:e.url,label:e.title,kind:`direct`},A=e,w=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,B())}function qn(){let e=A;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Kn(),!0)}async function Jn(e){if(c!==`remote`){w=`Pick a server to go live on, or connect to one, to put a link on the air.`,B();return}w=`Asking ${l||`the server`} to fetch ${e}…`,B(),await Ce(async()=>{let t,n={};try{t=await fetch(P.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{w=`could not reach the server`;return}if(!t.ok||!n.channel){w=n.error??`that link would not play.`;return}try{await fetch(P.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await lo({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&&(w=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),B()}a.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.linkUrl.value.trim();t!==``&&Wn(t)});function Yn(){let e=c===`remote`?P.address:``,t=u.filter(t=>v(t.url)!==v(e)),n=JSON.stringify({here:e,name:l,carries:m,others:t});if(n===d||document.activeElement===a.linkServer)return;d=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${l||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)}a.linkServer.replaceChildren(...r),a.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,a.linkServer.hidden=t.length===0}function Xn(){let e=c===`remote`?v(P.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!u.some(t=>v(t.url)===e)){let n=document.createElement(`option`);n.value=P.address,n.textContent=l||e,t.push(n)}for(let e of u){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}a.remoteServer.replaceChildren(...t);let r=u.find(t=>v(t.url)===e);a.remoteServer.value=r?.url??``}async function Zn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;u=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Yn(),Xn()}catch{}}async function Qn(){let e=a.linkUrl.value.trim()||k?.url||``;if(e===``){w=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,B();return}let t=a.linkServer.value;if(t!==``&&(c!==`remote`||v(t)!==v(P.address))){let n=u.find(e=>e.url===t)?.name??t;h=e,w=`Connecting to ${n} to go live with it…`,B(),$n(t);return}if(c!==`remote`){w=u.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.`,B();return}if(!m){w=`${l||`This server`} has no ffmpeg, so it cannot carry a link.`+(u.length>0?` Pick a server to go live on, beside the link.`:``),B();return}if(!gt()){w=`Sign in to nixamp.com to go live here, or use the server's control link.`,B();return}await Jn(e)}function $n(e){let t=a.linkUrl.value.trim();ee=!0,y=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit(),a.linkUrl.value=t}a.linkGoLive.addEventListener(`click`,()=>{Qn()}),a.linkServer.addEventListener(`change`,()=>{let e=a.linkServer.value;e!==``&&$n(e)}),a.downloadNow.addEventListener(`click`,()=>{let e=D?.link;if(!e||c!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(P.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),w=`Fetching it through the server; your browser will save it when it arrives.`,B()}),a.goLiveNow.addEventListener(`click`,()=>{let e=St();e&&Ct(e,a.goLiveNow)}),a.seek.addEventListener(`input`,()=>{fe=!0}),a.seek.addEventListener(`change`,()=>{let e=rn();e>0&&N.seek(Number(a.seek.value)/1e3*e),fe=!1}),a.volume.addEventListener(`input`,()=>{let e=Number(a.volume.value)/100;N.volume=e,a.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),a.volumeToggle.textContent=e===0?`🔇`:`🔊`,_(a.volumeToggle,`aria-label`,()=>p(e===0?`Unmute`:`Mute`));try{localStorage.setItem(dn,String(e))}catch{}}),a.volumeToggle.addEventListener(`click`,()=>{let e=Number(a.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(dn));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}a.volume.value=e?String(t):`0`,a.volume.dispatchEvent(new Event(`input`))}),a.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let er=e=>{e.addEventListener(`change`,()=>{let t=Te(Array.from(e.files??[]));if(t.length===0){w=`Nothing playable in that selection.`,B();return}Oe(b),b=t,le=0,c=`local`,P.close(),io(!1),w=``,hn(0)})};er(a.files),er(a.folder),a.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.remoteUrl.value,{base:n,key:r}=Le(t);if(n===``){w=`That is not an address.`,B();return}(async()=>{ue=`connecting`,B();let e=Ye(n);if(e){ue=`error`,S=e,w=e,h=``,c=`local`,B();return}if(await Je(n,void 0,r)===null){ue=`error`;let e=Ke(n);S=e?`needs the server's name`:`not answering`,w=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,h=``,c=`local`,B();return}let i=await qe(n,r);if(i){ue=`error`,S=i,w=i,h=``,c=`local`,B();return}c=`remote`,w=``;try{localStorage.setItem(ln,t.trim())}catch{}P.connect(t),io(!0),ea(),fr(),eo(),B()})()}),a.remoteServer.addEventListener(`change`,()=>{let e=a.remoteServer.value;e!==``&&(ee=!1,y=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit())});let tr=``,nr=null,rr=async(e=!1)=>{a.directory.hidden=!1,e||(a.directoryNote.textContent=`Looking for live streams…`,C(a.directoryList)),nr||=setInterval(()=>{!a.directory.hidden&&document.visibilityState===`visible`&&rr(!0)},pn);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??[],u=t.map(e=>({name:e.name,url:e.url})),Yn();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:K});if(e&&i===tr)return;tr=i,hr(r.recent??[])}catch{e||(a.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(C(a.directoryList),t.length===0){a.directoryNote.textContent=`Nobody is streaming right now.`;return}a.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 s=[`${e.tracks.toLocaleString(f.language)} files to browse`];e.playing!==!1&&e.nowPlaying?s.push(`playing ${e.nowPlaying}`):s.push(`player idle`),e.code&&s.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=s.join(` · `),i.title=i.textContent,n.append(r,i);let c=e.admin??re(e.url),l=(t,n=``)=>{ee=t,y=n,a.remoteUrl.value=t?e.url:c??e.url,a.directory.hidden=!0,document.body.classList.remove(`route-directory`),a.remoteForm.requestSubmit()},u=document.createElement(`ul`);u.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 s=e.lineup?.find(e=>e.name===t);if(s?.art&&/^https?:\/\//i.test(s.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=s.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}s?.about&&(r.title=s.about);let d=document.createElement(`button`);d.type=`button`,d.className=`icon`,o(d,`party`),d.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),d.title=`Join live: ${t} on ${e.name}`,d.addEventListener(`click`,()=>l(!0,`channel:${t}`));let f=document.createElement(`button`);f.type=`button`,f.className=`icon`,o(f,`link`),f.setAttribute(`aria-label`,`Copy live room link for ${t}`),f.title=`Copy a nixamp link to this live room`;let p=`${globalThis.location.origin}/?url=${encodeURIComponent(e.url)}&play=${encodeURIComponent(`channel:${s?.id??t}`)}`;f.addEventListener(`click`,e=>{e.stopPropagation(),_o(p,f,`✓`)});let m=document.createElement(`button`);m.type=`button`,m.className=`icon`,o(m,`copy`),m.setAttribute(`aria-label`,`Copy raw stream URL for ${t}`),m.title=`Copy the raw stream URL for VLC or another player`;let h=e.url;try{let n=new URL(e.url);n.pathname=`/api/channels/${encodeURIComponent(s?.id??t)}`,h=n.toString()}catch{}if(m.addEventListener(`click`,e=>{e.stopPropagation(),_o(h,m,`✓`)}),n.append(r,d,f,m),s?.startedBy&&K&&s.startedBy===K&&c){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,o(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),l(!1,`channel:${s?.id??t}`)}),n.append(e)}u.append(n)}let[d,p]=ie({name:e.name,view:e.url,admin:c},()=>{a.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(n,d,p),K&&t.append(Ar(e.url,e.name)),e.ownerId&&K&&e.ownerId!==K&&t.append(ma(e.ownerId,e.name)),u.childElementCount>0&&t.append(u),e.ownerId&&K&&e.ownerId===K){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(()=>({}));a.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{a.directoryNote.textContent=`could not reach the directory`}finally{await rr()}})()}),t.append(n)}a.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!a.directory.hidden&&rr(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),rr()}let ir=null,ar=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,or=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,sr=``,cr=``,lr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===sr)return;sr=t,a.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)}a.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,``],[ar(t.network),`network-${t.network}`],[or(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)}a.adminConnections.append(e)}};function H(e){a.adminSaid.textContent=e,a.adminSaid.hidden=e===``}let ur=async()=>{try{let e=await fetch(P.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;a.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,lr(t.connections??[]),dr(t.publish??[],(t.channels??[]).map(e=>e.id)),Co(t.home??``,t.root??``),$()}catch{a.adminNote.textContent=`lost touch with the server`}};function dr(e,t){a.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===cr)return;if(cr=n,e.length===0){C(a.publishList);return}let r=e.length-t.length;a.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,C(a.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`,g(o,()=>p(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let fr=async()=>{if(c!==`remote`){a.adminPanel.hidden=!0,a.publishPanel.hidden=!0,ir&&clearInterval(ir),ir=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(P.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(ee&&(e=!1),mt=i&&!e,a.adminPanel.hidden=!e,$a(e),h!==``){let e=h;h=``,gt()?Jn(e):(w=`Sign in to nixamp.com to go live here.`,B())}if(ir&&clearInterval(ir),ir=null,$(),ea(),eo(),a.listenOnly.hidden=e,!e){a.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}a.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,ur(),ir=setInterval(()=>void ur(),2e3)};function pr(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)}`;H(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(P.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}:{}})}),o=await i.json();if(!i.ok){H(o.error??`that did not work`);return}H(`${o.channel?.name||t||e} is on the air.`),a.adminSource.value=``,a.adminName.value=``,eo(),$()}catch{H(`could not reach the server`)}})()}a.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=a.adminSource.value.trim();t&&pr(t,a.adminName.value.trim())}),a.adminAdd.addEventListener(`click`,()=>{let e=a.adminSource.value.trim();if(!e)return;H(`Reading ${e}…`);let t=a.adminReplace.checked,n=a.adminName.value.trim();(async()=>{try{let r=await fetch(P.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();H(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&&(a.adminSource.value=``,a.adminName.value=``,eo(),$())}catch{H(`could not reach the server`)}})()});let mr=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`},hr=e=>{let t=[],n=K?e.filter(e=>e.ownerId&&e.ownerId!==K):[];if(a.recentNote.hidden=n.length===0,n.length===0){C(a.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 ${mr(e.endedAt)}`:`ended ${mr(e.endedAt)}`,r.append(i,a),n.append(r,ma(e.ownerId,e.name)),t.push(n)}C(a.recentList,...t)},gr=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 _r(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?`▶ ${gr(e.party.positionNow)}`:`❚❚ ${gr(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`);o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.className=`party-row`,n.className=`party-name`,n.title=i.textContent,i.hidden=!0;let s=document.createElement(`details`);s.className=`party-actions`;let c=document.createElement(`summary`);return c.textContent=`⋯`,_(c,`aria-label`,()=>`${p(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let vr=[],yr=[],br=!1,xr=null,Sr=``;function Cr(){let e=new Map,t=(t,n,r)=>{if(!r.length)return;let i=e.get(t);if(i){let e=new Set(i.rows.map(e=>e.dataset.liveKey));i.rows.push(...r.filter(t=>!e.has(t.dataset.liveKey)))}else e.set(t,{name:n,rows:r})},n=c===`remote`&&O?v(P.address):``;for(let e of vr){let r=v(e.url);if(!r||r===n)continue;let i=[],o=(t,n)=>{let o=document.createElement(`li`);o.dataset.liveKey=`${r}:${t}`,o.className=`party-row`;let s=document.createElement(`span`);s.className=`party-name`,s.textContent=n,s.title=n;let c=document.createElement(`button`);c.type=`button`,wt(c),_(c,`aria-label`,()=>`${p(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{ee=!0,y=t,a.remoteUrl.value=e.url,a.remoteForm.requestSubmit()}),o.append(s,c),i.push(o)};e.playing!==!1&&e.nowPlaying&&o(`live`,me(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);o(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&O&&t(n,O.server.name||l||n,oo(O));for(let e of yr){let n=e.party.origin;try{n=new URL(e.links.partyUrl||e.party.partyUrl).origin}catch{}let r=e.party.origin;try{r=new URL(n).hostname}catch{}let i=_r(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...a.partiesList.children].map(e=>[e.dataset.liveKey,e])),i=[];for(let[t,n]of e){let e=r.get(t);if(!e){e=document.createElement(`li`),e.dataset.liveKey=t,e.className=`party-server`;let n=document.createElement(`h3`),r=document.createElement(`ul`);r.className=`party-rows`,e.append(n,r)}let a=e.querySelector(`h3`);a.textContent!==n.name&&(a.textContent=n.name),pe(e.querySelector(`ul`),n.rows),i.push(e)}pe(a.partiesList,i),a.partiesNote.hidden=e.size>0,e.size||g(a.partiesNote,()=>p(br?`No parties live right now.`:`Loading…`))}async function wr(){if(e||(Sr!==K&&(xr?.abort(),xr=null,yr=[],Sr=K,Cr()),xr))return;let t=new AbortController;xr=t;let n=K,r=setTimeout(()=>t.abort(),8e3),i=async e=>{let n=await fetch(e,{signal:t.signal,cache:`no-store`});return{ok:n.ok,status:n.status,body:n.ok?await n.json():null}};try{let[e,r]=await Promise.allSettled([i(`/api/directory`),n?i(`/api/v1/watch-parties`):Promise.resolve(null)]);if(xr!==t||n!==K||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(vr=e.value.body.streams??[],br=!0,a.directory.dataset.available=String(vr.length>0),Za()),r.status===`fulfilled`&&r.value&&(r.value.ok?(yr=r.value.body.parties??[],br=!0):[401,403].includes(r.value.status)&&(yr=[])),Cr(),!br&&!O&&g(a.partiesNote,()=>p(`Could not refresh parties.`))}finally{clearTimeout(r),xr===t&&(xr=null)}}a.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){w=n.error??`No party found with that invite code.`,B();return}a.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{w=`Could not look up that party. Try again.`,B()}})()});async function Tr(){if(!K){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];a.connectionsNote.hidden=t.length===0,a.connectionsList.hidden=t.length===0,C(a.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`,g(a,()=>p(`Disconnect`)),a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Tr()})()}),t.append(n,a),t}))}catch{a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0}}let Er=new Set,U=e=>{try{return new URL(e).origin}catch{return e}},Dr=e=>[...Er].some(t=>U(t)===U(e));async function Or(){if(!K){Er=new Set,a.favoritesPanel.hidden=!0,jr();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){a.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];Er=new Set(t.map(e=>e.url)),a.favoritesPanel.hidden=t.length===0,a.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,C(a.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,...ie({name:e.name||e.url,view:e.url,admin:re(e.url)}),Ar(e.url,e.name)),t}))}catch{a.favoritesPanel.hidden=!0}jr()}async function kr(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){w=n?`Could not save that favourite.`:`Could not remove that favourite.`,B();return}}catch{w=`could not reach nixamp.com`,B();return}if(n)Er.add(e);else for(let t of[...Er])U(t)===U(e)&&Er.delete(t);await Or()}function Ar(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Dr(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=>U(t)===U(e))??e;kr(Dr(e)?i:e,t,!Dr(e)).then(r)}),n}function jr(){let e=c===`remote`?P.shareLink:``;if(a.favHere.hidden=!(K&&e),a.favHere.hidden)return;let t=Dr(e);a.favHere.textContent=t?`♥`:`♡`,a.favHere.dataset.on=t?`yes`:`no`,a.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,a.favHere.setAttribute(`aria-label`,a.favHere.title)}o(a.copyNow,`copy`),a.copyNow.addEventListener(`click`,()=>{_o(N.source,a.copyNow,`✓`)});function Mr(e){if(e===``||e===at)return;at=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),g(n,()=>r.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}));let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),a.logList.prepend(t);a.logList.children.length>100;)a.logList.lastElementChild?.remove()}let Nr=3e3,W=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,Pr=``,Fr=``,Ir=null,Lr=!1,Rr=new Set,zr=``,Br=null,Vr=!1,Hr=Ht(e=>localStorage.getItem(e)),G=Lt(e=>localStorage.getItem(e)),Ur=new Set,Wr=new Set,Gr=null,Kr=``,qr=``,K=``,Jr=(()=>{try{let e=sessionStorage.getItem(`nixamp.translationSession`);if(e&&/^listener-[a-f0-9-]{36}$/.test(e))return e;let t=`listener-${crypto.randomUUID()}`;return sessionStorage.setItem(`nixamp.translationSession`,t),t}catch{return`listener-${crypto.randomUUID()}`}})(),Yr=null,q=!1,Xr=``,Zr=!1,Qr=!1,$r=``,ei=0,ti=!1,ni=!1;try{a.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let ri=new Yt(()=>{ni=!0,ti&&(a.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),ii=()=>{let e=Number(a.transcriptBackgroundLevel.value);ri.setLevel(e/100),a.transcriptBackgroundValue.value=`${e}%`,_(a.transcriptBackgroundLevel,`aria-valuetext`,()=>f.number(e/100,{style:`percent`})),a.transcriptBackgroundLevel.disabled=!a.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(a.transcriptBackgroundLevel.value=e)}catch{}ii(),a.transcriptBackgroundLevel.addEventListener(`input`,()=>{ii();try{localStorage.setItem(`nixamp.backgroundLevel`,a.transcriptBackgroundLevel.value)}catch{}});let J=new Zt({account:()=>W===``?K:``,changed:()=>Li()});z(`translation-buy-tools`).append(J.button()),J.refresh();let ai=new Xt({reconnecting:()=>Y.reset(),line:(e,t)=>{pi=0,mi.push(e),Fi(),Y.push(e,t,0)},status:e=>{a.transcriptAudioNote.textContent=e},failed:e=>{Xr=e,qr=e,q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci(),a.transcriptAudioNote.textContent=`${e} Original audio restored.`,J.refresh()}}),Y=new Kt({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(ai.audio(String(e))):fetch(e,t)),playing:()=>N.playing,volume:()=>N.volume,active:e=>{ti=e,N.translatedAudio(e),ri.active(e&&N.playing&&a.transcriptBackground.checked)},status:e=>{a.transcriptAudioNote.textContent=e+(ni&&ti?` · background unavailable`:``)},failed:()=>{qr=a.transcriptAudioNote.textContent||`Translated audio stopped.`,q=!1,a.transcriptAudio.checked=!1,ci()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!K||W!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!Yr||Yr.channel!==t.channel||Yr.expires<Date.now()+2e4||Yr.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.`);Yr={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return Yr.remaining-=t.text.length,{authorization:`Bearer ${Yr.token}`}}}),oi=new $t({fetcher:(e,t)=>{let n=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&n.set(`x-nixamp-translation-session`,Jr),fetch(e,{...t,headers:n})},language:()=>G,speakers:()=>a.transcriptAudio.checked,voices:()=>Gr?.voices??[],channel:()=>Jr,status:e=>{!Zr&&!q&&(Xr=e),a.transcriptNote.textContent=e},failed:()=>{q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci()},lines:e=>{pi=0,mi.push(...e),Fi(),ui(),a.transcriptAudio.checked&&Y.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:G,channel:Jr,speaker:e.speaker,voice:oi.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),si=new qt(e=>{Zr&&N.playing&&oi.push(e)});function ci(){ei++,Zr=!1,Qr=!1,$r=``,si.stop(),oi.reset(),ai.stop(),ri.stop(),Y.reset(),C(a.transcriptSpeakers)}async function li(){if((Zr||Qr)&&$r===N.mediaKey)return;ci();let e=ei;Qr=!0,$r=N.mediaKey;try{if(!K||W!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=N.audioInput();if(ni=!1,a.transcriptAudio.checked&&a.transcriptBackground.checked&&ri.start(t.context,t.node).then(t=>{t&&e===ei&&ri.active(ti&&N.playing&&a.transcriptBackground.checked)}),a.transcriptAudio.checked&&c===`remote`&&E)await ai.start(zi(),G),J.refresh();else{if(a.transcriptAudio.checked&&await J.startSession(Jr),e!==ei)return;await si.start(t.context,t.node,a.transcriptAudio.checked?2:5)}if(e!==ei)return;Zr=!0,q=!0,pi=0,gi??=setInterval(Fi,250),a.transcriptNote.textContent=a.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==ei)return;q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci(),Xr=t instanceof Error?t.message:`This audio could not be captured.`,a.transcriptNote.textContent=Xr}finally{e===ei&&(Qr=!1)}}function ui(){let e=[...oi.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(a.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id;let n=document.createElement(`span`),r=t.id.split(`-`)[1];g(n,()=>`${p(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,_(i,`aria-label`,()=>`${p(`Speaker voices`)}: ${r}`);for(let e of Gr?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,Y.reset()}),e.append(i),a.transcriptSpeakers.append(e)}a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked;for(let e of a.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[a.audio,a.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(N.showingVideo?a.video:a.audio)&&ci()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(N.showingVideo?a.video:a.audio)&&q&&Hr&&N.playing&&li()});e.addEventListener(`volumechange`,()=>{Y.setVolume()})}let di=``,fi=null,pi=zt(6,!1),mi=[],hi=[],gi=null;function _i(){if(c!==`remote`)return null;let{base:e}=Le(yo());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=E?E.id:D?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function vi(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${W}/api/v1/trollbox?${n.toString()}`}function yi(){let e=_i(),t=e?`${e.server}|${e.channel}`:``;t!==Pr&&(Pr=t,Fr=``,Rr.clear(),a.trollboxList.replaceChildren(),Ir&&clearTimeout(Ir),Ir=null,a.trollboxPanel.hidden=e===null,a.trollboxForm.hidden=!0,Ti(!1),e&&(g(a.trollboxNote,()=>`The room for ${en()||e.channel}. Loading…`),xi()))}function bi(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);g(n,()=>Number.isNaN(r.getTime())?``:r.toLocaleTimeString(f.language,{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,a.dir=`auto`,a.translate=!1,t.append(n,i,a),t}async function xi(){let e=_i(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===Pr&&!Lr){Lr=!0;try{let n=await fetch(vi(e,Fr)),r=await n.json().catch(()=>({}));if(t!==Pr)return;if(!n.ok){a.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!Rr.has(e.id));for(let e of i)Rr.add(e.id),a.trollboxList.append(bi(e)),Fr=e.createdAt;for(;a.trollboxList.children.length>200;)a.trollboxList.firstElementChild?.remove();let o=r.you??``,s=zr!==o;zr=o,s&&(Yr=null,Li()),a.trollboxForm.hidden=o===``,a.trollboxEditLabel.hidden=o===``||!Si,o===``&&Ti(!1),g(a.trollboxNote,()=>o===``?W===``?`The room for ${en()||e.channel}. Sign in to say something.`:`The room for ${en()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${en()||e.channel}.`)}catch{t===Pr&&(a.trollboxNote.textContent=`The trollbox is not answering.`)}finally{Lr=!1,t===Pr&&(Ir=setTimeout(()=>{document.visibilityState===`visible`?xi():Ir=setTimeout(()=>void xi(),Nr)},Nr))}}}a.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=_i(),n=a.trollboxInput.value.trim();t&&n!==``&&(a.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${W}/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){a.trollboxNote.textContent=r.error??`that did not send`;return}a.trollboxInput.value=``,Rr.has(r.message.id)||(Rr.add(r.message.id),a.trollboxList.append(bi(r.message)),Fr=r.message.createdAt)}catch{a.trollboxNote.textContent=`The trollbox is not answering.`}finally{a.trollboxInput.disabled=!1}})())});let Si=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Ci=Si?Mt(e=>MediaRecorder.isTypeSupported(e)):``;a.trollboxMic.hidden=!Si;function wi(e){a.trollboxNote.textContent=e,Mr(e)}function Ti(e){let t=Br;if(!t)return;Br=null,clearTimeout(t.stop),clearInterval(t.tick),a.trollboxMic.setAttribute(`aria-pressed`,`false`),a.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(()=>Di(new Blob(t.chunks,{type:t.recorder.mimeType||Ci||`audio/webm`}),t.startedAt))}async function Ei(){if(Br||Vr||zr===``||!_i())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){wi(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,Ci?{mimeType:Ci}:{})}catch{for(let t of e.getTracks())t.stop();wi(`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();Br={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>Ti(!0),jt),tick:setInterval(()=>{a.trollboxMic.textContent=Nt(r,Date.now())},500)},t.start(250),a.trollboxMic.setAttribute(`aria-pressed`,`true`),a.trollboxMic.textContent=Nt(r,r),wi(`Listening. Tap the mic again when you have said it (${Math.round(jt/1e3)} s at most).`)}async function Di(e,t){let n=_i();if(n&&zr!==``){if(Date.now()-t<400||e.size===0){wi(`That was too short to hear. Tap, say it, then tap again.`);return}Vr=!0,a.trollboxMic.disabled=!0,a.trollboxMic.textContent=`…`,wi(`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),o=i.createBufferSource();o.buffer=r,o.connect(i.destination),o.start();let s=kt((await i.startRendering()).getChannelData(0),At),c=a.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(`${W}/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){wi(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){wi(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=a.trollboxInput.value.trimEnd();a.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),wi(`Heard: “${p}”. Send it, or fix it first.`);return}_i()&&!Rr.has(f.message.id)&&(Rr.add(f.message.id),a.trollboxList.append(bi(f.message)),Fr=f.message.createdAt),wi(`Said: “${f.message.body}”`)}catch{wi(`That recording could not be read here.`)}finally{Vr=!1,a.trollboxMic.disabled=!1,a.trollboxMic.textContent=`🎤`}}}a.trollboxMic.addEventListener(`click`,()=>{Br?Ti(!0):Ei()});try{a.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}a.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,a.trollboxEdit.checked?`on`:`off`)}catch{}wi(a.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Oi(){try{let e=await fetch(`${W}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`Could not read your profile.`;return}a.personaHandle.value=t.chosen?t.handle??``:``,_(a.personaHandle,`placeholder`,()=>t.handle||p(`handle`)),a.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,a.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;a.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${ki(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${ki(t.voice??``)}${n}.`}catch{a.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function ki(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`}a.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.personaHandle.value.trim(),n={voice:a.personaVoice.value,profile:a.personaProfile.value.trim()};t!==``&&(n.handle=t),a.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${W}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`that did not save`;return}await Oi()}catch{a.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&Br&&Ti(!0)});function Ai(){return c===`remote`&&E?{id:E.id,name:E.name,hls:E.video&&vt()}:N.loaded||k?{id:Jr,name:en()||`This audio`,hls:!1}:null}function ji(){ci(),Yr=null,Ur.clear(),Wr.clear(),fi?.close(),fi=null,gi&&clearInterval(gi),gi=null,mi=[],hi=[],a.transcriptList.replaceChildren(),a.subtitle.hidden=!0,a.subtitle.textContent=``}function Mi(){let e=Ai(),t=`${e?.id??``}|${N.mediaKey}|${Hr}|${G}|${a.transcriptAudio.checked}|${q}|${K}`;if(t!==di){if(di=t,ji(),a.transcriptPanel.hidden=!1,a.transcriptOn.checked=Hr&&(!!E||q||a.transcriptAudio.checked),a.transcriptLanguage.options.length===0)for(let e of It){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),g(t,()=>e.code?e.label:p(`Original (auto-detect)`)),a.transcriptLanguage.append(t)}if(a.transcriptLanguage.value=G,Li(),Ri(),!e){a.transcriptNote.textContent=`Play something to see its captions.`;return}if(!Hr){a.transcriptNote.textContent=`Captions are off.`;return}if(Xr){a.transcriptNote.textContent=Xr;return}a.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,a.transcriptAudio.checked||q?N.playing?li():a.transcriptNote.textContent=`Press Play to start listening.`:c===`remote`&&E?Ni(e,t):a.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Ni(e,t){let n=6,r=G?`?language=${encodeURIComponent(G)}`:``;try{let i=await fetch(P.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),o=await i.json().catch(()=>({}));if(t!==di)return;if(!i.ok){a.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){K&&W===``?(q=!0,Mi()):a.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=o.backlog??n}catch{t===di&&(a.transcriptNote.textContent=`The server did not answer about captions.`);return}pi=zt(n,e.hls);let i=new EventSource(P.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));fi=i;let o=(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}`;Ur.has(e)||(Ur.add(e),Ur.size>600&&Ur.delete(Ur.values().next().value),mi.push(n),t&&a.transcriptAudio.checked&&Wr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==di)return;let i=JSON.parse(r.data);pi=zt(i.backlog??n,e.hls),o(i.lines??[]);let s=It.find(e=>e.code===i.language)?.label??i.language,c=It.find(e=>e.code===G)?.label??G;if(a.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:G?`${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=`${W||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,a.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==di)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=It.find(e=>e.code===i)?.label??i,c=It.find(e=>e.code===G)?.label??G;a.transcriptNote.textContent=G?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===di&&i.readyState===EventSource.CLOSED&&(a.transcriptNote.textContent=`Captions stopped; the server went away.`)}),gi=setInterval(Fi,250)}function Pi(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),g(n,()=>Ut(e.at));let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text,r.dir=`auto`,r.translate=!1,(e.language||e.sourceLanguage)&&(r.lang=e.language||e.sourceLanguage);let i=Rt(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 Fi(){let e=Date.now(),{ready:t,still:n}=Bt(mi,e,pi);mi=n;for(let e of t)if(hi.push(e),a.transcriptList.append(Pi(e)),Wr.delete(e)&&a.transcriptAudio.checked&&G){let t=new URLSearchParams({at:String(e.at),language:G,voice:`auto`});Y.push(e,P.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),pi)}for(;hi.length>200;)hi.shift();for(;a.transcriptList.children.length>200;)a.transcriptList.firstElementChild?.remove();let r=Vt(hi,e,pi),i=a.transcriptList.children,o=r?hi.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===o);let s=N.playing&&r!==null&&!a.video.hidden&&a.video.offsetHeight>0;a.subtitle.hidden=!s,s&&r&&(a.subtitle.textContent!==r.text&&(a.subtitle.textContent=r.text),a.subtitle.style.top=`${a.video.offsetTop+a.video.offsetHeight-a.subtitle.offsetHeight-10}px`)}a.transcriptOn.addEventListener(`change`,()=>{Hr=a.transcriptOn.checked,q=Hr&&(!E||a.transcriptAudio.checked),Hr||(a.transcriptAudio.checked=!1,Y.disable());try{localStorage.setItem(Pt,Hr?`on`:`off`)}catch{}Mi()}),a.transcriptLanguage.addEventListener(`change`,()=>{Xr=``,qr=``,G=Lt(()=>a.transcriptLanguage.value),!G&&a.transcriptAudio.checked&&(a.transcriptAudio.checked=!1,q=!1,Y.disable());try{G?localStorage.setItem(Ft,G):localStorage.removeItem(Ft)}catch{}Mi()});function Ii(){if(G)return G;let e=navigator.language.split(`-`)[0]||`en`;return It.some(t=>t.code===e)&&Gr?.languages.includes(e)?e:`en`}function Li(){let e=K!==``&&W===``,t=e&&J.loaded()&&!!Ai()&&!!Gr?.languages.includes(Ii());a.transcriptAudio.disabled=!t,a.transcriptVoiceSettings.contains(document.activeElement)||(a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked),t?a.transcriptAudio.checked||g(a.transcriptAudioNote,()=>qr||p(`Original audio.`)):(a.transcriptAudio.checked=!1,Y.disable(),a.transcriptAudioNote.textContent=e?Ai()?J.loaded()?qr||(Gr?`Audio translation is unavailable for this language.`:`Loading voices…`):J.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function Ri(){if(!K||W!==``)return;let e=`/api/v1/speech/voices`;if(Kr!==e){Kr=e,Gr=null,qr=``,Li();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(Kr!==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.`);Gr=n}catch(t){if(Kr!==e)return;qr=t instanceof Error?t.message:`Translated audio is unavailable.`}Li()}}a.transcriptBackground.addEventListener(`change`,()=>{ii();try{localStorage.setItem(`nixamp.backgroundSound`,a.transcriptBackground.checked?`on`:`off`)}catch{}if(ri.stop(),ni=!1,a.transcriptBackground.checked&&a.transcriptAudio.checked&&N.playing){let e=ei,t=N.audioInput();ri.start(t.context,t.node).then(t=>{t&&e===ei&&ri.active(ti&&N.playing&&a.transcriptBackground.checked)})}}),a.transcriptAudio.addEventListener(`change`,()=>{if(Xr=``,qr=``,Wr.clear(),a.transcriptAudio.checked&&!J.ready()){a.transcriptAudio.checked=!1,J.open(a.transcriptAudio);return}if(a.transcriptAudio.checked){G=Ii();try{localStorage.setItem(Ft,G)}catch{}Hr=!0,q=!0,Y.enable()}else q=!1,Y.disable();Mi()});function zi(){if(k)return k.url;if(c!==`remote`)return``;let{base:e,key:t}=Le(yo());if(e===``)return``;if(E)return Fe(e,`/api/channels/${encodeURIComponent(E.id)}`,t);if(D?.kind===`live`)return Fe(e,`/api/live`,t);if(N.source===``)return``;try{let n=new URL(N.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function Bi(){let e=zi();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function Vi(){return c===`remote`?E?vo(`channel:${E.id}`):D?.kind===`live`||L()?vo(`live`):``:``}a.shareNow.addEventListener(`click`,()=>{let e=Bi();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${R()} on nixamp`,url:e}).catch(()=>void 0);return}_o(e,a.shareNow,`Copied`)}),a.copyNixamp.addEventListener(`click`,()=>{let e=Vi();e!==``&&_o(e,a.copyNixamp,`✓`)}),a.favHere.addEventListener(`click`,()=>{let e=yo()||P.shareLink;if(!e)return;let t=[...Er].find(t=>U(t)===U(e))??e;kr(Dr(e)?t:e,l||P.address,!Dr(e)).then(jr)});let Hi=n?i:200,Ui=[],X=null,Z=null,Wi=``,Gi=[],Ki=0,qi=null,Ji=0,Yi=null,Xi=null,Zi=new Map;function Qi(e,t){Ji++,Yi?.abort(),qi&&clearTimeout(qi),qi=null,de(a.catalogsList),de(a.catalogsEntries),X=e,Z=t,Wi=``,a.catalogsFilter.value=``,Gi=[],Ki=0,a.catalogsEntries.setAttribute(`aria-busy`,`false`),na(),e&&t!==null&&sa(0)}function $i(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`}function ea(){let e=P.url(`/api/catalogs`);if(Xi?.url===e)return Xi.promise;let t=ta(e).finally(()=>{Xi?.promise===t&&(Xi=null)});return Xi={url:e,promise:t},t}async function ta(e){if(c!==`remote`){a.catalogsPanel.hidden=!0;return}let t;try{t=await fetch(e)}catch{e===P.url(`/api/catalogs`)&&(a.catalogsPanel.hidden=!0);return}if(c===`remote`&&e===P.url(`/api/catalogs`)){if(!t.ok){a.catalogsPanel.hidden=!0;return}Ui=(await t.json().catch(()=>({}))).catalogs??[],X&&=Ui.find(e=>e.id===X?.id)??null,X||(Z=null),a.catalogsPanel.hidden=!1,na()}}function na(){let e=!a.adminPanel.hidden;a.catalogsForm.hidden=!e;let t=Ui.reduce((e,t)=>e+t.live,0),n=Ui.reduce((e,t)=>e+t.vod,0);a.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`,ra();let r=X!==null&&Z!==null;if(a.catalogsList.hidden=r,a.catalogsFilter.hidden=!r,a.catalogsEntries.hidden=!r,r){ca();return}if(X){aa(X);return}C(a.catalogsList,...Ui.map(t=>ia(t,e)))}function ra(){let e=X!==null;if(a.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`,()=>Qi(null,null),!1),n(),t(X?.name??``,()=>Qi(X,null),Z===null)];Z!==null&&r.push(n(),t(Z===``?`All groups`:Z,()=>void 0,!0)),a.catalogsCrumbs.replaceChildren(...r)}function ia(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`,g(a,()=>[`${e.entries.toLocaleString(f.language)} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString(f.language)} live`,`${e.vod.toLocaleString(f.language)} on demand`,`refreshed ${$i(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.setAttribute(`aria-label`,`Browse ${e.name}`),o.addEventListener(`click`,()=>{Qi(e,null)}),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`,()=>{ua(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,g(r,()=>p(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&go(n,r,()=>da(e),()=>void ea())}),n.append(t,r)}return n}async function aa(e){let t=P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),n=`${t}:${e.refreshedAt}:${e.entries}`,r;a.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=Zi.get(n);e||(Zi.size>=20&&Zi.delete(Zi.keys().next().value),e=fetch(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),Zi.set(n,e)),r=await e}catch{if(Zi.delete(n),X?.id!==e.id||Z!==null||t!==P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`),w=`Could not read the groups in ${e.name}.`,B();return}if(X?.id!==e.id||Z!==null||t!==P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`);let i=[oa(`All groups`,``,e.entries,e.live,e.vod),...r.map(e=>oa(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];C(a.catalogsList,...i)}function oa(e,t,n,r,i){let a=document.createElement(`li`),o=document.createElement(`span`);o.className=`server-label`;let s=document.createElement(`span`);s.className=`name`,s.textContent=e;let c=document.createElement(`span`);c.className=`detail`,g(c,()=>`${n.toLocaleString(f.language)} · ${r.toLocaleString(f.language)} live · ${i.toLocaleString(f.language)} on demand`),o.append(s,c);let l=document.createElement(`button`);return l.type=`button`,l.className=`button`,l.textContent=`Open`,l.setAttribute(`aria-label`,`Open ${e}`),l.addEventListener(`click`,()=>{Qi(X,t)}),a.append(o,l),a}async function sa(e){let t=X,n=Z;if(!t||n===null)return;let r=++Ji;Yi?.abort();let i=new AbortController;Yi=i;let o=P.url(`/api/catalogs`);a.catalogsEntries.setAttribute(`aria-busy`,`true`);let s=new URLSearchParams({group:n,q:Wi,offset:String(e),limit:String(Hi)}),c;try{let e=await fetch(P.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${s}`),{signal:i.signal});if(!e.ok)throw Error(String(e.status));c=await e.json()}catch{if(i.signal.aborted||r!==Ji)return;a.catalogsEntries.setAttribute(`aria-busy`,`false`),w=`Could not read ${t.name}.`,ca(),B();return}r===Ji&&X?.id===t.id&&Z===n&&o===P.url(`/api/catalogs`)&&(a.catalogsEntries.setAttribute(`aria-busy`,`false`),Ki=c.total??0,Gi=e===0?c.entries??[]:[...Gi,...c.entries??[]],ca())}function ca(){let e=X;if(!e)return;let t=Gi.map(t=>{let n=document.createElement(`li`);n.className=`row`;let r=document.createElement(`span`);r.className=`name`,r.textContent=t.title;let i=document.createElement(`span`);i.className=t.live?`catalog-tag catalog-live`:`catalog-tag`,i.textContent=t.live?`LIVE`:t.duration>0?se(t.duration):`VOD`;let a=document.createElement(`button`);if(a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Play ${t.title}`),a.append(r,i),n.append(a),a.addEventListener(`click`,()=>{la(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,o(r,`copy`),r.title=`Copy this entry's URL`,r.setAttribute(`aria-label`,`Copy the URL of ${t.title}`),r.addEventListener(`click`,n=>{n.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/stream`;_o(P.url(i),r,`✓`)}),n.append(r)}return gt()&&n.append(Wt(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(Gi.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=Wi?`Nothing called "${Wi}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(Gi.length<Ki){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,g(n,()=>`Show more (${Gi.length.toLocaleString(f.language)} of ${Ki.toLocaleString(f.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),de(a.catalogsEntries,!1),n.disabled=!0,sa(Gi.length)}),e.append(n),t.push(e)}C(a.catalogsEntries,...t)}async function la(e,t,n){n?.classList.add(`loading`),w=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await Ce(async()=>{let n,i={};try{n=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{w=`could not reach the server`;return}if(!n.ok){w=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await lo({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){E=null,T=-1,D={kind:`vod`,...r},Be(a,`title`),await N.load({title:a,artist:``,album:``,duration:0,url:P.url(i.url),video:!0,objectUrl:!1},!0),Hn(!0),w=`Playing ${a}.`;return}w=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),B()}}async function ua(e){H(`Reading ${e.name} again…`);try{let t=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));H(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString(f.language)} entries.`:n.error??`that did not work`)}catch{H(`could not reach the server`)}ea()}async function da(e){try{let t=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(H(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return H(`could not reach the server`),!1}return X?.id===e.id&&(X=null,Z=null),!0}a.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.catalogSource.value.trim(),n=a.catalogName.value.trim();t&&(async()=>{H(`Reading ${n||t}…`);try{let e=await fetch(P.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){H(r.error??`that did not work`);return}H(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString(f.language)} entries.`),a.catalogSource.value=``,a.catalogName.value=``}catch{H(`could not reach the server`)}ea()})()}),a.catalogsFilter.addEventListener(`input`,()=>{Ji++,Yi?.abort(),qi&&clearTimeout(qi),qi=setTimeout(()=>{qi=null,Wi=a.catalogsFilter.value.trim(),sa(0)},250)});let fa=async()=>{C(a.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){a.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ne=new Map(t.map(e=>[U(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),a.serversPanel.hidden=!1,a.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 o=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=ie({name:e.name,view:o,admin:o});Je(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=ka()===U(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`,()=>{Aa(l?``:U(e.url)),fa()});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 fa()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),a.serversList.append(t)}}catch{a.serversPanel.hidden=!0}},pa=async()=>{C(a.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){a.followingNote.hidden=!0;return}let t=(await e.json()).following??[];a.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 o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,g(o,()=>p(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),a.followingList.children.length===0&&(a.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(n,o),a.followingList.append(t)}}catch{a.followingNote.hidden=!0}},ma=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,g(n,()=>p(`Follow`)),n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{g(n,()=>e?`Following`:p(`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),pa())}catch{}finally{n.disabled=!1}})()}),n},ha=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},ga=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,_a=async()=>{if(!ga())return a.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return a.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return a.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 a.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:ha(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 a.notifyNote.textContent=`This device will be told.`,!0}catch{return a.notifyNote.textContent=`Could not set this device up.`,!1}},va=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{}},ya=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();a.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(a.notifyPhone.value=n.phone)}catch{a.notifyPhoneNote.textContent=`could not reach nixamp.com`}},ba=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();a.notifyEmail.checked=t.wantsEmail!==!1,a.notifySms.checked=t.wantsSms===!0,a.notifyPhone.value=t.phone??``;let n=ga()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;a.notifyWeb.checked=t.wantsWeb!==!1&&n,a.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};a.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(a.notifyWeb.checked){let e=await _a();a.notifyWeb.checked=e,await ya({wantsWeb:e});return}await va(),await ya({wantsWeb:!1}),a.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),a.notifyEmail.addEventListener(`change`,()=>{ya({wantsEmail:a.notifyEmail.checked})}),a.notifySms.addEventListener(`change`,()=>{(async()=>{if(a.notifySms.checked&&!a.notifyPhone.value.trim()){a.notifyPhoneNote.textContent=`Add a phone number first.`,a.notifySms.checked=!1;return}await ya({wantsSms:a.notifySms.checked})})()}),a.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),ya({phone:a.notifyPhone.value.trim()})});let xa=!1,Sa=!1,Ca=`nixamp.welcome`,wa=()=>{let e=!1;try{e=localStorage.getItem(Ca)===`hidden`}catch{}a.welcome.hidden=!Sa||K!==``||e},Ta=e=>{let t=e!==null;J.refresh(),Kr=``,Yr=null,t||(q=!1,a.transcriptAudio.checked=!1,Y.disable(),ci()),Mi(),a.notifyPanel.hidden=!t,t?(ba(),pa(),fa()):(a.serversPanel.hidden=!0,a.followingNote.hidden=!0,C(a.followingList),a.recentNote.hidden=!0,a.recentList.replaceChildren()),a.accountForm.hidden=t,a.accountProviders.hidden=t||a.accountProviders.childElementCount===0,a.accountSignOut.hidden=!t,a.personaForm.hidden=!t,a.personaNote.hidden=!t,t&&Oi(),a.accountNote.textContent=t?`Signed in as ${e}.`:xa?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,g(a.accountSubmit,()=>p(xa?`Create account`:`Sign in`)),g(a.accountToggle,()=>xa?`I have one`:p(`Create one`)),a.accountPassword.autocomplete=xa?`new-password`:`current-password`,wa()},Ea=async()=>{let e=[];Sa=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Sa=!0,e=(await t.json()).providers??[])}catch{}a.accountProviders.replaceChildren(),a.accountProviders.hidden=e.length===0,a.accountPanel.hidden=!Sa,a.accountElsewhere.hidden=Sa,wa();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}`,a.accountProviders.append(e)}},Da=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();K=e.ok?t.account?.id??``:``,Ta(e.ok?t.account?.email??`you`:null)}catch{K=``,Ta(null)}if(P.session=``,K!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));P.session=e.ok&&typeof t.token==`string`?t.token:``}catch{P.session=``}c===`remote`&&fr()}Or(),wr(),Tr(),ja();let e=await Oa();if(rt!==``){let t=rt;rt=``,e?y=`golive:${t}`:Wn(t)}};async function Oa(){if(K===``||c===`remote`||Ze!==``)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=ka(),n=[...e].sort((e,n)=>Number(U(n.url)===t)-Number(U(e.url)===t));for(let e of n)if(await Je(e.url,void 0,e.key)!==null)return c!==`remote`&&(ee=!1,y=``,a.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,w=`Connecting to ${e.name}, your server…`,B(),a.remoteForm.requestSubmit(),!0);return!1}function ka(){try{return localStorage.getItem(un)??``}catch{return``}}function Aa(e){try{e===``?localStorage.removeItem(un):localStorage.setItem(un,e)}catch{}}function ja(){if(Ze===``)return;let e=Ze;Ze=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit()}a.accountToggle.addEventListener(`click`,()=>{xa=!xa,Ta(null)}),a.welcomeCreate.addEventListener(`click`,()=>{xa=!0,Ta(null),a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),a.accountEmail.focus({preventScroll:!0})}),a.welcomeBrowse.addEventListener(`click`,()=>{a.directory.hidden?a.browse.click():a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Ca,`hidden`)}catch{}a.welcome.hidden=!0}),a.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.accountEmail.value.trim(),n=a.accountPassword.value;(async()=>{a.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${xa?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){a.accountNote.textContent=r.error??`that did not work`;return}K=r.account?.id??``,a.accountPassword.value=``,Ta(r.account?.email??t),fr(),ja()}catch{a.accountNote.textContent=`could not reach nixamp.com`}finally{a.accountSubmit.disabled=!1}})()}),a.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}K=``,Ta(null),wr(),P.close(),T=-1,c=`local`,ue=`idle`,S=``,a.remoteUrl.value=``,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,a.listenOnly.hidden=!0,io(!1);try{localStorage.removeItem(ln)}catch{}w=`Signed out, and disconnected from the server.`,fr(),B()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Ze=t,y=e.get(`play`)??``,te=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t,w=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(a.linkUrl.value=n,t!==``&&y===``?y=`link:${n}`:t===``&&(rt=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=Ie(r);t?(Ze=t.view,y=t.what,te=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t.view,w=`Opening the stream you were sent…`):(a.linkUrl.value=r,rt=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Ma=[`zone-top`,`zone-main`],Na=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Pa=e=>e.parentElement&&Ma.includes(e.parentElement.id)?e.parentElement:null,Fa=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Ia=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Na(e)&&Pa(e)!==null),La=e=>e.dataset.title??e.id,Ra=new Map,za=Ia().map((e,t)=>(Ra.set(e.id,{zone:Pa(e)?.id??``,col:Fa(e),index:t}),e.id)),Q=xt();try{Q=Tt(localStorage.getItem(bt))}catch{}let Ba=()=>Q.order.length>0||Object.keys(Q.placement).length>0;function Va(){Q.order=Ia().map(e=>e.id);try{localStorage.setItem(bt,Et(Q))}catch{}}function Ha(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 Ua(){if(e)return;for(let e of Ia()){let t=Q.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Ma.includes(i.id)&&Ha(e,i,r===`a`||r===`b`?r:``)}let t=Dt(Ia().map(e=>e.id),Q.order);for(let e of Ma){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(Na),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((e,n)=>t.indexOf(e.id)-t.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of Ia())e.toggleAttribute(`data-collapsed`,Q.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Q.closed.includes(e.id))}function Wa(e,t){e.toggleAttribute(`data-collapsed`,t),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),Q.collapsed=Ot(Q.collapsed,e.id,t),Va(),Za()}function Ga(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===a.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===a.partiesPanel&&!t&&wr(),t&&n&&a.panelsToggle.focus({preventScroll:!0}),Q.closed=Ot(Q.closed,e.id,t),Va(),Za()}function Ka(e,t,n){let r=Pa(t);r&&e!==t&&(Ha(e,r,Fa(t)),n?t.after(e):t.before(e),Q.placement[e.id]=`${r.id}:${Fa(t)}`,Va(),Za())}let qa=null,Ja=()=>{for(let e of Ia())e.classList.remove(`drop-before`,`drop-after`)},Ya=(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 Xa(){for(let e of Ia()){let t=La(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=Ya(`≡`,`Move ${La(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=Ia().filter(t=>Pa(t)===Pa(e)&&Fa(t)===Fa(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(Ka(e,r,t.key===`ArrowDown`),i.focus({preventScroll:!0}))}),i.classList.add(`grip`),i.draggable=!0,i.addEventListener(`dragstart`,t=>{qa=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),i.addEventListener(`dragend`,()=>{qa=null,e.classList.remove(`dragging`),Ja()});let a=Ya(`▁`,`Shade ${La(e)} to its title`,()=>Wa(e,!e.hasAttribute(`data-collapsed`)));a.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let o=Ya(`✕`,`Hide ${La(e)}; the Panels list turns it back on`,()=>Ga(e,!0));e.id===`transcript-panel`&&r.append(J.button()),r.append(i,a,o),e.prepend(r),e.addEventListener(`dragover`,t=>{if(!qa||qa===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;Ja(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!qa||qa===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);Ja(),Ka(qa,e,n)})}}function Za(){if(a.panelsPanel.hidden||a.panelsList.contains(document.activeElement))return;let e=Ia().filter(e=>e!==a.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,`aria-label`,()=>`${La(e)} on`),i.addEventListener(`change`,()=>Ga(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,g(a,()=>La(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&&e.dataset.available!==`true`?`nothing to show right now`:``,t.append(r,o),t});a.panelsList.replaceChildren(...e)}function Qa(){Q=xt();for(let e of za){let t=document.getElementById(e),n=Ra.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(Ha(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Q.order=[...za],Ua(),Q=xt();try{localStorage.removeItem(bt)}catch{}Za()}function $a(e){if(!e||Ba())return;let t=Pa(a.adminPanel);if(!t)return;let n=[...t.children].filter(Na).find(e=>Fa(e)===Fa(a.adminPanel));n&&n!==a.adminPanel&&n.before(a.adminPanel),a.adminPanel.removeAttribute(`data-collapsed`),a.adminPanel.removeAttribute(`data-closed`)}a.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=a.panelsPanel.hidden||a.panelsPanel.hasAttribute(`data-closed`)||a.panelsPanel.hasAttribute(`data-collapsed`);a.panelsPanel.hidden=!t,a.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(a.panelsPanel.hasAttribute(`data-closed`)&&Ga(a.panelsPanel,!1),a.panelsPanel.hasAttribute(`data-collapsed`)&&Wa(a.panelsPanel,!1),Za(),a.panelsPanel.showPopover?.(),a.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):a.panelsPanel.hidePopover?.()}),a.panelsPanel.addEventListener(`toggle`,()=>{let e=a.panelsPanel.matches(`:popover-open`);a.panelsToggle.setAttribute(`aria-expanded`,String(e&&!a.panelsPanel.hasAttribute(`data-collapsed`))),e||(a.panelsPanel.hidden=!0)}),a.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof a.panelsPanel.hidePopover!=`function`&&(a.panelsPanel.hidden=!0,a.panelsToggle.setAttribute(`aria-expanded`,`false`),a.panelsToggle.focus({preventScroll:!0}))}),a.panelsReset.addEventListener(`click`,Qa),a.panelsSave.addEventListener(`click`,()=>{Va();let e=a.panelsSave.textContent??`Save setup`;a.panelsSave.textContent=`Saved`,window.setTimeout(()=>{a.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{Xa(),Za()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),Xa(),Ua(),Ea(),Da(),fr(),Zn(),a.browse.addEventListener(`click`,()=>{if(!a.directory.hidden){a.directory.hidden=!0;return}rr(),a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.disconnect.addEventListener(`click`,()=>{P.close(),a.listenOnly.hidden=!0,T=-1,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,_(a.catalogsPanel,`data-title`,()=>p(`Catalogs on this server`)),l=``,ae=``,jr(),io(!1),c=`local`,ue=`idle`,S=``,B()});async function eo(){if(c!==`remote`||P.shareLink===``){a.sharePanel.hidden=!0;return}a.sharePanel.hidden=!1;let e=yo(),t=globalThis.location.origin;a.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,a.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,a.sharePhone.hidden=!0,a.shareSend.hidden=!0,a.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(P.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ae=r.url,a.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Ve=r.live,He=r.live?r.code:``,We=n,a.liveControls.hidden=a.adminPanel.hidden||!r.possible,a.goLive.hidden=r.live,a.stopLive.hidden=!r.live,a.sharePhone.hidden=!1,!r.live){a.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){a.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,a.shareSend.hidden=!1;return}a.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),To(n),document.createTextNode(` and key `),To(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),a.shareSend.hidden=!1}}let to=null,no=null,ro=0,io=e=>{to&&clearInterval(to),to=null,ro+=1,no?.abort(),no=null,O=null,Cr(),e&&($(),to=setInterval(()=>{document.visibilityState===`visible`&&$()},2e3))};async function $(){if(c!==`remote`||no)return;let e=new AbortController;no=e;let t=ro,n=P.url(`/api/streams`),r=setTimeout(()=>e.abort(),8e3);try{let r=await fetch(n,{signal:e.signal,cache:`no-store`});if(!r.ok)return;let i=await r.json();if(e.signal.aborted||t!==ro||c!==`remote`||n!==P.url(`/api/streams`))return;m=i.server.carries!==!1,i.server.name&&i.server.name!==l&&(l=i.server.name,a.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${l}`),jr()),O=i,bo(i),B(),ao(i)}catch{}finally{clearTimeout(r),no===e&&(no=null)}}function ao(e){Cr(),E&&Fn()}function oo(e){let t=Jt(),n=e.restreams??[],r=[],i=e.server.playing,o=!a.adminPanel.hidden;i&&r.push(xo({key:`live`,title:me(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${me(e.server.nowPlaying)}`:`nothing loaded`,i&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:`Join party`,onPlay:()=>{i&&co(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:vo(`live`)}:{},direct:i?P.url(`/api/live`):``}));for(let e of n)r.push(xo({key:`restream:${e.at}`,title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{hn(e.at)},link:``,direct:P.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=P.url(`/api/channels/${encodeURIComponent(t.id)}`),i=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&i.push(`☎ ${t.code}`),t.redials&&i.push(`redialled ${t.redials}×`),o&&t.error&&i.push(t.error),r.push(xo({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{lo({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:vo(`channel:${t.id}`),direct:n,onRestart:(o||mt&&K!==``&&t.startedBy===K)&&t.via===`pull`?()=>{po(t.id,t.name)}:void 0,onStop:o||mt&&K!==``&&t.startedBy===K?()=>ho(t.id,t.name):void 0,onRename:o||mt&&K!==``&&t.startedBy===K?()=>{mo(t.id,t.name)}:void 0}))}return r}async function so(){if(c===`remote`)try{if((await fetch(P.media(I(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;w=K===``?`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.`,K===``&&a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),B()}catch{}}async function co(e){T=-1,E=null,D={kind:`live`},Be(e,`auto`),await Ce(()=>N.load({title:e||`Live`,artist:``,album:``,duration:0,url:P.url(`/api/live`),video:!0,objectUrl:!1},!0)),Hn(!0),w=`Watching what this server is playing. Everyone here sees the same thing.`,B()}async function lo(e,t=!0,n){T=-1,E=e,t&&(ye=0),t&&(D=n??{kind:`channel`}),t&&Be(e.name,D?.link||sn(e.name)?`auto`:`channel`);let r=e.video&&vt(),i=e.video&&(e.playlist?.length??0)>1;await Ce(()=>N.load({title:e.name,artist:``,album:``,duration:0,url:P.url(r||i?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),Hn(e.video),E===e&&(w=`Watching ${e.name}, live on this server.`),B()}function uo(){let e=E;return e?Xe?!0:ye>=5?(w=`${e.name} stopped, and did not come back.`,E=null,D=null,B(),!0):(ye+=1,w=`${e.name} started over; rejoining…`,B(),Xe=setTimeout(()=>{Xe=null,E===e&&lo(e,!1)},2e3),!0):!1}function fo(e){a.partiesNote.hidden=!1,a.partiesNote.textContent=e,H(e)}async function po(e,t){fo(`Restarting ${t}…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));fo(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{fo(`could not reach the server`)}$()}async function mo(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){fo(`Renaming ${t}…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));fo(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{fo(`could not reach the server`)}E?.id===e&&(E={...E,name:r}),$(),B()}}async function ho(e,t){fo(`Taking ${t} off the air…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));if(fo(n.ok?`${t} is off the air.`:r.error??`that did not work`),!n.ok)return!1}catch{return fo(`could not reach the server`),!1}return E?.id===e&&(E=null,N.stop()),!0}function go(e,t,n,r){if(e.classList.contains(`removing`))return;t.disabled=!0,t.setAttribute(`aria-busy`,`true`);let i=document.createElement(`span`);i.className=`delete-spinner`,i.setAttribute(`role`,`status`),i.setAttribute(`aria-label`,`Removing`),i.textContent=``,t.after(i),n().then(n=>{if(!n){i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`);return}e.classList.add(`removing`),window.setTimeout(()=>{e.remove(),r?.()},260)}).catch(()=>{i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`)})}async function _o(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{w=e,B();return}n===`✓`||n===`✓`?o(t,`check`):g(t,()=>p(n)),setTimeout(()=>{t.innerHTML=r},1200)}function vo(e,t=0){let n=yo();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 yo(){if(ae!==``)return ae;let e=c===`remote`?P.shareLink:``;return/\/admin\//.test(e)?``:e}function bo(e){if(y===``)return;let t=y;if(t===`live`){y=``,e.server.playing?co(e.server.nowPlaying):(w=`Nothing is playing on this server right now.`,B());return}if(t.startsWith(`link:`)){y=``,Wn(t.slice(5));return}if(t.startsWith(`golive:`)){y=``,a.linkUrl.value=t.slice(7),fr().then(()=>Qn());return}if(t.startsWith(`track:`)){y=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&hn(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&&(y=``,lo({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function xo(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${v(P.address)}:${e.key}`;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 s=document.createElement(`button`);s.type=`button`,s.className=`button`,wt(s,e.playLabel??`Join party`),s.hidden=e.key.startsWith(`channel:`)&&E?.id===e.key.slice(8),s.addEventListener(`click`,e.onPlay),a.append(s);let c=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,o(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(c(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;_o(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(c(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{_o(e.direct??``,t,`✓`)})),e.onRestart&&a.append(c(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(c(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(c(`remove`,`Remove: take it off the air`,n=>{go(t,n,e.onStop,()=>void $())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,_(s,`aria-label`,()=>`${p(e.playLabel??`Join party`)}: ${e.title}`);let l=document.createElement(`details`);l.className=`party-actions`;let u=document.createElement(`summary`);return u.textContent=`⋯`,_(u,`aria-label`,()=>`${p(`Show more`)}: ${e.title}`),a.removeChild(s),l.append(u,a),t.append(n,s),a.childElementCount&&t.append(l),t}let So=``;function Co(e,t){So=e;let n=e!==``&&t===e;a.loadHome.hidden=e===``,a.homeNote.hidden=e===``,e!==``&&(a.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,a.loadHome.disabled=!1)}a.loadHome.addEventListener(`click`,()=>{So!==``&&(a.loadHome.disabled=!0,H(`Reading this server's files…`),(async()=>{try{let e=await fetch(P.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:So})}),t=await e.json();H(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{H(`could not reach the server`)}finally{a.loadHome.disabled=!1}})())});let wo=async e=>{a.goLive.disabled=!0,a.stopLive.disabled=!0,a.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(P.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();a.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{a.shareNote.textContent=`could not reach the server`}finally{a.goLive.disabled=!1,a.stopLive.disabled=!1,await eo()}};a.goLive.addEventListener(`click`,()=>void wo(!0)),a.stopLive.addEventListener(`click`,()=>void wo(!1));function To(e){let t=document.createElement(`b`);return t.textContent=e,t}a.shareCopy.addEventListener(`click`,()=>{a.shareLink.select(),navigator.clipboard?.writeText(a.shareLink.value).then(()=>{a.shareNote.textContent=`Copied. Send it to anybody.`},()=>{a.shareNote.textContent=`Copy it from the box above.`})}),a.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=a.shareTo.value.trim();t!==``&&(async()=>{a.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:yo()})}),n=await e.json();a.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(a.shareTo.value=``)}catch{a.shareNote.textContent=`could not send that`}})()}),a.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(fn,a.listenHere.checked?`1`:`0`)}catch{}c===`remote`&&(async()=>{a.listenHere.checked?(await P.send({type:`stop`}),await vn(x.index)):(N.stop(),T=-1),B()})()}),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===a.transport)switch(e.key){case` `:e.preventDefault(),yn();return;case`s`:xn();return;case`n`:case`ArrowRight`:bn(1);return;case`p`:case`ArrowLeft`:bn(-1);return;case`ArrowDown`:e.preventDefault(),hn(Math.min(F()-1,I()+1));return;case`ArrowUp`:e.preventDefault(),hn(Math.max(0,I()-1));return}});let Eo=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Eo=e,a.install.hidden=!1}),a.install.addEventListener(`click`,()=>{Eo?.prompt(),Eo=null,a.install.hidden=!0});try{let e=localStorage.getItem(dn);e!==null&&(a.volume.value=String(Math.round(Number(e)*100)),N.volume=Number(e));let t=localStorage.getItem(ln);t&&(a.remoteUrl.value=t),localStorage.getItem(fn)===`0`&&(a.listenHere.checked=!1)}catch{}(async()=>{if(a.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await Je(e)===null)return;let t=await Ge(e);t&&t.trackCount!==0&&(a.remoteUrl.value=e,c=`remote`,w=``,P.connect(e),io(!0),ea(),B())})(),wr();let Do=()=>{document.visibilityState===`visible`&&!a.partiesPanel.hasAttribute(`data-closed`)&&wr()},Oo=setInterval(Do,2e3);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(wr(),$())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(Oo),to&&clearInterval(to),xr?.abort(),no?.abort(),xr=null,no=null,ro+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(Oo),Oo=setInterval(Do,2e3),Do(),c===`remote`&&io(!0))}),(()=>{if(mn||Ze!==``)return;let e=()=>N.source!==``||N.playing||Se()||E!==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=()=>{mn=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||N.playJingle(n).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,N.playJingle(n).then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),B(),requestAnimationFrame(zn)}hn(),ie(),ue(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{e as n,u as t};