nixamp 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/handoff-routes.d.ts +17 -0
  2. package/dist/handoff-routes.js +64 -0
  3. package/dist/handoff.d.ts +89 -0
  4. package/dist/handoff.js +358 -0
  5. package/dist/library-index.d.ts +9 -0
  6. package/dist/library-index.js +19 -0
  7. package/dist/oauth-server.d.ts +1 -0
  8. package/dist/oauth-server.js +1 -0
  9. package/dist/owner.js +4 -1
  10. package/dist/server.d.ts +3 -0
  11. package/dist/server.js +49 -3
  12. package/package.json +1 -1
  13. package/src/handoff-routes.ts +73 -0
  14. package/src/handoff.ts +383 -0
  15. package/src/library-index.ts +21 -0
  16. package/src/oauth-server.ts +1 -0
  17. package/src/owner.ts +5 -2
  18. package/src/server.ts +52 -3
  19. package/web/dist/assets/{ar-4kD-mTIA.js → ar-DoW0wbjC.js} +1 -1
  20. package/web/dist/assets/{cs-CziXiWNY.js → cs-CjKqCjy5.js} +1 -1
  21. package/web/dist/assets/{da-CyjJ8UOr.js → da-BQERb7Qz.js} +1 -1
  22. package/web/dist/assets/{de-DxwYa667.js → de-CKKbRy6c.js} +1 -1
  23. package/web/dist/assets/{es-QgMTJeSc.js → es-CL3v5Og9.js} +1 -1
  24. package/web/dist/assets/{fi-Clj-jHhR.js → fi-DgV81qNU.js} +1 -1
  25. package/web/dist/assets/{fr-nH_gzSFv.js → fr-BGumytzF.js} +1 -1
  26. package/web/dist/assets/{hi-D7djQ6_C.js → hi-CAQ9elqo.js} +1 -1
  27. package/web/dist/assets/{hls-3VKVEQE3-BaWVouMg.js → hls-3VKVEQE3-Ceri0flt.js} +1 -1
  28. package/web/dist/assets/{hu-H5Q3L8bD.js → hu-UJNgJVWX.js} +1 -1
  29. package/web/dist/assets/{id-40z_EQdf.js → id-BqQOlrF-.js} +1 -1
  30. package/web/dist/assets/{it-C9Fcgywl.js → it-Cs8G6mvW.js} +1 -1
  31. package/web/dist/assets/{main-BJUyBy0h.js → main-Y1Rvn1GX.js} +2 -2
  32. package/web/dist/assets/{mpegts-LO6RVLD6-CAuth8C5.js → mpegts-LO6RVLD6-CPI8xaZ-.js} +1 -1
  33. package/web/dist/assets/{mpegts-BlmyNlBC.js → mpegts-jS_Diizz.js} +1 -1
  34. package/web/dist/assets/{nl-CrL4Psk9.js → nl-BJXQ9nqo.js} +1 -1
  35. package/web/dist/assets/{ru-C84JS0ch.js → ru-XmVkvNY8.js} +1 -1
  36. package/web/dist/assets/{sv-DtMcl0sf.js → sv-pVm9p66e.js} +1 -1
  37. package/web/dist/assets/{uk-dOLf99vZ.js → uk-4hcyaD3e.js} +1 -1
  38. package/web/dist/assets/{vi-BWeQVRZ8.js → vi-B7MipBlv.js} +1 -1
  39. package/web/dist/assets/{zh-Cnv3Qpux.js → zh-B5YVExOW.js} +1 -1
  40. package/web/dist/index.html +1 -1
  41. package/web/dist/sw.js +22 -22
@@ -1,4 +1,4 @@
1
- import"./styles-D70tSrIe.js";var e={"Nixamp Share link or HTTPS media URL":`Nixamp Share link or HTTPS media URL`,"For TV playback, use a Nixamp Share link or a direct HTTPS media URL. Pairux viewing opens separately.":`For TV playback, use a Nixamp Share link or a direct HTTPS media URL. Pairux viewing opens separately.`,Paused:`Paused`,"Broadcast ended":`Broadcast ended`,"Class broadcast":`Class broadcast`,Play:`Play`,Pause:`Pause`,"Retry playback":`Retry playback`,"Back 10 seconds":`Back 10 seconds`,"Forward 10 seconds":`Forward 10 seconds`,Mute:`Mute`,Unmute:`Unmute`,"Full screen":`Full screen`,"Exit full screen":`Exit full screen`,Playing:`Playing`,"Select Play to watch the broadcast.":`Select Play to watch the broadcast.`,"The broadcast could not be loaded. Try again.":`The broadcast could not be loaded. Try again.`,"This Pairux broadcast opens separately. For playback here on Fire TV, the host needs to share a Nixamp stream or direct media link.":`This Pairux broadcast opens separately. For playback here on Fire TV, the host needs to share a Nixamp stream or direct media link.`,"Open on Pairux":`Open on Pairux`,"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-DxwYa667.js`),[]),sv:()=>u(()=>import(`./sv-DtMcl0sf.js`),[]),es:()=>u(()=>import(`./es-QgMTJeSc.js`),[]),fr:()=>u(()=>import(`./fr-nH_gzSFv.js`),[]),it:()=>u(()=>import(`./it-C9Fcgywl.js`),[]),nl:()=>u(()=>import(`./nl-CrL4Psk9.js`),[]),da:()=>u(()=>import(`./da-CyjJ8UOr.js`),[]),fi:()=>u(()=>import(`./fi-Clj-jHhR.js`),[]),ru:()=>u(()=>import(`./ru-C84JS0ch.js`),[]),uk:()=>u(()=>import(`./uk-dOLf99vZ.js`),[]),cs:()=>u(()=>import(`./cs-CziXiWNY.js`),[]),hu:()=>u(()=>import(`./hu-H5Q3L8bD.js`),[]),zh:()=>u(()=>import(`./zh-Cnv3Qpux.js`),[]),ar:()=>u(()=>import(`./ar-4kD-mTIA.js`),[]),hi:()=>u(()=>import(`./hi-D7djQ6_C.js`),[]),vi:()=>u(()=>import(`./vi-BWeQVRZ8.js`),[]),id:()=>u(()=>import(`./id-40z_EQdf.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=[[/\.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`]],h=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function g(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of h)if(t.test(e.mimeType))return n}let t=_(e.src);for(let[e,n]of m)if(e.test(t))return n;return`unknown`}function _(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function v(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 y(e,t){let n=g(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 b(e,t){let n=t.capabilities??v(),r=y({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-BaWVouMg.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-CAuth8C5.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 ee=300,x=120,te=.4;function ne(e,t,n,r){return n<=0||e===t?(r(t),Promise.resolve()):new Promise(i=>{let a=Date.now(),o=n*1e3,s=()=>{let n=Math.min(1,(Date.now()-a)/o);r(e+(t-e)*n),n<1?setTimeout(s,16):i()};s()})}var re=e=>Math.min(1,Math.max(0,e));function ie(e){return e.volume>0?e.volume:1}function ae(e){return e&&e.tagName===`VIDEO`?e:null}function S(e){return e?typeof document<`u`&&document.pictureInPictureElement===e||e.webkitPresentationMode===`picture-in-picture`:!1}async function oe(e){let t=e,n=e.requestPictureInPicture;if(typeof n==`function`){await n.call(e);return}if(typeof t.webkitSetPresentationMode==`function`){t.webkitSetPresentationMode(`picture-in-picture`);return}throw Error(`picture-in-picture is not available here`)}var C=/\.(mp3|m4a|aac|ogg|oga|opus|wav|flac)(\?|#|$)/i;function se(e){let t=typeof e==`string`?{url:e}:e;return{url:t.url,kind:t.kind??(C.test(t.url)?`audio`:`video`)}}function w(e,t,n,r=()=>Date.now()){let i=Math.max(5,n.everySeconds??ee)*1e3,a=Math.max(5,n.maxSeconds??x)*1e3,o=Math.max(0,n.fadeSeconds??te),s=n.revealStage!==!1;function c(){if(!s||typeof window>`u`)return;let t=e.getBoundingClientRect();if(Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)>=t.height*.6)return;let n=!window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;e.scrollIntoView({block:`center`,behavior:n?`smooth`:`auto`})}async function l(e){if(e)try{await oe(e)}catch(e){n.onError?.(e)}}let u=0,d=null,f=0,p=!1,m=!1,h=!n.preroll,g=document.createElement(`div`);g.className=`pux-ad`,g.hidden=!0,Object.assign(g.style,{position:`absolute`,inset:`0`,zIndex:`3`,display:`grid`,placeItems:`center`,background:`#000`});let _=getComputedStyle(e).position;(!_||_===`static`)&&(e.style.position=`relative`);let v=document.createElement(`video`);v.className=`pux-ad__video`,v.playsInline=!0,v.preload=`auto`,Object.assign(v.style,{width:`100%`,height:`100%`,objectFit:`contain`,background:`#000`});let y=document.createElement(`audio`);y.className=`pux-ad__audio`,y.preload=`auto`;let b=v;for(let e of[v,y])e.muted=t.muted,e.volume=ie(t);let C=document.createElement(`span`);C.className=`pux-ad__badge`,C.textContent=`Ad`,Object.assign(C.style,{position:`absolute`,top:`0.75rem`,left:`0.75rem`,padding:`0.15rem 0.5rem`,borderRadius:`0.25rem`,background:`rgb(0 0 0 / 0.65)`,color:`#fff`,font:`600 0.75rem/1.4 system-ui, sans-serif`,letterSpacing:`0.04em`,textTransform:`uppercase`});let w=document.createElement(`button`);w.type=`button`,w.className=`pux-ad__skip`,w.hidden=!0,Object.assign(w.style,{position:`absolute`,right:`1rem`,bottom:`1rem`,padding:`0.5rem 0.9rem`,border:`1px solid rgb(255 255 255 / 0.4)`,borderRadius:`0.3rem`,background:`rgb(0 0 0 / 0.6)`,color:`#fff`,font:`500 0.85rem/1 system-ui, sans-serif`,cursor:`pointer`}),g.append(v,y,C,w),e.append(g);function T(){if(m||p)return;let e=r();if(t.paused){d=null;return}d!==null&&(u+=e-d),d=e,u>=i&&ce()}async function ce(){if(p||m)return;p=!0,u=0,d=null;let r=null;try{r=await n.next()}catch(e){n.onError?.(e)}if(!r||m){p=!1;return}let i=se(r),s=i.url;b=i.kind===`audio`?y:v;let h=f++,_=!t.paused,ee=i.kind!==`audio`&&S(t),x=ie(t);await ne(x,0,o,e=>{t.volume=re(e)}),t.pause(),b.src=s,b.currentTime=0,b.muted=t.muted,b.volume=0,g.style.opacity=`0`,c(),g.hidden=!1,g.classList.toggle(`pux-ad--audio`,i.kind===`audio`);let te=i.kind===`audio`;g.style.background=te?`rgb(0 0 0 / 0.35)`:`#000`,v.style.display=te?`none`:``,e.classList.add(`pux-player--ad`),n.onBreakStart?.({url:s,index:h});let oe=!1,C=e=>{p&&(oe=e,ne(1,0,o,e=>{g.style.opacity=String(e),b.volume=re(x*e)}).then(async()=>{ee&&S(b)&&await l(ae(t)),T(),n.onBreakEnd?.({url:s,index:h,skipped:oe}),!m&&(t.volume=0,_&&t.play().catch(()=>{}),ne(0,x,o,e=>{t.volume=re(e)}))}))};function T(){clearTimeout(le),clearInterval(ue),b.removeEventListener(`ended`,ce),b.removeEventListener(`error`,E),w.removeEventListener(`click`,D),b.pause(),b.removeAttribute(`src`),b.load(),g.hidden=!0,g.classList.remove(`pux-ad--audio`),w.hidden=!0,e.classList.remove(`pux-player--ad`),p=!1}let ce=()=>C(!1),E=()=>{n.onError?.(Error(`advert failed to play: ${s}`)),C(!1)},D=()=>C(!0);b.addEventListener(`ended`,ce),b.addEventListener(`error`,E),w.addEventListener(`click`,D);let le=setTimeout(()=>C(!1),a),O=n.skipAfter,ue=0;if(typeof O==`number`&&O>=0){let e=O;w.hidden=!1;let t=()=>{let t=Math.ceil(e-b.currentTime);t>0?(w.disabled=!0,w.textContent=`Skip in ${t}`):(w.disabled=!1,w.textContent=`Skip ad`)};t(),ue=setInterval(t,250)}try{await b.play(),ee&&await l(b),await ne(0,1,o,e=>{g.style.opacity=String(e),b.volume=re(x*e)})}catch(e){n.onError?.(e),t.volume=re(x),C(!1)}}let E=()=>T(),D=()=>{d=r(),h||(h=!0,ce())},le=()=>{T(),d=null},O=()=>{for(let e of[v,y])e.muted=t.muted,e.volume=ie(t)};return t.addEventListener(`timeupdate`,E),t.addEventListener(`play`,D),t.addEventListener(`pause`,le),t.addEventListener(`volumechange`,O),{play(){return ce()},destroy(){m=!0,S(b)&&l(ae(t)),t.removeEventListener(`timeupdate`,E),t.removeEventListener(`play`,D),t.removeEventListener(`pause`,le),t.removeEventListener(`volumechange`,O),v.pause(),y.pause(),g.remove()},get playing(){return p}}}var T=[`active`,`trialing`];function ce(e,t,n=new Date){if(!e?.length)return!1;let r=new Set(T);return e.some(e=>{if(e.product!==t||!r.has(e.status))return!1;let i=e.period?.end?Date.parse(e.period.end):NaN;if(Number.isFinite(i)&&i<n.getTime())return!1;let a=e.period?.start?Date.parse(e.period.start):NaN;return!(Number.isFinite(a)&&a>n.getTime())})}async function E(e){let t=null;try{t=await e.entitlements()??null}catch{return e.ads}let n=e.now?.()??new Date;return ce(t,e.product,n)?null:e.ads}var D=600,le=`https://crawlproof.com/api/ads/stream`,O=`nixamp.pro`;function ue(){let e=document.querySelector(`#video`);return e&&!e.hidden&&e.currentSrc&&!e.paused?`video`:`audio`}async function de(){try{let e=await fetch(`/api/entitlements`,{credentials:`include`,headers:{accept:`application/json`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t)?t:t.entitlements??[]}catch{return[]}}var fe=`7e0ea02c-c40f-4cdd-b4d3-93b2baca8f2c`;function pe(e){let t=new URLSearchParams(e),n=t.get(`ads`),r=Number(t.get(`adsEvery`)),i=t.get(`adNow`);return{enabled:i===null?n===null?null:n!==`0`&&n!==`false`:!0,everySeconds:Number.isFinite(r)&&r>0?Math.min(3600,Math.max(5,r)):null,adUrl:he(t.get(`adUrl`)),now:i!==null&&i!==`0`&&i!==`false`}}function me(e=location.search){return pe(e).now}function he(e){if(!e)return null;try{let t=new URL(e,location.origin);return t.protocol===`https:`?t.toString():null}catch{return null}}var k=null;function A(e){if(k)try{let t=`${k.endpoint}?d=${encodeURIComponent(k.decision)}&t=${encodeURIComponent(e)}&s=player`;new Image().src=t}catch{}}async function ge(e={},t=location.search){let n=pe(t);if(n.enabled===!1)return null;let r={everySeconds:n.everySeconds??e.everySeconds??D,next:async()=>{if(n.adUrl)return{url:n.adUrl};try{let t=`${le}?slot=${encodeURIComponent(e.slot??fe)}&kind=${ue()}`,n=await fetch(t,{headers:{accept:`application/json`}});if(!n.ok)return null;let r=await n.json();return r.url?(k=r.decisionId&&r.eventsUrl?{decision:r.decisionId,endpoint:r.eventsUrl,url:r.url}:null,{url:r.url,kind:r.kind}):null}catch{return null}},onBreakStart:e=>{k&&k.url!==e.url&&(k=null),A(`start`)},onBreakEnd:e=>{A(e.skipped?`abandon`:`complete`),k=null},onError:e=>{A(`error`),k=null,console.warn(`advert failed`,e)}};return n.enabled===!0?r:e.paid===!0?null:E({product:O,entitlements:de,ads:r})}var j={"no-window":`Push notifications are only available in a browser.`,"insecure-context":`Push notifications need a secure (https://) connection.`,"no-service-worker":`This browser does not support service workers, which push notifications need.`,"ios-needs-install":`On iPhone and iPad, add this site to your Home Screen (Share, then "Add to Home Screen") and open it from there to get notifications.`,"no-push-manager":`This browser does not support push notifications.`,"no-notification":`This browser does not support notifications.`,denied:`Notifications are blocked for this site. Allow them in your browser’s site settings, then try again.`,"no-server-key":`Push notifications are not set up on this server yet.`};function _e(e){let t=e?.userAgent??``;return/iPad|iPhone|iPod/.test(t)||/Macintosh/.test(t)&&(e?.maxTouchPoints??0)>1}function ve(e){return e?.navigator?.standalone===!0||typeof e?.matchMedia==`function`&&e.matchMedia(`(display-mode: standalone)`).matches}function ye(e=globalThis){let t=e,n=e?.navigator,r=e=>({supported:!1,reason:e,message:j[e],permission:be(t)});return!t||!n?r(`no-window`):t.isSecureContext===!1?r(`insecure-context`):`serviceWorker`in n?`PushManager`in t?`Notification`in t?t.Notification.permission===`denied`?r(`denied`):{supported:!0,reason:null,message:null,permission:t.Notification.permission}:r(`no-notification`):r(_e(n)&&!ve(t)?`ios-needs-install`:`no-push-manager`):r(`no-service-worker`)}function be(e){return e&&`Notification`in e?e.Notification.permission:`unsupported`}var xe=class extends Error{constructor(e,t){super(t??j[e]??e),this.name=`PushError`,this.reason=e}},M=new Map;async function Se({url:e=`/api/push/vapid-public-key`,fetch:t=globalThis.fetch}={}){if(M.has(e))return M.get(e);let n=await t(e,{headers:{accept:`application/json`}});if(!n.ok)throw new xe(`no-server-key`);let r=(await n.text()).trim(),i=r;try{i=JSON.parse(r).publicKey??``}catch{}if(!i||!/^[A-Za-z0-9_-]{80,100}={0,2}$/.test(i))throw new xe(`no-server-key`);return M.set(e,i),i}function Ce(e){let t=e+`=`.repeat((4-e.length%4)%4),n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function we(e,t){if(!e||!t)return!1;let n=new Uint8Array(e);if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}async function Te({serviceWorkerUrl:e,scope:t,env:n}){let r=n.navigator.serviceWorker;return await r.getRegistration(t)||await r.register(e,t?{scope:t}:void 0),r.ready}async function Ee(e={}){let t=e.env??globalThis,n=e.fetch??t.fetch?.bind(t)??globalThis.fetch,r=ye(t);if(!r.supported)throw new xe(r.reason);if((t.Notification.permission===`granted`?`granted`:await t.Notification.requestPermission())!==`granted`)throw new xe(`denied`);let i=Ce(e.vapidPublicKey||await Se({url:e.vapidKeyUrl,fetch:n})),a=await Te({serviceWorkerUrl:e.serviceWorkerUrl??`/sw.js`,scope:e.scope,env:t}),o=await a.pushManager.getSubscription();o&&!we(o.options?.applicationServerKey,i)&&(await o.unsubscribe(),o=null),o??=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:i});let s=typeof o.toJSON==`function`?o.toJSON():o;if(e.save&&await e.save(s),e.saveUrl){let t=await n(e.saveUrl,{method:`POST`,headers:{"content-type":`application/json`,...e.headers??{}},body:JSON.stringify(s),credentials:`include`});if(!t.ok)throw new xe(`save-failed`,`Could not save the subscription (${t.status})`)}return s}async function De({scope:e,env:t=globalThis}={}){let n=ye(t);if(!n.supported&&n.reason!==`denied`)return null;let r=await(await t.navigator.serviceWorker.getRegistration(e))?.pushManager.getSubscription();return r?r.toJSON():null}async function Oe({scope:e,removeUrl:t,headers:n,env:r=globalThis,fetch:i}={}){let a=await(await r.navigator?.serviceWorker?.getRegistration(e))?.pushManager.getSubscription();if(!a)return!1;let o=a.endpoint;return await a.unsubscribe(),t&&await(i??r.fetch.bind(r))(t,{method:`DELETE`,headers:{"content-type":`application/json`,...n??{}},body:JSON.stringify({endpoint:o}),credentials:`include`}).catch(()=>void 0),!0}var N=new Map;function ke(e,t,n){let r=N.get(e);r||(r=new Map,N.set(e,r)),r.set(t,n),n()}function P(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return ke(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){N.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function F(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return ke(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){N.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var Ae=[`aria-label`,`title`,`placeholder`,`data-title`],je=[`[data-i18n]`,...Ae.map(e=>`[data-i18n-${e}]`)].join(`,`);function Me(e){let t=[...e.querySelectorAll(je)];e instanceof HTMLElement&&e.matches(je)&&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;ke(e,`text`,()=>{if(e.textContent!==n){N.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=p(t),e.textContent!==n&&(e.textContent=n)})}for(let t of Ae){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);ke(e,t,()=>{if(e.getAttribute(t)!==r){N.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=p(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function Ne(){document.documentElement.lang=f.language,document.documentElement.dir=f.direction;for(let[e,t]of N){if(!e.isConnected){N.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=f.language}var Pe=0;async function Fe(e){let t=++Pe;try{if(!await f.setLanguage(e)||t!==Pe)return;try{localStorage.setItem(i,f.language)}catch{}window.nixampLanguage?.set(f.language).catch(()=>{})}catch{Ne()}}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`,()=>{Fe(e.value)});Me(document),Ne(),f.onChange(Ne),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&Me(e);for(let e of N.keys())e.isConnected||N.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 Le={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 Re(e,t){e.innerHTML=Le[t]}function ze(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 Be(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function Ve(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var He=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function Ue(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&He.has(e.slice(n+1).toLowerCase())}function I(){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 We=new WeakMap;function Ge(e,t=!0){let n=e.contains(document.activeElement);We.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function L(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){We.delete(e),e.replaceChildren(...t);return}let n=We.has(e);if(We.set(e,t),n)return;let r=()=>{let t=We.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}We.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var Ke=new WeakMap,qe=new WeakSet;function Je(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?Ke.set(e,t):Ke.delete(e),qe.has(e))return;qe.add(e);let a=()=>{let t=Ke.get(e);t&&Je(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function Ye(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 Xe(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 Ze(e,t,n=`Live`){let r=e[t];if(!r){let e=Ye(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${Ye(r.title)}`:Ye(r.title),a=Xe(r.folder??``),o=Xe(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}}function Qe(e,t=160){let n=e.replace(/[-]/g,` `).trim();if(n.length<=t)return n;let r=n.split(/\s›\s|[\\/]/).map(e=>e.replace(/_+/g,` `).trim()).filter(Boolean),i=Ye(r.pop()??``);if(r.length===0)return $e(i,t);let a=r.shift(),o=e=>[a,...e,i].join(` › `),s=[];for(let e=r.length-1;e>=0&&!(o([r[e],...s]).length>t);--e)s.unshift(r[e]);let c=o(s);if(c.length<=t)return c;let l=t-i.length-3;return l>=12?`${$e(a,l)} › ${i}`:$e(i,t)}function $e(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=e[t-1]===` `?n.length:n.lastIndexOf(` `);return`${(r>t/2?n.slice(0,r):n).trimEnd()}…`}var et=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`]),tt=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function nt(e){let t=e.lastIndexOf(`.`);return t>0&&tt.has(e.slice(t+1).toLowerCase())}function R(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&et.has(e.slice(n+1).toLowerCase())}function rt(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function it(e){return e.filter(e=>R(e.name,e.type)).sort((e,t)=>rt(at(e),at(t))).map(e=>({title:Ve(e.name),artist:``,album:z(at(e)),duration:0,url:URL.createObjectURL(e),video:Ue(e.name,e.type),objectUrl:!0,...nt(e.name)?{kind:`mpegts`}:{}}))}function at(e){return e.webkitRelativePath||e.name}function z(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function ot(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var st=2048;function B(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 ct(e,t){return e||t===`hls`||t===`mpegts`}var lt=class{elements;handlers;attach;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;ads=null;adOptions=null;adRoot=null;frequencies=new Uint8Array;analysable=!0;constructor(e,t,n=b){this.elements=e,this.handlers=t,this.attach=n,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.attached||this.attached.engine===`native`)&&this.handlers.onError(ut(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}enableAds(e,t){this.adRoot=t?e:null,this.adOptions=t,this.rebindAds()}get adPlaying(){return this.ads?.playing??!1}async playAdNow(){await this.ads?.play()}rebindAds(){this.ads?.destroy(),this.ads=null,this.adOptions&&this.adRoot&&(this.ads=w(this.adRoot,this.active,this.adOptions))}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=st,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`:g({src:e.url})),r=ct(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||B(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.rebindAds()),this.attached?.destroy(),this.attached=null;try{this.attached=await this.attach(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.onBusy?.(!0)}})}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:`)||B(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}if(e instanceof Error&&e.name===`AbortError`&&this.attached?.engine!==`native`)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 ut(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 dt(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function ft(e,t){return{...t,tracks:t.tracks??e.tracks}}function pt(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 mt(e,t,n=``){let r=`${e===``?``:pt(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function ht(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 gt(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:pt(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var _t=null;function vt(e){if(!e&&_t!==null)return _t;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||(_t=n),n}catch{return!1}}function yt(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return mt(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function bt(e){if(typeof e!=`object`||!e)return null;let t=e,n=dt(),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 xt(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var St=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return xt(this.base,e)}url(e){let t=mt(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}=gt(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(mt(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=bt(Ct(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(mt(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=bt(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=vt()){return yt(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function Ct(e){try{return JSON.parse(e)}catch{return null}}async function wt(e,t,n=``){try{let r=await fetch(mt(e,`/api/state`,n),{signal:t});return r.ok?bt(await r.json()):null}catch{return null}}function Tt(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 Et(e,t=``,n){let r;try{r=await fetch(mt(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 Dt(e,t,n=``){try{let r=await fetch(mt(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 Ot(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 kt=.14,At=.02;function jt(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 Mt(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 Nt(e,t,n=kt){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Pt(e,t,n=At){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function Ft(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 It(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 Lt(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function Rt(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 zt(e,t={}){let n=e.data,r=It(n.away,n.awayScore),i=It(n.home,n.homeScore),a=Lt(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=Rt(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 Bt=`nixamp.tv`,Vt=/\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 Ht(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?Ut(r):/\bSilk\b/.test(e)&&n===0?!0:Vt.test(e):Ut(i)}function Ut(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Wt(e){return e?12:100}function Gt(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 Kt=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,qt=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,Jt=/\.m3u8(\?.*)?$/i,Yt=/\.(m3u|pls)(\?.*)?$/i;function Xt(e){try{let t=new URL(e);return qt.test(t.pathname+t.search)}catch{return!1}}function Zt(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 Qt(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||Zt(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(!Kt.test(a)&&!qt.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 $t(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 en(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=$t(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 Yt.test(o)?{kind:`list`,url:n.toString(),label:Zt(n.toString())}:Kt.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:qt.test(o)||Jt.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var tn=`nixamp.panels`;function nn(){return{order:[],placement:{},collapsed:[],closed:[]}}var V=/^[a-z][a-z0-9-]{0,63}$/,rn=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function H(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&V.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function an(e){if(!e)return nn();let t;try{t=JSON.parse(e)}catch{return nn()}if(!t||typeof t!=`object`||Array.isArray(t))return nn();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))V.test(e)&&typeof t==`string`&&rn.test(t)&&(r[e]=t);let i=e=>{let t=H(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 on(e){return JSON.stringify(e)}function sn(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 cn(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function ln(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}function un(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 dn(e,t){return Object.assign(Error(e),{status:t})}var fn=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}},pn=class{options;tracker=new fn;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 dn(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=this.options.sourceLanguage?.()??``,s=new Uint8Array(ln(i?t.samples:t.samples.slice(-8e4))),c=this.options.hear?await this.options.hear(s,{speakers:i,language:o,signal:r}):await this.json(mn(i?this.options.paths?.speakers??`/api/v1/speech/speakers`:this.options.paths?.transcribe??`/api/v1/speech/transcribe?live=1`,o),{method:`POST`,headers:{"content-type":`audio/wav`},body:s},r);if(e!==this.generation)return;this.recognitionFailures=0;let l=c.language,u=[];if(i){let e=this.tracker.reconcile(c.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=c.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),s=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),c=[],d=()=>{c.length&&(u.push({channel:this.options.channel(),at:t.at+c[0].start*1e3,until:t.at+c.at(-1).end*1e3,text:c.map(e=>e.text).join(` `).trim(),language:l,speaker:o.id,voiceProfile:a.profile}),c=[])};for(let e of s)c.length&&e.start-c.at(-1).end>=.45&&d(),c.push(e),(/[.!?。!?]$/.test(e.text)||c.map(e=>e.text).join(` `).length>=400)&&d();c.length&&(i<r.length-1||t.until-(t.at+c.at(-1).end*1e3)>=350||t.until-(t.at+c[0].start*1e3)>=3e3)&&d()}}else c.text&&(u=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:c.text,language:l}]);if(!u.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...u.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:u,language:l,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!un(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 dn(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]),t=n.map(e=>e.text),a=this.options.translate?await this.options.translate(t,r,i,e):await this.json(this.options.paths?.translate??`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:t,from:r,to:i})},e);if(a.texts.length!==n.length||a.texts.some(e=>!e.trim()))throw dn(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((e,t)=>({...e,original:e.text,sourceLanguage:r,language:i,text:a.texts[t]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>hn(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!un(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 mn(e,t){return/^[a-z]{2,3}$/.test(t)?`${e}${e.includes(`?`)?`&`:`?`}language=${t}`:e}function hn(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 gn=16e3,_n=3e4;function vn(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function yn(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var bn=`nixamp.captions`,xn=`nixamp.captions.native-v2.language`,Sn=[{code:``,label:`Original (auto-detect)`},...r];function Cn(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return Sn.some(e=>e.code===t)?t:``}catch{return``}}function wn(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function Tn(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function En(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 Dn(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 On(e){try{return e(bn)!==`off`}catch{return!0}}function kn(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var An=`live-translate-audio-tap`,jn=`// The render thread copies small mono blocks. All networking stays off it.
1
+ import"./styles-D70tSrIe.js";var e={"Nixamp Share link or HTTPS media URL":`Nixamp Share link or HTTPS media URL`,"For TV playback, use a Nixamp Share link or a direct HTTPS media URL. Pairux viewing opens separately.":`For TV playback, use a Nixamp Share link or a direct HTTPS media URL. Pairux viewing opens separately.`,Paused:`Paused`,"Broadcast ended":`Broadcast ended`,"Class broadcast":`Class broadcast`,Play:`Play`,Pause:`Pause`,"Retry playback":`Retry playback`,"Back 10 seconds":`Back 10 seconds`,"Forward 10 seconds":`Forward 10 seconds`,Mute:`Mute`,Unmute:`Unmute`,"Full screen":`Full screen`,"Exit full screen":`Exit full screen`,Playing:`Playing`,"Select Play to watch the broadcast.":`Select Play to watch the broadcast.`,"The broadcast could not be loaded. Try again.":`The broadcast could not be loaded. Try again.`,"This Pairux broadcast opens separately. For playback here on Fire TV, the host needs to share a Nixamp stream or direct media link.":`This Pairux broadcast opens separately. For playback here on Fire TV, the host needs to share a Nixamp stream or direct media link.`,"Open on Pairux":`Open on Pairux`,"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-CKKbRy6c.js`),[]),sv:()=>u(()=>import(`./sv-pVm9p66e.js`),[]),es:()=>u(()=>import(`./es-CL3v5Og9.js`),[]),fr:()=>u(()=>import(`./fr-BGumytzF.js`),[]),it:()=>u(()=>import(`./it-Cs8G6mvW.js`),[]),nl:()=>u(()=>import(`./nl-BJXQ9nqo.js`),[]),da:()=>u(()=>import(`./da-BQERb7Qz.js`),[]),fi:()=>u(()=>import(`./fi-DgV81qNU.js`),[]),ru:()=>u(()=>import(`./ru-XmVkvNY8.js`),[]),uk:()=>u(()=>import(`./uk-4hcyaD3e.js`),[]),cs:()=>u(()=>import(`./cs-CjKqCjy5.js`),[]),hu:()=>u(()=>import(`./hu-UJNgJVWX.js`),[]),zh:()=>u(()=>import(`./zh-B5YVExOW.js`),[]),ar:()=>u(()=>import(`./ar-DoW0wbjC.js`),[]),hi:()=>u(()=>import(`./hi-CAQ9elqo.js`),[]),vi:()=>u(()=>import(`./vi-B7MipBlv.js`),[]),id:()=>u(()=>import(`./id-BqQOlrF-.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=[[/\.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`]],h=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function g(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of h)if(t.test(e.mimeType))return n}let t=_(e.src);for(let[e,n]of m)if(e.test(t))return n;return`unknown`}function _(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function v(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 y(e,t){let n=g(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 b(e,t){let n=t.capabilities??v(),r=y({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-Ceri0flt.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-CPI8xaZ-.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 ee=300,x=120,te=.4;function ne(e,t,n,r){return n<=0||e===t?(r(t),Promise.resolve()):new Promise(i=>{let a=Date.now(),o=n*1e3,s=()=>{let n=Math.min(1,(Date.now()-a)/o);r(e+(t-e)*n),n<1?setTimeout(s,16):i()};s()})}var re=e=>Math.min(1,Math.max(0,e));function ie(e){return e.volume>0?e.volume:1}function ae(e){return e&&e.tagName===`VIDEO`?e:null}function S(e){return e?typeof document<`u`&&document.pictureInPictureElement===e||e.webkitPresentationMode===`picture-in-picture`:!1}async function oe(e){let t=e,n=e.requestPictureInPicture;if(typeof n==`function`){await n.call(e);return}if(typeof t.webkitSetPresentationMode==`function`){t.webkitSetPresentationMode(`picture-in-picture`);return}throw Error(`picture-in-picture is not available here`)}var C=/\.(mp3|m4a|aac|ogg|oga|opus|wav|flac)(\?|#|$)/i;function se(e){let t=typeof e==`string`?{url:e}:e;return{url:t.url,kind:t.kind??(C.test(t.url)?`audio`:`video`)}}function w(e,t,n,r=()=>Date.now()){let i=Math.max(5,n.everySeconds??ee)*1e3,a=Math.max(5,n.maxSeconds??x)*1e3,o=Math.max(0,n.fadeSeconds??te),s=n.revealStage!==!1;function c(){if(!s||typeof window>`u`)return;let t=e.getBoundingClientRect();if(Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)>=t.height*.6)return;let n=!window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;e.scrollIntoView({block:`center`,behavior:n?`smooth`:`auto`})}async function l(e){if(e)try{await oe(e)}catch(e){n.onError?.(e)}}let u=0,d=null,f=0,p=!1,m=!1,h=!n.preroll,g=document.createElement(`div`);g.className=`pux-ad`,g.hidden=!0,Object.assign(g.style,{position:`absolute`,inset:`0`,zIndex:`3`,display:`grid`,placeItems:`center`,background:`#000`});let _=getComputedStyle(e).position;(!_||_===`static`)&&(e.style.position=`relative`);let v=document.createElement(`video`);v.className=`pux-ad__video`,v.playsInline=!0,v.preload=`auto`,Object.assign(v.style,{width:`100%`,height:`100%`,objectFit:`contain`,background:`#000`});let y=document.createElement(`audio`);y.className=`pux-ad__audio`,y.preload=`auto`;let b=v;for(let e of[v,y])e.muted=t.muted,e.volume=ie(t);let C=document.createElement(`span`);C.className=`pux-ad__badge`,C.textContent=`Ad`,Object.assign(C.style,{position:`absolute`,top:`0.75rem`,left:`0.75rem`,padding:`0.15rem 0.5rem`,borderRadius:`0.25rem`,background:`rgb(0 0 0 / 0.65)`,color:`#fff`,font:`600 0.75rem/1.4 system-ui, sans-serif`,letterSpacing:`0.04em`,textTransform:`uppercase`});let w=document.createElement(`button`);w.type=`button`,w.className=`pux-ad__skip`,w.hidden=!0,Object.assign(w.style,{position:`absolute`,right:`1rem`,bottom:`1rem`,padding:`0.5rem 0.9rem`,border:`1px solid rgb(255 255 255 / 0.4)`,borderRadius:`0.3rem`,background:`rgb(0 0 0 / 0.6)`,color:`#fff`,font:`500 0.85rem/1 system-ui, sans-serif`,cursor:`pointer`}),g.append(v,y,C,w),e.append(g);function T(){if(m||p)return;let e=r();if(t.paused){d=null;return}d!==null&&(u+=e-d),d=e,u>=i&&ce()}async function ce(){if(p||m)return;p=!0,u=0,d=null;let r=null;try{r=await n.next()}catch(e){n.onError?.(e)}if(!r||m){p=!1;return}let i=se(r),s=i.url;b=i.kind===`audio`?y:v;let h=f++,_=!t.paused,ee=i.kind!==`audio`&&S(t),x=ie(t);await ne(x,0,o,e=>{t.volume=re(e)}),t.pause(),b.src=s,b.currentTime=0,b.muted=t.muted,b.volume=0,g.style.opacity=`0`,c(),g.hidden=!1,g.classList.toggle(`pux-ad--audio`,i.kind===`audio`);let te=i.kind===`audio`;g.style.background=te?`rgb(0 0 0 / 0.35)`:`#000`,v.style.display=te?`none`:``,e.classList.add(`pux-player--ad`),n.onBreakStart?.({url:s,index:h});let oe=!1,C=e=>{p&&(oe=e,ne(1,0,o,e=>{g.style.opacity=String(e),b.volume=re(x*e)}).then(async()=>{ee&&S(b)&&await l(ae(t)),T(),n.onBreakEnd?.({url:s,index:h,skipped:oe}),!m&&(t.volume=0,_&&t.play().catch(()=>{}),ne(0,x,o,e=>{t.volume=re(e)}))}))};function T(){clearTimeout(le),clearInterval(ue),b.removeEventListener(`ended`,ce),b.removeEventListener(`error`,E),w.removeEventListener(`click`,D),b.pause(),b.removeAttribute(`src`),b.load(),g.hidden=!0,g.classList.remove(`pux-ad--audio`),w.hidden=!0,e.classList.remove(`pux-player--ad`),p=!1}let ce=()=>C(!1),E=()=>{n.onError?.(Error(`advert failed to play: ${s}`)),C(!1)},D=()=>C(!0);b.addEventListener(`ended`,ce),b.addEventListener(`error`,E),w.addEventListener(`click`,D);let le=setTimeout(()=>C(!1),a),O=n.skipAfter,ue=0;if(typeof O==`number`&&O>=0){let e=O;w.hidden=!1;let t=()=>{let t=Math.ceil(e-b.currentTime);t>0?(w.disabled=!0,w.textContent=`Skip in ${t}`):(w.disabled=!1,w.textContent=`Skip ad`)};t(),ue=setInterval(t,250)}try{await b.play(),ee&&await l(b),await ne(0,1,o,e=>{g.style.opacity=String(e),b.volume=re(x*e)})}catch(e){n.onError?.(e),t.volume=re(x),C(!1)}}let E=()=>T(),D=()=>{d=r(),h||(h=!0,ce())},le=()=>{T(),d=null},O=()=>{for(let e of[v,y])e.muted=t.muted,e.volume=ie(t)};return t.addEventListener(`timeupdate`,E),t.addEventListener(`play`,D),t.addEventListener(`pause`,le),t.addEventListener(`volumechange`,O),{play(){return ce()},destroy(){m=!0,S(b)&&l(ae(t)),t.removeEventListener(`timeupdate`,E),t.removeEventListener(`play`,D),t.removeEventListener(`pause`,le),t.removeEventListener(`volumechange`,O),v.pause(),y.pause(),g.remove()},get playing(){return p}}}var T=[`active`,`trialing`];function ce(e,t,n=new Date){if(!e?.length)return!1;let r=new Set(T);return e.some(e=>{if(e.product!==t||!r.has(e.status))return!1;let i=e.period?.end?Date.parse(e.period.end):NaN;if(Number.isFinite(i)&&i<n.getTime())return!1;let a=e.period?.start?Date.parse(e.period.start):NaN;return!(Number.isFinite(a)&&a>n.getTime())})}async function E(e){let t=null;try{t=await e.entitlements()??null}catch{return e.ads}let n=e.now?.()??new Date;return ce(t,e.product,n)?null:e.ads}var D=600,le=`https://crawlproof.com/api/ads/stream`,O=`nixamp.pro`;function ue(){let e=document.querySelector(`#video`);return e&&!e.hidden&&e.currentSrc&&!e.paused?`video`:`audio`}async function de(){try{let e=await fetch(`/api/entitlements`,{credentials:`include`,headers:{accept:`application/json`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t)?t:t.entitlements??[]}catch{return[]}}var fe=`7e0ea02c-c40f-4cdd-b4d3-93b2baca8f2c`;function pe(e){let t=new URLSearchParams(e),n=t.get(`ads`),r=Number(t.get(`adsEvery`)),i=t.get(`adNow`);return{enabled:i===null?n===null?null:n!==`0`&&n!==`false`:!0,everySeconds:Number.isFinite(r)&&r>0?Math.min(3600,Math.max(5,r)):null,adUrl:he(t.get(`adUrl`)),now:i!==null&&i!==`0`&&i!==`false`}}function me(e=location.search){return pe(e).now}function he(e){if(!e)return null;try{let t=new URL(e,location.origin);return t.protocol===`https:`?t.toString():null}catch{return null}}var k=null;function A(e){if(k)try{let t=`${k.endpoint}?d=${encodeURIComponent(k.decision)}&t=${encodeURIComponent(e)}&s=player`;new Image().src=t}catch{}}async function ge(e={},t=location.search){let n=pe(t);if(n.enabled===!1)return null;let r={everySeconds:n.everySeconds??e.everySeconds??D,next:async()=>{if(n.adUrl)return{url:n.adUrl};try{let t=`${le}?slot=${encodeURIComponent(e.slot??fe)}&kind=${ue()}`,n=await fetch(t,{headers:{accept:`application/json`}});if(!n.ok)return null;let r=await n.json();return r.url?(k=r.decisionId&&r.eventsUrl?{decision:r.decisionId,endpoint:r.eventsUrl,url:r.url}:null,{url:r.url,kind:r.kind}):null}catch{return null}},onBreakStart:e=>{k&&k.url!==e.url&&(k=null),A(`start`)},onBreakEnd:e=>{A(e.skipped?`abandon`:`complete`),k=null},onError:e=>{A(`error`),k=null,console.warn(`advert failed`,e)}};return n.enabled===!0?r:e.paid===!0?null:E({product:O,entitlements:de,ads:r})}var j={"no-window":`Push notifications are only available in a browser.`,"insecure-context":`Push notifications need a secure (https://) connection.`,"no-service-worker":`This browser does not support service workers, which push notifications need.`,"ios-needs-install":`On iPhone and iPad, add this site to your Home Screen (Share, then "Add to Home Screen") and open it from there to get notifications.`,"no-push-manager":`This browser does not support push notifications.`,"no-notification":`This browser does not support notifications.`,denied:`Notifications are blocked for this site. Allow them in your browser’s site settings, then try again.`,"no-server-key":`Push notifications are not set up on this server yet.`};function _e(e){let t=e?.userAgent??``;return/iPad|iPhone|iPod/.test(t)||/Macintosh/.test(t)&&(e?.maxTouchPoints??0)>1}function ve(e){return e?.navigator?.standalone===!0||typeof e?.matchMedia==`function`&&e.matchMedia(`(display-mode: standalone)`).matches}function ye(e=globalThis){let t=e,n=e?.navigator,r=e=>({supported:!1,reason:e,message:j[e],permission:be(t)});return!t||!n?r(`no-window`):t.isSecureContext===!1?r(`insecure-context`):`serviceWorker`in n?`PushManager`in t?`Notification`in t?t.Notification.permission===`denied`?r(`denied`):{supported:!0,reason:null,message:null,permission:t.Notification.permission}:r(`no-notification`):r(_e(n)&&!ve(t)?`ios-needs-install`:`no-push-manager`):r(`no-service-worker`)}function be(e){return e&&`Notification`in e?e.Notification.permission:`unsupported`}var xe=class extends Error{constructor(e,t){super(t??j[e]??e),this.name=`PushError`,this.reason=e}},M=new Map;async function Se({url:e=`/api/push/vapid-public-key`,fetch:t=globalThis.fetch}={}){if(M.has(e))return M.get(e);let n=await t(e,{headers:{accept:`application/json`}});if(!n.ok)throw new xe(`no-server-key`);let r=(await n.text()).trim(),i=r;try{i=JSON.parse(r).publicKey??``}catch{}if(!i||!/^[A-Za-z0-9_-]{80,100}={0,2}$/.test(i))throw new xe(`no-server-key`);return M.set(e,i),i}function Ce(e){let t=e+`=`.repeat((4-e.length%4)%4),n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function we(e,t){if(!e||!t)return!1;let n=new Uint8Array(e);if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}async function Te({serviceWorkerUrl:e,scope:t,env:n}){let r=n.navigator.serviceWorker;return await r.getRegistration(t)||await r.register(e,t?{scope:t}:void 0),r.ready}async function Ee(e={}){let t=e.env??globalThis,n=e.fetch??t.fetch?.bind(t)??globalThis.fetch,r=ye(t);if(!r.supported)throw new xe(r.reason);if((t.Notification.permission===`granted`?`granted`:await t.Notification.requestPermission())!==`granted`)throw new xe(`denied`);let i=Ce(e.vapidPublicKey||await Se({url:e.vapidKeyUrl,fetch:n})),a=await Te({serviceWorkerUrl:e.serviceWorkerUrl??`/sw.js`,scope:e.scope,env:t}),o=await a.pushManager.getSubscription();o&&!we(o.options?.applicationServerKey,i)&&(await o.unsubscribe(),o=null),o??=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:i});let s=typeof o.toJSON==`function`?o.toJSON():o;if(e.save&&await e.save(s),e.saveUrl){let t=await n(e.saveUrl,{method:`POST`,headers:{"content-type":`application/json`,...e.headers??{}},body:JSON.stringify(s),credentials:`include`});if(!t.ok)throw new xe(`save-failed`,`Could not save the subscription (${t.status})`)}return s}async function De({scope:e,env:t=globalThis}={}){let n=ye(t);if(!n.supported&&n.reason!==`denied`)return null;let r=await(await t.navigator.serviceWorker.getRegistration(e))?.pushManager.getSubscription();return r?r.toJSON():null}async function Oe({scope:e,removeUrl:t,headers:n,env:r=globalThis,fetch:i}={}){let a=await(await r.navigator?.serviceWorker?.getRegistration(e))?.pushManager.getSubscription();if(!a)return!1;let o=a.endpoint;return await a.unsubscribe(),t&&await(i??r.fetch.bind(r))(t,{method:`DELETE`,headers:{"content-type":`application/json`,...n??{}},body:JSON.stringify({endpoint:o}),credentials:`include`}).catch(()=>void 0),!0}var N=new Map;function ke(e,t,n){let r=N.get(e);r||(r=new Map,N.set(e,r)),r.set(t,n),n()}function P(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return ke(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){N.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function F(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return ke(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){N.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var Ae=[`aria-label`,`title`,`placeholder`,`data-title`],je=[`[data-i18n]`,...Ae.map(e=>`[data-i18n-${e}]`)].join(`,`);function Me(e){let t=[...e.querySelectorAll(je)];e instanceof HTMLElement&&e.matches(je)&&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;ke(e,`text`,()=>{if(e.textContent!==n){N.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=p(t),e.textContent!==n&&(e.textContent=n)})}for(let t of Ae){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);ke(e,t,()=>{if(e.getAttribute(t)!==r){N.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=p(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function Ne(){document.documentElement.lang=f.language,document.documentElement.dir=f.direction;for(let[e,t]of N){if(!e.isConnected){N.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=f.language}var Pe=0;async function Fe(e){let t=++Pe;try{if(!await f.setLanguage(e)||t!==Pe)return;try{localStorage.setItem(i,f.language)}catch{}window.nixampLanguage?.set(f.language).catch(()=>{})}catch{Ne()}}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`,()=>{Fe(e.value)});Me(document),Ne(),f.onChange(Ne),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&Me(e);for(let e of N.keys())e.isConnected||N.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 Le={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 Re(e,t){e.innerHTML=Le[t]}function ze(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 Be(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function Ve(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var He=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function Ue(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&He.has(e.slice(n+1).toLowerCase())}function I(){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 We=new WeakMap;function Ge(e,t=!0){let n=e.contains(document.activeElement);We.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function L(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){We.delete(e),e.replaceChildren(...t);return}let n=We.has(e);if(We.set(e,t),n)return;let r=()=>{let t=We.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}We.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var Ke=new WeakMap,qe=new WeakSet;function Je(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?Ke.set(e,t):Ke.delete(e),qe.has(e))return;qe.add(e);let a=()=>{let t=Ke.get(e);t&&Je(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function Ye(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 Xe(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 Ze(e,t,n=`Live`){let r=e[t];if(!r){let e=Ye(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${Ye(r.title)}`:Ye(r.title),a=Xe(r.folder??``),o=Xe(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}}function Qe(e,t=160){let n=e.replace(/[-]/g,` `).trim();if(n.length<=t)return n;let r=n.split(/\s›\s|[\\/]/).map(e=>e.replace(/_+/g,` `).trim()).filter(Boolean),i=Ye(r.pop()??``);if(r.length===0)return $e(i,t);let a=r.shift(),o=e=>[a,...e,i].join(` › `),s=[];for(let e=r.length-1;e>=0&&!(o([r[e],...s]).length>t);--e)s.unshift(r[e]);let c=o(s);if(c.length<=t)return c;let l=t-i.length-3;return l>=12?`${$e(a,l)} › ${i}`:$e(i,t)}function $e(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=e[t-1]===` `?n.length:n.lastIndexOf(` `);return`${(r>t/2?n.slice(0,r):n).trimEnd()}…`}var et=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`]),tt=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function nt(e){let t=e.lastIndexOf(`.`);return t>0&&tt.has(e.slice(t+1).toLowerCase())}function R(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&et.has(e.slice(n+1).toLowerCase())}function rt(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function it(e){return e.filter(e=>R(e.name,e.type)).sort((e,t)=>rt(at(e),at(t))).map(e=>({title:Ve(e.name),artist:``,album:z(at(e)),duration:0,url:URL.createObjectURL(e),video:Ue(e.name,e.type),objectUrl:!0,...nt(e.name)?{kind:`mpegts`}:{}}))}function at(e){return e.webkitRelativePath||e.name}function z(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function ot(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var st=2048;function B(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 ct(e,t){return e||t===`hls`||t===`mpegts`}var lt=class{elements;handlers;attach;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;ads=null;adOptions=null;adRoot=null;frequencies=new Uint8Array;analysable=!0;constructor(e,t,n=b){this.elements=e,this.handlers=t,this.attach=n,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.attached||this.attached.engine===`native`)&&this.handlers.onError(ut(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}enableAds(e,t){this.adRoot=t?e:null,this.adOptions=t,this.rebindAds()}get adPlaying(){return this.ads?.playing??!1}async playAdNow(){await this.ads?.play()}rebindAds(){this.ads?.destroy(),this.ads=null,this.adOptions&&this.adRoot&&(this.ads=w(this.adRoot,this.active,this.adOptions))}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=st,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`:g({src:e.url})),r=ct(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||B(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.rebindAds()),this.attached?.destroy(),this.attached=null;try{this.attached=await this.attach(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.onBusy?.(!0)}})}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:`)||B(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}if(e instanceof Error&&e.name===`AbortError`&&this.attached?.engine!==`native`)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 ut(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 dt(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function ft(e,t){return{...t,tracks:t.tracks??e.tracks}}function pt(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 mt(e,t,n=``){let r=`${e===``?``:pt(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function ht(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 gt(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:pt(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var _t=null;function vt(e){if(!e&&_t!==null)return _t;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||(_t=n),n}catch{return!1}}function yt(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return mt(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function bt(e){if(typeof e!=`object`||!e)return null;let t=e,n=dt(),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 xt(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var St=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return xt(this.base,e)}url(e){let t=mt(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}=gt(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(mt(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=bt(Ct(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(mt(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=bt(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=vt()){return yt(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function Ct(e){try{return JSON.parse(e)}catch{return null}}async function wt(e,t,n=``){try{let r=await fetch(mt(e,`/api/state`,n),{signal:t});return r.ok?bt(await r.json()):null}catch{return null}}function Tt(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 Et(e,t=``,n){let r;try{r=await fetch(mt(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 Dt(e,t,n=``){try{let r=await fetch(mt(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 Ot(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 kt=.14,At=.02;function jt(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 Mt(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 Nt(e,t,n=kt){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Pt(e,t,n=At){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function Ft(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 It(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 Lt(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function Rt(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 zt(e,t={}){let n=e.data,r=It(n.away,n.awayScore),i=It(n.home,n.homeScore),a=Lt(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=Rt(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 Bt=`nixamp.tv`,Vt=/\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 Ht(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?Ut(r):/\bSilk\b/.test(e)&&n===0?!0:Vt.test(e):Ut(i)}function Ut(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Wt(e){return e?12:100}function Gt(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 Kt=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,qt=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,Jt=/\.m3u8(\?.*)?$/i,Yt=/\.(m3u|pls)(\?.*)?$/i;function Xt(e){try{let t=new URL(e);return qt.test(t.pathname+t.search)}catch{return!1}}function Zt(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 Qt(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||Zt(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(!Kt.test(a)&&!qt.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 $t(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 en(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=$t(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 Yt.test(o)?{kind:`list`,url:n.toString(),label:Zt(n.toString())}:Kt.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:qt.test(o)||Jt.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var tn=`nixamp.panels`;function nn(){return{order:[],placement:{},collapsed:[],closed:[]}}var V=/^[a-z][a-z0-9-]{0,63}$/,rn=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function H(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&V.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function an(e){if(!e)return nn();let t;try{t=JSON.parse(e)}catch{return nn()}if(!t||typeof t!=`object`||Array.isArray(t))return nn();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))V.test(e)&&typeof t==`string`&&rn.test(t)&&(r[e]=t);let i=e=>{let t=H(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 on(e){return JSON.stringify(e)}function sn(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 cn(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function ln(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}function un(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 dn(e,t){return Object.assign(Error(e),{status:t})}var fn=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}},pn=class{options;tracker=new fn;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 dn(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=this.options.sourceLanguage?.()??``,s=new Uint8Array(ln(i?t.samples:t.samples.slice(-8e4))),c=this.options.hear?await this.options.hear(s,{speakers:i,language:o,signal:r}):await this.json(mn(i?this.options.paths?.speakers??`/api/v1/speech/speakers`:this.options.paths?.transcribe??`/api/v1/speech/transcribe?live=1`,o),{method:`POST`,headers:{"content-type":`audio/wav`},body:s},r);if(e!==this.generation)return;this.recognitionFailures=0;let l=c.language,u=[];if(i){let e=this.tracker.reconcile(c.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=c.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),s=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),c=[],d=()=>{c.length&&(u.push({channel:this.options.channel(),at:t.at+c[0].start*1e3,until:t.at+c.at(-1).end*1e3,text:c.map(e=>e.text).join(` `).trim(),language:l,speaker:o.id,voiceProfile:a.profile}),c=[])};for(let e of s)c.length&&e.start-c.at(-1).end>=.45&&d(),c.push(e),(/[.!?。!?]$/.test(e.text)||c.map(e=>e.text).join(` `).length>=400)&&d();c.length&&(i<r.length-1||t.until-(t.at+c.at(-1).end*1e3)>=350||t.until-(t.at+c[0].start*1e3)>=3e3)&&d()}}else c.text&&(u=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:c.text,language:l}]);if(!u.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...u.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:u,language:l,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!un(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 dn(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]),t=n.map(e=>e.text),a=this.options.translate?await this.options.translate(t,r,i,e):await this.json(this.options.paths?.translate??`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:t,from:r,to:i})},e);if(a.texts.length!==n.length||a.texts.some(e=>!e.trim()))throw dn(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((e,t)=>({...e,original:e.text,sourceLanguage:r,language:i,text:a.texts[t]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>hn(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!un(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 mn(e,t){return/^[a-z]{2,3}$/.test(t)?`${e}${e.includes(`?`)?`&`:`?`}language=${t}`:e}function hn(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 gn=16e3,_n=3e4;function vn(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function yn(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var bn=`nixamp.captions`,xn=`nixamp.captions.native-v2.language`,Sn=[{code:``,label:`Original (auto-detect)`},...r];function Cn(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return Sn.some(e=>e.code===t)?t:``}catch{return``}}function wn(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function Tn(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function En(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 Dn(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 On(e){try{return e(bn)!==`off`}catch{return!0}}function kn(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var An=`live-translate-audio-tap`,jn=`// The render thread copies small mono blocks. All networking stays off it.
2
2
  class LiveTranslateAudioTap extends AudioWorkletProcessor {
3
3
  constructor() { super(); this.block = new Float32Array(2048); this.at = 0; }
4
4
  process(inputs) {
@@ -19,4 +19,4 @@ class LiveTranslateAudioTap extends AudioWorkletProcessor {
19
19
  registerProcessor("live-translate-audio-tap", LiveTranslateAudioTap);
20
20
  `,Mn=null;function Nn(){return Mn??=URL.createObjectURL(new Blob([jn],{type:`text/javascript`})),Mn}var Pn=new WeakMap,Fn=class{take;options;tap=null;generation=0;constructor(e,t={}){this.take=e,this.options=t}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(Pn.has(e)||Pn.set(e,e.audioWorklet.addModule(this.options.workletUrl??Nn()).catch(t=>{throw Pn.delete(e),t})),await Pn.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,this.options.workletUrl?this.options.processor??`nixamp-audio-tap`:An);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}},In=12e3,Ln=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>In}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 dn((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 dn(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!un(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`)}},Rn=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t,n={}){this.stop();let r=new AbortController;this.controller=r;let i=async()=>{let i=new AbortController,a=setTimeout(()=>i.abort(),12e3),o=await(this.options.fetcher??fetch)(this.options.path??`/api/translation/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n,source:e,language:t}),signal:AbortSignal.any([r.signal,i.signal])}).finally(()=>clearTimeout(a));if(!o.ok||!o.body)throw dn((await o.json().catch(()=>({}))).error||`Live translation is unavailable.`,o.status);return o.body},a=await i();if(this.controller!==r){await a.cancel();return}this.consume(a,r,i)}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 dn(`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(!un(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(dn(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw dn(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
21
21
 
22
- `))>=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`){if(this.options.error?.(e))return;throw dn(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=`${this.options.scheme??`live-translate`}:${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(dn(`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)}});if(this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t,e),e.audio===!1){let e=this.clips.get(t);e.ended=!0,e.taken=!0,e.controller.close()}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)}},zn=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,Bn=class extends Fn{constructor(e){super(e,{workletUrl:zn,processor:`nixamp-audio-tap`})}},Vn=3,Hn=1,Un=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*Hn: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*Vn: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?Hn:Vn):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?Hn:Vn):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}},Wn=class extends Rn{constructor(e){super({path:`/api/v1/speech/shared`,scheme:`nixamp-shared`,...e})}},Gn=e=>new Intl.NumberFormat(f.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),U=e=>document.getElementById(e),Kn=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=U(`translation-purchase`);plan=U(`translation-plan`);coin=U(`translation-coin`);buy=U(`translation-checkout`);note=U(`translation-purchase-note`);checkoutLink=U(`translation-checkout-link`);constructor(e){this.options=e,U(`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})}),U(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),U(`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=`$`,F(e,`title`,()=>p(`Buy translated audio`)),F(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 P(t,()=>`${e.name} · ${Gn(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${p(`Audio credit`)}: ${Gn(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?` · ✓`:``}`:``;P(U(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),P(U(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),P(U(`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.`:``),U(`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));U(`translation-plan-description`).textContent=`${Gn(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,U(`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,U(`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}}},qn=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,Jn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,Yn=/\s+(?:vs\.?|v\.?|at|@)\s+/i,Xn=/^(?: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 Zn(e){let t=e.replace(Jn,``).replace(Jn,``).trim().split(Yn);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!Xn.test(t)})}function Qn(e){let t=String(e??``).trim();return t===``?!1:Zn(t.replace(qn,``))||Zn(t)}function $n(e,t){if(e.dataset.longStringScroller===`true`)return;e.dataset.longStringScroller=`true`,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=!1,o=null,s=()=>{n=0;let c=matchMedia(`(prefers-reduced-motion: reduce)`).matches?r:i+(r-i)*.22;if(i=Math.abs(r-c)<.5?r:c,t.style.setProperty(`--path-shift`,`${i}px`),Math.abs(r-i)>=.5){n=requestAnimationFrame(s);return}a&&(a=!1,delete t.dataset.pan,t.style.removeProperty(`--path-shift`),o=setTimeout(()=>{o=null,e.style.removeProperty(`min-height`)},280))},c=()=>{n||=requestAnimationFrame(s)};e.addEventListener(`pointerenter`,n=>{n.pointerType===`mouse`&&matchMedia(`(hover: hover) and (pointer: fine)`).matches&&(o!==null&&(clearTimeout(o),o=null),e.style.minHeight=`${e.getBoundingClientRect().height}px`,a=!1,t.dataset.pan=`true`)}),e.addEventListener(`pointermove`,n=>{if(t.dataset.pan!==`true`)return;let i=getComputedStyle(e),a=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),o=Math.max(0,t.scrollWidth-(e.clientWidth-a));if(o<=0)return;let s=e.getBoundingClientRect(),l=Math.max(0,Math.min(1,(n.clientX-s.left)/Math.max(1,s.width)));if(l<=.02)r=0;else if(l>=.98)r=-o;else{let e=l*l*(3-2*l);r=-o*e}c()}),e.addEventListener(`pointerleave`,()=>{r=0,a=!0,c()})}var er=`nixamp.remote`,tr=`nixamp.defaultServer`,nr=`nixamp.volume`,rr=`nixamp.listenHere`,ir=1e4,ar=!1;function W(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function or(){let e=new URLSearchParams(location.search).get(`embed`)===`1`,t=``;function n(e,n){let r=new URL(e instanceof Request?e.url:String(e),location.href);if(!t||r.origin!==location.origin||!r.pathname.startsWith(`/api/v1/`))return globalThis.fetch(e,n);let i=new Headers(n?.headers??(e instanceof Request?e.headers:void 0));return i.set(`authorization`,`Bearer ${t}`),globalThis.fetch(e,{...n,headers:i})}document.body.classList.toggle(`classroom-embed`,e);let r=null;try{r=localStorage.getItem(Bt)}catch{}let i=Ht(navigator.userAgent,location.search,navigator.maxTouchPoints,r);if(document.body.classList.toggle(`tv`,i),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Bt,i?`1`:`0`)}catch{}let a=document.getElementById(`tv-toggle`);a&&(P(a,()=>i?`TV mode: on`:p(`TV mode`)),a.title=i?`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.`,a.addEventListener(`click`,()=>{try{localStorage.setItem(Bt,i?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let o=Wt(i),s={status:W(`status`),source:W(`source`),install:W(`install`),video:W(`video`),audio:W(`audio`),title:W(`title-line`),album:W(`album-line`),meta:W(`meta-line`),metaBlurb:W(`meta-blurb`),liveLine:W(`live-line`),downloadNow:W(`download-now`),wayInHere:W(`way-in-here`),embed:W(`embed`),embedFrame:W(`embed-frame`),linkForm:W(`link-form`),linkUrl:W(`link-url`),linkServer:W(`link-server`),linkGoLive:W(`link-go-live`),goLiveNow:W(`go-live-now`),elapsed:W(`elapsed`),total:W(`total`),seek:W(`seek`),fullscreen:W(`fullscreen`),copyNow:W(`copy-now`),copyNixamp:W(`copy-nixamp`),schoolLive:W(`school-live`),canvas:W(`spectrum`),glyphs:W(`glyphs`),levels:W(`levels`),playlist:W(`playlist`),livePlaylist:W(`live-playlist`),livePlaylistPanel:W(`live-playlist-panel`),playlistPager:W(`playlist-pager`),crumbs:W(`crumbs`),filter:W(`filter`),playlistTitle:W(`playlist-panel`),note:W(`note`),linkNote:W(`link-note`),logList:W(`log-list`),files:W(`files`),folder:W(`folder`),remoteUrl:W(`remote-url`),remoteServer:W(`remote-server`),remoteForm:W(`remote-form`),remoteState:W(`remote-state`),disconnect:W(`disconnect`),browse:W(`browse`),panelsToggle:W(`panels-toggle`),panelsPanel:W(`panels-panel`),panelsList:W(`panels-list`),panelsSave:W(`panels-save`),panelsReset:W(`panels-reset`),accountForm:W(`account-form`),accountEmail:W(`account-email`),accountPassword:W(`account-password`),accountSubmit:W(`account-submit`),accountToggle:W(`account-toggle`),accountForgot:W(`account-forgot`),accountProviders:W(`account-providers`),accountPanel:W(`account-panel`),accountElsewhere:W(`account-elsewhere`),welcome:W(`welcome`),welcomeCreate:W(`welcome-create`),welcomeBrowse:W(`welcome-browse`),welcomeHide:W(`welcome-hide`),accountSignOut:W(`account-signout`),accountNote:W(`account-note`),personaForm:W(`persona-form`),personaHandle:W(`persona-handle`),personaVoice:W(`persona-voice`),personaProfile:W(`persona-profile`),personaNote:W(`persona-note`),adminPanel:W(`admin-panel`),adminNote:W(`admin-note`),adminSaid:W(`admin-said`),adminConnections:W(`admin-connections`),publishPanel:W(`publish-panel`),publishNote:W(`publish-note`),publishList:W(`publish-list`),adminRestream:W(`admin-restream`),adminReplace:W(`admin-replace`),adminSource:W(`admin-source`),adminName:W(`admin-name`),adminAdd:W(`admin-add`),homeNote:W(`home-note`),loadHome:W(`load-home`),directory:W(`directory`),recentNote:W(`recent-note`),recentList:W(`recent-list`),followingNote:W(`following-note`),followingList:W(`following-list`),serversPanel:W(`servers-panel`),serversNote:W(`servers-note`),serversList:W(`servers-list`),favoritesPanel:W(`favorites-panel`),favoritesNote:W(`favorites-note`),favoritesList:W(`favorites-list`),favHere:W(`fav-here`),partyRoom:W(`party-room`),partyTitle:W(`party-title`),partyMeta:W(`party-meta`),partyRoomNote:W(`party-note`),partyWatch:W(`party-watch`),partyCopy:W(`party-copy`),partyEnd:W(`party-end`),partyChat:W(`party-chat`),partyChatForm:W(`party-chat-form`),partyChatInput:W(`party-chat-input`),partyChatSend:W(`party-chat-send`),partyChatNote:W(`party-chat-note`),partiesPanel:W(`parties-panel`),partiesNote:W(`parties-note`),partiesList:W(`parties-list`),partyForm:W(`party-form`),partyCode:W(`party-code`),partyJoin:W(`party-join`),connectionsNote:W(`connections-note`),connectionsList:W(`connections-list`),catalogsPanel:W(`catalogs-panel`),catalogsNote:W(`catalogs-note`),catalogsForm:W(`catalogs-form`),catalogSource:W(`catalog-source`),catalogName:W(`catalog-name`),catalogsList:W(`catalogs-list`),catalogsCrumbs:W(`catalogs-crumbs`),catalogsFilter:W(`catalogs-filter`),catalogsEntries:W(`catalogs-entries`),notifyPanel:W(`notify-panel`),notifyNote:W(`notify-note`),notifyWeb:W(`notify-web`),notifyEmail:W(`notify-email`),notifySms:W(`notify-sms`),notifyPhone:W(`notify-phone`),notifyPhoneForm:W(`notify-phone-form`),notifyPhoneNote:W(`notify-phone-note`),directoryNote:W(`directory-note`),directoryList:W(`directory-list`),sharePanel:W(`share-panel`),trollboxPanel:W(`trollbox-panel`),trollboxNote:W(`trollbox-note`),trollboxList:W(`trollbox-list`),trollboxForm:W(`trollbox-form`),trollboxInput:W(`trollbox-input`),trollboxMic:W(`trollbox-mic`),trollboxEdit:W(`trollbox-edit`),trollboxEditLabel:W(`trollbox-edit-label`),transcriptPanel:W(`transcript-panel`),transcriptNote:W(`transcript-note`),transcriptOn:W(`transcript-on`),transcriptLanguage:W(`transcript-language`),transcriptAudio:W(`transcript-audio`),transcriptVoiceSettings:W(`transcript-voice-settings`),transcriptBackground:W(`transcript-background`),transcriptBackgroundLevel:W(`transcript-background-level`),transcriptBackgroundValue:W(`transcript-background-value`),transcriptAudioNote:W(`transcript-audio-note`),transcriptSpeakers:W(`transcript-speakers`),transcriptList:W(`transcript-list`),subtitle:W(`subtitle`),shareNote:W(`share-note`),shareLink:W(`share-link`),shareCopy:W(`share-copy`),sharePhone:W(`share-phone`),shareSend:W(`share-send`),liveControls:W(`live-controls`),goLive:W(`go-live`),stopLive:W(`stop-live`),shareTo:W(`share-to`),listenOnly:W(`listen-only`),listenHere:W(`listen-here`),volume:W(`volume`),volumeToggle:W(`volume-toggle`),prev:W(`prev`),playPause:W(`play-pause`),transport:W(`transport`),stop:W(`stop`),next:W(`next`),shareNow:W(`share-now`),refreshPlayer:W(`refresh-player`),appVersion:W(`app-version`)};s.appVersion.textContent=`nixamp 0.33.0`;let c=(e,t)=>{Re(e,t)};c(s.copyNixamp,`link`);let l=document.createElement(`a`);if(l.className=`button`,l.href=`#account-panel`,l.hidden=!0,P(l,()=>p(`Sign in`)),s.trollboxNote.after(l),e){let e=document.createElement(`div`);e.className=`classroom-caption-controls`,e.append(s.transcriptOn.closest(`label`),s.transcriptLanguage.closest(`label`)),s.transcriptPanel.prepend(e),s.transcriptPanel.classList.remove(`panel`,`col-b`),s.transcriptPanel.hidden=!1,document.querySelector(`.classroom-player`).append(s.transcriptPanel),document.querySelector(`#app`).append(s.trollboxPanel);let t=document.createElement(`dialog`);t.className=`classroom-sign-in`,F(t,`aria-label`,()=>p(`Sign in`));let n=document.createElement(`button`);n.type=`button`,n.className=`button`,P(n,()=>p(`Close`)),n.addEventListener(`click`,()=>t.close()),s.accountPanel.classList.remove(`panel`,`col-a`),t.append(n,s.accountPanel),document.body.append(t),l.addEventListener(`click`,e=>{e.preventDefault(),t.showModal()}),t.addEventListener(`close`,()=>{(l.hidden?s.trollboxList:l).focus({preventScroll:!0})})}let u=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,d=`local`,m=``,h=[],g=``,_=!0,v=``;function y(e){try{return new URL(e).origin}catch{return e}}let b=!1,ee=globalThis.location?.search??``,x=``,te=0,ne=new Map,re=e=>ne.get(K(e))??null;function ie(e,t){let n=n=>{b=n,x=``,s.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),s.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,c(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`,c(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:Y?`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=``,S=[],oe=0,C=dt(),se=`idle`,w=``,T=`Pick files, or connect to a nixamp running somewhere else.`,ce=!1,E=-1,D=null,le=0,O=null;function ue(e){return e?/^https?:\/\//i.test(e)?e:z.url(e):``}let de=0,fe=0,pe=!1,he=()=>!R.needsInteraction&&(fe>0||pe);async function k(e){fe+=1,V();try{return await e()}finally{--fe,V()}}let A=null,j=null,_e=``,ve=null,be=``,M=null,Se=null,Ce=0;function we(){s.embed.hidden||(s.embedFrame.src=`about:blank`),s.embed.hidden=!0}let Te=null,N=``,ke=null;function Ae(e,t,r=null,i=!1){let a=`${t}|${e}`;if(N=a,ke&&clearTimeout(ke),ke=null,!i){if(Te?.key===a)return;Te=null}if(d!==`remote`||e.trim()===``)return;let o=new URLSearchParams({name:e,kind:t});r&&o.set(`year`,String(r)),n(z.url(`/api/enrich?${o}`)).then(e=>e.ok?e.json():{match:null}).then(n=>{if(N!==a)return;Te={key:a,match:n.match??null},V();let i=Te.match;i?.kind===`fixture`&&Lt(i)!==`post`&&(ke=setTimeout(()=>{ke=null,!(N!==a||R.source===``&&!O)&&Ae(e,t,r,!0)},6e4))}).catch(()=>void 0)}let je=!1,Me=``,Ne=``,Pe=null,Fe=``,Ie=``,Le=``,Ve=Array(24).fill(0),He=Array(24).fill(0),Ue=[],I=()=>d===`remote`&&!s.listenHere.checked,We=()=>d===`remote`&&!s.adminPanel.hidden,Ke=!1,qe=()=>We()||d===`remote`&&Ke;function Xe(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:s.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function $e(){if(d!==`remote`||M)return null;if(A?.catalog&&A.entry)return{kind:`entry`,catalog:A.catalog,entry:A.entry};if(O)return{kind:`channel`,id:O.id,name:O.name};let e=C.tracks[B()];return e&&(R.source!==``||I())?{kind:`track`,index:B(),name:_t(e)}:null}async function et(e,t){t.disabled=!0;let r=e.kind===`entry`?e.entry.title:e.name;T=`Putting ${r} on the air…`,V();try{let i=``,a=``,o=!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`,s=await n(z.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),c=await s.json().catch(()=>({}));if(!s.ok){T=s.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:c.error??`${r} would not go on the air.`,V();return}a=e.kind===`channel`?e.id:c.channel??``,o=c.video!==!1,i=`channel:${a}`}if(We()&&(je?await n(z.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await Uo(!0)),await yo(),wo(),a!==``&&O?.id!==a){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 ko({id:a,name:r,video:o},!0,t)}let s=Lo(i),c=Me?` Call ${Ne||`the line`} and key ${Me} to talk about it.`:``;s===``?T=`${r} is on the air and you are watching it.${c}`:(await Io(s,t,`✓`),T=`${r} is on the air and you are watching it. Link copied.${c}`),V()}catch{T=`could not reach the server`,V()}finally{t.disabled=!1}}function tt(e,t=`Join party`){c(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);P(n,()=>` ${p(t)}`),e.append(n),F(e,`title`,()=>p(/join/i.test(t)?`Join live`:t))}tt(s.partyJoin);function nt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,c(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(),et(e(),n)}),n}let R=new lt({audio:s.audio,video:s.video},{readable:e=>z.owns(e),onTime:(e,t)=>{let n=S[oe];d===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),V()},onEnded:()=>{Ao()||or()||It()||d===`remote`&&E<0&&!I()||Kt(1)},onState:()=>V(),onBusy:e=>{pe!==e&&(pe=e,V())},onError:e=>{if(!Ao()&&!(Ce!==0&&Date.now()-Ce<2e3)){if(Se&&e===`this browser cannot play that format`){let e=Se.url;if(Se=null,Ce=Date.now(),qe()){T=`That site will not let a page play it directly; going live with it on ${m||`the server`} instead.`,V(),s.linkUrl.value=e,dr();return}T=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,V();return}T=e,V(),Do()}}}),rt=s.video.closest(`section`)??s.video.parentElement;rt&&(async()=>{if(R.enableAds(rt,await ge({},ee)),me(ee)){let e=()=>{rt.scrollIntoView({block:`center`}),R.playAdNow()};addEventListener(`pointerdown`,e,{once:!0}),addEventListener(`keydown`,e,{once:!0})}})();let at=()=>I()&&!R.jinglePlaying,z=new St({onSnapshot:e=>{let t=e.tracks!==void 0||C.index!==e.index;if(C=ft(C,e),x.startsWith(`track:`)&&C.tracks.length>0){let e=Number(x.slice(6));if(x=``,Number.isInteger(e)&&e>=0&&e<C.tracks.length){let t=te;Vt(e).then(()=>{t>0&&(R.seek(t),setTimeout(()=>R.seek(t),600))})}}at()&&(Ve=e.bars.length>0?e.bars:Ve,He=Pt(He,Ve)),V(),t&&j&&To(j)},onStatus:(e,t)=>{se=e,w=t??``,V()}}),st=()=>d===`remote`?C.tracks.length:S.length,B=()=>d===`remote`?I()||E<0?C.index:Math.min(E,Math.max(0,C.tracks.length-1)):oe,ct=()=>{let e=j?.server.nowPlaying||`Live`;return(!ve||ve.tracks!==C.tracks||ve.index!==C.index||ve.fallback!==e)&&(ve={tracks:C.tracks,index:C.index,fallback:e,value:Ze(C.tracks,C.index,e)}),ve.value},ut=()=>d===`remote`&&!O&&A?.kind===`live`,pt=()=>ut()?ct().fullTitle:vt(),_t=e=>{let t=Be(e);return e.folder?`${e.folder} / ${t}`:t},vt=()=>{if(O){let e=O.id,t=j?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||O.name}if(M)return M.label;if(ut())return ct().title;let e=d===`remote`?C.tracks[B()]:S[B()];return e?_t(e):p(`Nothing loaded.`)},yt=()=>{if(O)return`live on this server`;if(M)return`playing here, in this browser`;if(ut()){let{context:e,position:t}=ct();return[e,t,`live on ${m||`this server`}`].filter(Boolean).join(` · `)}return(d===`remote`?C.tracks[B()]:S[B()])?.album||`—`};function bt(){if(d!==`remote`||O===null&&A?.kind!==`live`){s.liveLine.hidden=!0,s.liveLine.replaceChildren(),delete s.liveLine.dataset.drawn;return}let e=m||`this server`,t=O?O.name:ct().fullTitle,n=[O?`Live on ${e}: `:`Live from ${e}, now playing: `,Wo(t)],r=O?j?.channels.find(e=>e.id===O?.id)?.code??``:je?Me:``;if(r){let e=Ne?document.createElement(`a`):Wo(`the line`);Ne&&(e.textContent=Ne,e.setAttribute(`href`,`tel:${Ne.replace(/[^+\d]/g,``)}`)),n.push(`. To talk about it, call `,e,` and key `,Wo(r),`.`)}let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);s.liveLine.dataset.drawn!==i&&(s.liveLine.dataset.drawn=i,s.liveLine.hidden=!1,s.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let xt=()=>I()?C.tracks[B()]?.duration??0:R.duration,Ct=()=>I()?C.position:R.position,kt=()=>I()?C.playing:R.playing;async function At(e){if(d===`remote`){if(I()){await z.send({type:`play`,index:e});return}await Vt(e);return}let t=S[e];t&&(oe=e,O=null,A={kind:`file`},await k(()=>R.load(t,!0)),qn(t.video),Jn(),V())}function It(){return!D||D.length<2?!1:(le=(le+1)%D.length,At(D[le]),!0)}function Rt(e){e.length!==0&&(D=[...e],le=0,At(D[0]))}async function Vt(e){let t=C.tracks[e];t&&(E=e,O=null,A={kind:`file`},Ae(t.title,`auto`),await k(()=>R.load({title:_t(t),artist:t.artist,album:t.album,duration:t.duration,url:z.media(e,0),video:t.video===!0,objectUrl:!1},!0)),qn(t.video===!0),Jn())}async function Ut(){if(R.needsInteraction){await R.play(),V();return}if(I()){await z.send({type:`toggle`});return}st()!==0&&(R.playing?R.pause():R.position>0?await R.play():await At(B()),V())}async function Kt(e){D=null;let t=st();if(t!==0){if(I()){await z.send({type:e>0?`next`:`prev`});return}await At((B()+e+t)%t)}}async function qt(){if(D=null,we(),M=null,Se=null,I()){await z.send({type:`stop`});return}O=null,A=null,R.stop(),Ve=Array(24).fill(0),He=[...Ve],V()}let Jt=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Yt=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],Zt=``;function $t(){let e=[],t=``,n=null,r=O?j?.channels.find(e=>e.id===O?.id):void 0;O&&r?.ended&&be!==O.id&&(be=O.id,Yr(`${O.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=R.source===``&&!O&&!(I()&&C.tracks[B()]);if(!i){O&&r?.ended?e.push(`ENDED`):O?e.push(A?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):A?.kind===`vod`?e.push(`ON DEMAND`):A?.kind===`live`?e.push(`LIVE`):d===`remote`&&I()?e.push(`ON THE SERVER`):e.push(`FILE`),!s.video.hidden&&s.video.videoWidth>0?e.push(`${s.video.videoWidth}×${s.video.videoHeight}`):s.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 ${ze(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),We()&&r.error&&e.push(r.error)):d===`remote`&&!O?(C.tracks[B()]&&st()>0&&e.push(`${ut()?`library track`:`track`} ${B()+1} of ${st()}`),I()&&j&&e.push(`${j.server.playing?`playing`:`stopped`} on ${m||`the server`}`)):d===`local`&&st()>0&&e.push(`track ${B()+1} of ${st()}`),A?.catalog!==void 0&&(A.kind===`channel`?O!==null:A.kind===`vod`&&R.source!==``)&&A?.catalog&&(e.push(A.entry?.group?`${A.catalog.name} › ${A.entry.group}`:A.catalog.name),t=A.entry?.logo??``),t===``&&O&&(t=ue(r?.art??O.art));let i=Te?.key===N?Te.match:null;if(i?.kind===`fixture`)n=zt(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(O&&A?.link){let t=``;try{t=new URL(A.link.url).hostname.replace(/^www\./,``)}catch{}e.push(A.link.extractor&&A.link.extractor!==`direct`&&A.link.extractor!==`generic`?`${A.link.extractor} · ${t}`:t||`link`)}je&&Me&&I()&&!O&&A?.kind!==`live`&&e.push(Ne?`☎ ${Ne} · key ${Me}`:`☎ code ${Me}`)}let a=Te?.key===N?Te.match:null,o=!i&&!n&&a?.summary?a.summary:``,c=e.map(e=>/^on air \d/.test(e)?`on air`:e),l=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${c.join(`|`)}|${o}`;if(l===Zt){let t=s.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}Zt=l,s.meta.hidden=e.length===0,s.metaBlurb.textContent=o,s.metaBlurb.hidden=o===``;let u=[];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)),u.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=a?.kind===`title`&&t===a.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),u.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,u.push(e)}s.meta.replaceChildren(...u)}function V(){let e=st(),t=kt(),n=he();P(s.status,()=>p(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),s.status.dataset.playing=n?`loading`:String(t),P(s.title,()=>vt()),s.title.classList.toggle(`with-context`,ut()),s.album.classList.toggle(`with-context`,ut()),(ut()||O)&&Jn(),bt(),$t(),s.goLiveNow.hidden=!qe()||O!==null||ut()||$e()===null;let r=t?`${pt()} · ${u}`:u;document.title!==r&&(document.title=r),s.copyNow.hidden=R.source===``,s.copyNixamp.hidden=aa()===``,s.schoolLive.hidden=aa()===``||!Ba||Y===``,s.shareNow.hidden=ia()===``,Li(),Xi(),s.downloadNow.hidden=!(O&&A?.link?.download),cr(),s.album.textContent=yt();let i=Ct(),a=xt();s.elapsed.textContent=ze(i),s.total.textContent=a>0?ze(a):`--:--`,ce||(s.seek.value=String(a>0?Math.round(i/a*1e3):0),s.seek.disabled=a<=0||I()),s.playPause.textContent=t?`❚❚`:`▶`,F(s.playPause,`aria-label`,()=>p(t?`Pause`:`Play`)),F(s.seek,`aria-valuetext`,()=>`${ze(R.position)} ${f.language===`en`?`of`:`/`} ${ze(R.duration)}`),F(s.volume,`aria-valuetext`,()=>f.number(Number(s.volume.value)/100,{style:`percent`})),F(s.playlistTitle,`data-title`,()=>d===`remote`?`Files on ${m||`this server`} (${e.toLocaleString(f.language)})`:`${p(`Playlist`)} (${f.number(e)})`),P(s.source,()=>d===`remote`?`connected · ${m||z.address.replace(/^https?:\/\//,``)||`—`}`:S.length>0?`local · ${S.length} files`:p(`no source`)),U(),P(s.remoteState,()=>d===`remote`?`${se}${w?` — ${w}`:``}`:p(`not connected`)),s.remoteState.dataset.status=d===`remote`?se:`idle`,s.disconnect.hidden=d!==`remote`;let o=R.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:d===`remote`&&C.note!==``?C.note:T;s.note.textContent=o,s.note.hidden=o===``,s.linkNote.textContent=o,s.linkNote.hidden=o===``,Yr(o),In(),s.glyphs.textContent=Ve.map(Yt).join(``);let[c,l]=at()?C.levels:R.levels();s.levels.textContent=Jt(c,l)}let rn=``,H=``,un=0;function dn(e){Ge(s.playlist),H=e,un=0,rn=``,In()}function fn(e,t,n,r,i){if(s.playlistPager.hidden=n<=1,n<=1){s.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{Ge(s.playlist),un=t,rn=``,In()}),i},o=document.createElement(`span`);o.className=`pager-where`,P(o,()=>`${r+1}–${i} of ${e.toLocaleString(f.language)}`),s.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),o,a(`Next ›`,t+1,`The page after this one`))}function mn(e){if(s.crumbs.hidden=!e,!e)return;let t=H===``?[]:H.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`,()=>dn(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))}),s.crumbs.replaceChildren(...r)}function hn(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 o=document.createElement(`button`);if(o.type=`button`,o.className=`row-main`,o.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),o.append(i,a),r.replaceChildren(o),o.addEventListener(`click`,t=>{t.stopPropagation(),dn(H===``?e:`${H}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,c(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),Rt(n)}),r.append(i)}return d===`remote`&&n.length>0&&qe()&&r.append(nt(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let An=null,jn=``,Mn=``,Nn=[],Pn=(e,t)=>{t.title=t.textContent??``,$n(e,t)};function Fn(e,t){let n=document.createElement(`span`);n.className=`name row-file`,n.textContent=e;let r=document.createElement(`span`);r.className=`row-path`,r.textContent=t;let i=document.createElement(`span`);i.className=`row-label`;let a=document.createElement(`span`);a.className=`row-value`,a.append(n);let o=document.createElement(`span`);return o.className=`row-value`,o.append(r),i.append(a),Pn(a,n),Pn(o,r),{label:i,pathView:o}}function In(){let e=(O?j?.channels.find(e=>e.id===O?.id):void 0)?.playlist,t=!!(O&&e?.length);s.livePlaylistPanel.hidden===t&&(s.livePlaylistPanel.hidden=!t);let n=t?O.id:``,r=t?e:[];if(Mn!==n||Nn.length!==r.length||Nn.some((e,t)=>e!==r[t])){Mn=n,Nn=r;let e=r.map((e,t)=>{let n=document.createElement(`li`);n.className=`row file-row live-file-row`,n.dataset.index=String(t);let r=document.createElement(`span`);r.className=`n`,r.textContent=String(t+1);let{label:i,pathView:a}=Fn(e.slice(e.lastIndexOf(`/`)+1),e),o=document.createElement(`span`);return o.className=`row-main`,o.append(i,r),n.append(o,a),n});L(s.livePlaylist,...e)}let i=d===`remote`?C.tracks:S,a=`${d}:${O?.id??``}:${H}:${s.filter.value}:${un}:${qe()}:${s.adminPanel.hidden}`;if(rn&&An===i&&jn===a){Rn();return}An=i,jn=a;let l=d===`remote`?C.tracks.map(e=>({name:Be(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):S.map(e=>({name:Be(e),seconds:e.duration,group:``,folder:``,remote:!1})),u=s.filter.value.trim().toLowerCase(),f=l.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>u===``||`${e.folder}/${e.name}`.toLowerCase().includes(u)),p=e=>u!==``||H===``||e===H||e.startsWith(`${H}/`),m=e=>e===H,h=e=>{let t=H===``?e:e.slice(H.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},g=new Map;for(let e of f){if(!p(e.folder)||m(e.folder))continue;let t=h(e.folder);t!==``&&g.set(t,(g.get(t)??0)+1)}let _=f.filter(e=>m(e.folder)&&p(e.folder)),v=[...g].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),y=Gt(v.length+_.length,un,o);un=y.page;let b=v.slice(y.from,y.to),ee=_.slice(Math.max(0,y.from-v.length),Math.max(0,y.to-v.length)),x=`${d}:${H}:${u}:${y.page}/${o}:${v.join(`,`)}:${_.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(x!==rn){rn=x,mn(u===``&&(v.length>0||H!==``)),fn(v.length+_.length,y.page,y.pages,y.from,y.to);let e=[];for(let[t,n]of b){let r=H===``?t:`${H}/${t}`,i=f.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(hn(t,n,i))}let t=``,n=_.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(zn(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 o=r.folder?`${r.folder} / ${r.name}`:r.name,{label:s,pathView:l}=Fn(r.name,r.folder?`${r.folder}/${r.name}`:r.name),u=document.createElement(`span`);u.className=`time`,u.textContent=r.seconds>0?ze(r.seconds):`--:--`;let f=document.createElement(`button`);f.type=`button`,f.className=`row-main`,f.setAttribute(`aria-label`,`Play ${o}${r.seconds>0?`, ${ze(r.seconds)}`:``}`),f.append(s,a,u),i.append(f);let p=document.createElement(`span`);p.className=`row-play-glyph`,c(p,`play`),i.append(p),d===`remote`&&qe()&&O===null&&!ut()&&i.append(nt(()=>({kind:`track`,index:r.index,name:o}),o)),i.classList.add(`file-row`),i.append(l),e.push(i)}L(s.playlist,...e)}Rn()}function Rn(){let e=O?j?.channels.find(e=>e.id===O?.id):void 0;if(e?.playlist&&e.playlist.length>0){let t=e.entry??0;for(let e of Array.from(s.livePlaylist.children)){let n=e,r=Number(n.dataset.index),i=Number.isInteger(r)&&r===t;n.classList.toggle(`selected`,i),n.classList.toggle(`playing`,i),n.classList.toggle(`live-file-current`,i),i?n.setAttribute(`aria-current`,`true`):n.removeAttribute(`aria-current`)}for(let n of Array.from(s.playlist.children)){let r=n,i=Number(r.dataset.index),a=C.tracks[i],o=a?`${a.folder?`${a.folder}/`:``}${Be(a)}`:``,s=!!o&&o===e.playlist[t];r.classList.toggle(`selected`,s),r.classList.toggle(`playing`,!1),s?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}return}for(let e of Array.from(s.livePlaylist.children)){let t=e;t.classList.remove(`selected`,`playing`,`live-file-current`),t.removeAttribute(`aria-current`)}let t=B(),n=kt();for(let e of Array.from(s.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 zn(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!==``&&!s.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(),Fo(t,n,()=>Vn(e),()=>In())}),t.append(n)}return t}async function Vn(e){try{let t=await n(z.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),r=await t.json();return G(t.ok?`Removed ${r.removed??0} tracks from ${e}.`:r.error??`that did not work`),t.ok}catch{return G(`could not reach the server`),!1}}function Hn(){let e=s.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(at())He=Pt(He,Ve);else{let e=R.read();e.length>0&&(Ue.length!==25&&(Ue=jt(24,e.length)),Ve=Nt(Ve,Mt(e,Ue)),He=Pt(He,Ve))}if(i){let t=getComputedStyle(document.documentElement);Ft(i,{width:e.width,height:e.height},Ve,He,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(kt()||R.jinglePlaying){s.glyphs.textContent=Ve.map(Yt).join(``);let[e,t]=at()?C.levels:R.levels();s.levels.textContent=Jt(e,t)}if(kt()){s.elapsed.textContent=ze(Ct());let e=xt();!ce&&e>0&&(s.seek.value=String(Math.round(Ct()/e*1e3)))}requestAnimationFrame(Hn)}let Gn=``;function U(){if(d!==`remote`){s.wayInHere.hidden=!0,Gn=``;return}let e=We()&&!b,t=ae||z.address,n=e?null:re(z.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Gn)return;Gn=r;let[i,a]=ie({name:m||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,s.wayInHere.replaceChildren(i,a),s.wayInHere.hidden=!1}function qn(e){s.video.hidden=!e,s.fullscreen.hidden=!e,we(),M=null,Se=null}function Jn(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=O?ue(j?.channels.find(e=>e.id===O?.id)?.art??O.art):``,t=JSON.stringify([vt(),yt(),e]);t!==_e&&(_e=t,navigator.mediaSession.metadata=new MediaMetadata({title:vt(),album:yt(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void Ut()),navigator.mediaSession.setActionHandler(`pause`,()=>void Ut()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void Kt(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void Kt(-1)))}document.addEventListener(`click`,()=>{R.resumeAfterInteraction().catch(()=>{})}),s.filter.addEventListener(`input`,()=>{un=0,rn=``,In()}),s.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())}),s.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(D=null,At(n))}),s.fullscreen.addEventListener(`click`,()=>{let e=s.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),s.prev.addEventListener(`click`,()=>void Kt(-1)),s.next.addEventListener(`click`,()=>void Kt(1)),s.stop.addEventListener(`click`,()=>void qt()),s.playPause.addEventListener(`click`,()=>void Ut());async function Yn(e){let t=en(e,Xe());if(!t){if(!qe()){T=d===`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.`,V();return}await sr(e);return}if(O=null,R.stop(),t.kind===`embed`){A={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},qn(!1),s.embedFrame.src=t.src,s.embed.hidden=!1,M={url:e,label:t.label,kind:`embed`},T=`Playing ${t.label} here, in this browser.`,V();return}if(t.kind===`list`){await Xn(e,t.label);return}A={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await k(()=>R.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),qn(t.video),M={url:e,label:t.label,kind:`direct`},T=`Playing ${t.label} here, in this browser.`,V()}async function Xn(e,t){T=`Reading ${t}…`,V();let r=``;try{let t=await n(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);r=await t.text()}catch(e){T=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,V();return}let i=Qt(r,e);if(i.entries.length===0){T=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,V();return}Se={url:e,title:i.title||t,entries:i.entries,at:0},await Zn()}async function Zn(){let e=Se,t=e?.entries[e.at];if(!e||!t)return;let n=Xt(t.url);A={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await k(()=>R.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),Se!==null&&(qn(n),M={url:e.url,label:e.title,kind:`direct`},Se=e,T=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,V())}function or(){let e=Se;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Zn(),!0)}async function sr(e){if(d!==`remote`){T=`Pick a server to go live on, or connect to one, to put a link on the air.`,V();return}T=`Asking ${m||`the server`} to fetch ${e}…`,V(),await k(async()=>{let t,r={};try{t=await n(z.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),r=await t.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!t.ok||!r.channel){T=r.error??`that link would not play.`;return}try{await n(z.url(`/api/channels/${encodeURIComponent(r.channel)}/keep`),{method:`POST`})}catch{}await ko({id:r.channel,name:r.name||e,video:r.video!==!1,art:r.art},!0,{kind:`channel`,link:{url:e,extractor:r.extractor??``,download:r.download===!0,live:r.live===!0,video:r.video!==!1}}),(r.entries??0)>1&&(T=`${r.name||e} is on the air: ${r.entries} entries, played in turn.`)}),V()}s.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.linkUrl.value.trim();t!==``&&Yn(t)});function cr(){let e=d===`remote`?z.address:``,t=h.filter(t=>y(t.url)!==y(e)),n=JSON.stringify({here:e,name:m,carries:_,others:t});if(n===g||document.activeElement===s.linkServer)return;g=n;let r=[];if(e!==``&&_){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${m||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}s.linkServer.replaceChildren(...r),s.linkServer.value=e!==``&&!_&&t[0]?t[0].url:``,s.linkServer.hidden=t.length===0}function lr(){let e=d===`remote`?y(z.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!h.some(t=>y(t.url)===e)){let n=document.createElement(`option`);n.value=z.address,n.textContent=m||e,t.push(n)}for(let e of h){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}s.remoteServer.replaceChildren(...t);let r=h.find(t=>y(t.url)===e);s.remoteServer.value=r?.url??``}async function ur(){try{let e=await n(`/api/directory`);if(!e.ok)return;h=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),cr(),lr()}catch{}}async function dr(){let e=s.linkUrl.value.trim()||M?.url||``;if(e===``){T=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,V();return}let t=s.linkServer.value;if(t!==``&&(d!==`remote`||y(t)!==y(z.address))){let n=h.find(e=>e.url===t)?.name??t;v=e,T=`Connecting to ${n} to go live with it…`,V(),fr(t);return}if(d!==`remote`){T=h.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,V();return}if(!_){T=`${m||`This server`} has no ffmpeg, so it cannot carry a link.`+(h.length>0?` Pick a server to go live on, beside the link.`:``),V();return}if(!qe()){T=`Sign in to nixamp.com to go live here, or use the server's control link.`,V();return}await sr(e)}function fr(e){let t=s.linkUrl.value.trim();b=!0,x=``,s.remoteUrl.value=e,s.remoteForm.requestSubmit(),s.linkUrl.value=t}s.linkGoLive.addEventListener(`click`,()=>{dr()}),s.linkServer.addEventListener(`change`,()=>{let e=s.linkServer.value;e!==``&&fr(e)}),s.downloadNow.addEventListener(`click`,()=>{let e=A?.link;if(!e||d!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(z.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),T=`Fetching it through the server; your browser will save it when it arrives.`,V()}),s.goLiveNow.addEventListener(`click`,()=>{let e=$e();e&&et(e,s.goLiveNow)}),s.seek.addEventListener(`input`,()=>{ce=!0}),s.seek.addEventListener(`change`,()=>{let e=xt();e>0&&R.seek(Number(s.seek.value)/1e3*e),ce=!1}),s.volume.addEventListener(`input`,()=>{let e=Number(s.volume.value)/100;R.volume=e,s.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),s.volumeToggle.textContent=e===0?`🔇`:`🔊`,F(s.volumeToggle,`aria-label`,()=>p(e===0?`Unmute`:`Mute`));try{localStorage.setItem(nr,String(e))}catch{}}),s.volumeToggle.addEventListener(`click`,()=>{let e=Number(s.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(nr));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}s.volume.value=e?String(t):`0`,s.volume.dispatchEvent(new Event(`input`))}),s.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let pr=e=>{e.addEventListener(`change`,()=>{let t=it(Array.from(e.files??[]));if(t.length===0){T=`Nothing playable in that selection.`,V();return}ot(S),S=t,oe=0,d=`local`,z.close(),Co(!1),T=``,At(0)})};pr(s.files),pr(s.folder),s.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.remoteUrl.value,{base:n,key:r}=gt(t);if(n===``){T=`That is not an address.`,V();return}(async()=>{se=`connecting`,V();let e=Ot(n);if(e){se=`error`,w=e,T=e,v=``,d=`local`,V();return}if(await Dt(n,void 0,r)===null){se=`error`;let e=Tt(n);w=e?`needs the server's name`:`not answering`,T=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,v=``,d=`local`,V();return}let i=await Et(n,r);if(i){se=`error`,w=i,T=i,v=``,d=`local`,V();return}d=`remote`,T=``;try{localStorage.setItem(er,t.trim())}catch{}z.connect(t),Co(!0),ba(),Er(),yo(),V()})()}),s.remoteServer.addEventListener(`change`,()=>{let e=s.remoteServer.value;e!==``&&(b=!1,x=``,s.remoteUrl.value=e,s.remoteForm.requestSubmit())});let mr=``,hr=null,gr=async(e=!1)=>{s.directory.hidden=!1,e||(s.directoryNote.textContent=`Looking for live streams…`,L(s.directoryList)),hr||=setInterval(()=>{!s.directory.hidden&&document.visibilityState===`visible`&&gr(!0)},ir);let t;try{let r=await n(`/api/directory`);if(!r.ok)throw Error(String(r.status));let i=await r.json();t=i.streams??[],h=t.map(e=>({name:e.name,url:e.url})),cr();let a=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:i.recent??[],me:Y});if(e&&a===mr)return;mr=a,kr(i.recent??[])}catch{e||(s.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(L(s.directoryList),t.length===0){s.directoryNote.textContent=`Nobody is streaming right now.`;return}s.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`),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`);a.className=`detail`;let o=[`${e.tracks.toLocaleString(f.language)} files to browse`];e.playing!==!1&&e.nowPlaying?o.push(`playing ${e.nowPlaying}`):o.push(`player idle`),e.code&&o.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),a.textContent=o.join(` · `),a.title=a.textContent,r.append(i,a);let l=e.admin??re(e.url),u=(t,n=``)=>{b=t,x=n,s.remoteUrl.value=t?e.url:l??e.url,s.directory.hidden=!0,document.body.classList.remove(`route-directory`),s.remoteForm.requestSubmit()},d=document.createElement(`ul`);d.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let o=e.lineup?.find(e=>e.name===t);if(o?.art&&/^https?:\/\//i.test(o.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=o.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}o?.about&&(r.title=o.about);let s=document.createElement(`button`);s.type=`button`,s.className=`icon`,c(s,`party`),s.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),s.title=`Join live: ${t} on ${e.name}`,s.addEventListener(`click`,()=>u(!0,`channel:${t}`));let f=document.createElement(`button`);f.type=`button`,f.className=`icon`,c(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:${o?.id??t}`)}`;f.addEventListener(`click`,e=>{e.stopPropagation(),Io(p,f,`✓`)});let m=document.createElement(`button`);m.type=`button`,m.className=`icon`,c(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(o?.id??t)}`,h=n.toString()}catch{}if(m.addEventListener(`click`,e=>{e.stopPropagation(),Io(h,m,`✓`)}),n.append(r,s,f,m),o?.startedBy&&Y&&o.startedBy===Y&&l){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,c(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),u(!1,`channel:${o?.id??t}`)}),n.append(e)}d.append(n)}let[p,m]=ie({name:e.name,view:e.url,admin:l},()=>{s.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(r,p,m),Y&&t.append(qr(e.url,e.name)),e.ownerId&&Y&&e.ownerId!==Y&&t.append(Pa(e.ownerId,e.name)),d.childElementCount>0&&t.append(d),e.ownerId&&Y&&e.ownerId===Y){let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Take off the list`,r.addEventListener(`click`,t=>{t.stopPropagation(),r.disabled=!0,(async()=>{try{let t=await n(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),r=await t.json().catch(()=>({}));s.directoryNote.textContent=t.ok?`${e.name} is off the list.`:r.error??`that did not work`}catch{s.directoryNote.textContent=`could not reach the directory`}finally{await gr()}})()}),t.append(r)}s.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!s.directory.hidden&&gr(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),gr()}let _r=/^\/live\/([^/]+)\/?$/.exec(location.pathname);if(_r){document.body.classList.add(`route-party`),s.partyRoom.hidden=!1;let e=decodeURIComponent(_r[1]??``),t=null,r=0,i=``,a=new Set,o=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}`},c=(e,t=!1)=>{let n=t?s.partyChatNote:s.partyRoomNote;n.hidden=e===``,n.textContent=e},l=()=>{if(!t)return;let e=t.party.playing?(Date.now()-r)/1e3:0,n=t.party.positionNow+e,i=[t.event.status===`live`?t.party.playing?`▶ ${o(n)}`:`❚❚ ${o(n)}`:`ended`,t.party.mediaTitle,`code ${t.party.partyCode}`,t.host?`yours`:``].filter(Boolean);s.partyMeta.textContent=i.join(` · `)},u=()=>{if(!t)return;document.title=`${t.event.title} — nixamp`,s.partyTitle.textContent=t.event.title||t.party.partyCode;let e=t.links.partyUrl||t.party.partyUrl;s.partyWatch.href=e||`#`,s.partyWatch.hidden=e===``;let n=t.party.origin;try{n=new URL(e).hostname}catch{}s.partyWatch.title=`The film plays on ${n} (opens in a new tab)`,s.partyEnd.hidden=!t.host||t.event.status!==`live`;let r=t.event.chatEnabled!==!1&&t.event.status===`live`;s.partyChatForm.hidden=!r,s.partyChatInput.disabled=!r||Y===``,s.partyChatSend.disabled=!r||Y===``,c(r?Y===``?`Sign in to say something; everybody can read.`:``:t.event.status===`live`?`Chat is off for this party.`:`This party has ended.`,!0),l()},d=async()=>{try{let i=await n(`/api/v1/watch-parties/${encodeURIComponent(e)}`,{cache:`no-store`});if(!i.ok){c(i.status===404?`No party here. It may have ended, or the link is not one.`:`Could not open this party. Try again in a moment.`);return}t=await i.json(),r=Date.now(),c(``),u()}catch{c(`Could not open this party. Try again in a moment.`)}},f=async()=>{if(t&&t.event.chatEnabled!==!1)try{let e=new URL(`/api/v1/events/${encodeURIComponent(t.event.id)}/chat`,location.origin);i&&e.searchParams.set(`after`,i);let r=await n(e.toString(),{cache:`no-store`});if(!r.ok)return;let o=((await r.json()).messages??[]).filter(e=>!a.has(e.id));if(!o.length){if(!s.partyChat.childElementCount){let e=document.createElement(`li`);e.className=`hint`,e.textContent=`No messages yet. Say hi!`,s.partyChat.replaceChildren(e)}return}s.partyChat.querySelector(`.hint`)&&s.partyChat.replaceChildren();let c=s.partyChat.scrollHeight-s.partyChat.scrollTop-s.partyChat.clientHeight<60;for(let e of o){a.add(e.id),i=e.createdAt;let t=document.createElement(`li`),n=document.createElement(`b`);n.textContent=e.authorName,t.append(n,document.createTextNode(e.body)),s.partyChat.append(t)}for(;s.partyChat.childElementCount>200;)s.partyChat.firstElementChild?.remove();c&&(s.partyChat.scrollTop=s.partyChat.scrollHeight)}catch{}};s.partyChatForm.addEventListener(`submit`,e=>{e.preventDefault();let r=s.partyChatInput.value.trim();t&&r!==``&&(s.partyChatSend.disabled=!0,(async()=>{try{let e=await n(`/api/v1/events/${encodeURIComponent(t.event.id)}/chat`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({body:r})}),i=await e.json().catch(()=>({}));if(!e.ok){c(i.error??`That did not send.`,!0);return}s.partyChatInput.value=``,c(``,!0),await f()}catch{c(`That did not send.`,!0)}finally{s.partyChatSend.disabled=Y===``}})())}),s.partyCopy.addEventListener(`click`,()=>{navigator.clipboard?.writeText(t?.links.nixampUrl||location.href).then(()=>{s.partyCopy.textContent=`Copied`,setTimeout(()=>{s.partyCopy.textContent=`Copy room link`},2e3)},()=>c(`Could not copy that.`))}),s.partyEnd.addEventListener(`click`,()=>{t&&t.host&&(async()=>{if(!(await n(`/api/v1/watch-parties/${encodeURIComponent(t.party.partyCode)}/end`,{method:`POST`})).ok){c(`Could not end it.`);return}await d()})()}),(async()=>{await d(),await f()})(),setInterval(l,1e3),setInterval(()=>void d(),1e4),setInterval(()=>void f(),4e3),document.addEventListener(`nixamp:account`,()=>u())}let vr=null,yr=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,br=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,xr=``,Sr=``,Cr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===xr)return;xr=t,s.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)}s.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,``],[yr(t.network),`network-${t.network}`],[br(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)}s.adminConnections.append(e)}};function G(e){s.adminSaid.textContent=e,s.adminSaid.hidden=e===``}let wr=async()=>{try{let e=await n(z.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),r=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,i=t.active??0;s.adminNote.textContent=r===0?`${i} listening now.`:`${i} listening now, and ${r} with the page open.`,Cr(t.connections??[]),Tr(t.publish??[],(t.channels??[]).map(e=>e.id)),Ho(t.home??``,t.root??``),wo()}catch{s.adminNote.textContent=`lost touch with the server`}};function Tr(e,t){s.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Sr)return;if(Sr=n,e.length===0){L(s.publishList);return}let r=e.length-t.length;s.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,L(s.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`,P(o,()=>p(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let Er=async()=>{if(d!==`remote`){s.adminPanel.hidden=!0,s.publishPanel.hidden=!0,vr&&clearInterval(vr),vr=null;return}let e=!1,t=null,r=!1,i=!1;try{let a=await n(z.url(`/api/admin`));if(a.ok){let n=await a.json();e=n.allowed===!0,t=n.as??null,r=n.claimed===!0,i=n.member===!0}}catch{e=!1}let a=e||i;b&&(e=!1),Ke=a&&!e;let o=s.partiesList.dataset.adminMode!==String(e);if(s.adminPanel.hidden=!e,o&&(s.partiesList.dataset.adminMode=String(e),s.partiesList.querySelectorAll(`details[open]`).forEach(e=>e.removeAttribute(`open`)),Lr()),vo(e),v!==``){let e=v;v=``,qe()?sr(e):(T=`Sign in to nixamp.com to go live here.`,V())}if(vr&&clearInterval(vr),vr=null,wo(),ba(),yo(),s.listenOnly.hidden=e,!e){s.listenOnly.textContent=r?`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}s.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,wr(),vr=setInterval(()=>void wr(),2e3)};function Dr(e,t,r){let i=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;G(`Starting ${t||e}…`),(async()=>{try{let a=await n(z.url(`/api/channels/${encodeURIComponent(i)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...r===void 0?{source:e}:{at:r},...t?{name:t}:{}})}),o=await a.json();if(!a.ok){G(o.error??`that did not work`);return}G(`${o.channel?.name||t||e} is on the air.`),s.adminSource.value=``,s.adminName.value=``,yo(),wo()}catch{G(`could not reach the server`)}})()}s.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=s.adminSource.value.trim();t&&Dr(t,s.adminName.value.trim())}),s.adminAdd.addEventListener(`click`,()=>{let e=s.adminSource.value.trim();if(!e)return;G(`Reading ${e}…`);let t=s.adminReplace.checked,r=s.adminName.value.trim();(async()=>{try{let i=await n(z.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...r?{name:r}:{},...t?{replace:!0}:{}})}),a=await i.json();G(i.ok?t?`Now serving ${e}.`:a.added===0?`Everything there was already in the playlist.`:`Added ${a.added??0} tracks from ${e}.`:a.error??`that did not work`),i.ok&&(s.adminSource.value=``,s.adminName.value=``,yo(),wo())}catch{G(`could not reach the server`)}})()});let Or=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`},kr=e=>{let t=[],n=Y?e.filter(e=>e.ownerId&&e.ownerId!==Y):[];if(s.recentNote.hidden=n.length===0,n.length===0){L(s.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 ${Or(e.endedAt)}`:`ended ${Or(e.endedAt)}`,r.append(i,a),n.append(r,Pa(e.ownerId,e.name)),t.push(n)}L(s.recentList,...t)},Ar=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 jr(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?`▶ ${Ar(e.party.positionNow)}`:`❚❚ ${Ar(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`,tt(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=`⋯`,F(c,`aria-label`,()=>`${p(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let Mr=[],Nr=[],Pr=!1,Fr=null,Ir=``;function Lr(){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=d===`remote`&&j?y(z.address):``;for(let e of Mr){let r=y(e.url);if(!r||r===n)continue;let i=[],a=(t,n)=>{let a=document.createElement(`li`);a.dataset.liveKey=`${r}:${t}`,a.className=`party-row`;let o=document.createElement(`span`);o.className=`party-name`,o.textContent=n,o.title=n;let c=document.createElement(`button`);c.type=`button`,tt(c),F(c,`aria-label`,()=>`${p(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{b=!0,x=t,s.remoteUrl.value=e.url,s.remoteForm.requestSubmit()}),a.append(o,c),i.push(a)};e.playing!==!1&&e.nowPlaying&&a(`live`,Ye(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);a(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&j&&t(n,j.server.name||m||n,Eo(j));for(let e of Nr){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=jr(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...s.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),Je(e.querySelector(`ul`),n.rows),i.push(e)}Je(s.partiesList,i),s.partiesNote.hidden=e.size>0,e.size||P(s.partiesNote,()=>p(Pr?`No parties live right now.`:`Loading…`))}let Rr=5e3,zr=new Set,Br=(e,t)=>{t?zr.add(e):zr.delete(e),zr.size?s.partiesPanel.dataset.loading=`true`:delete s.partiesPanel.dataset.loading};async function Vr(){if(e||(Ir!==Y&&(Fr?.abort(),Fr=null,Nr=[],Ir=Y,Lr()),Fr))return;let t=new AbortController;Fr=t;let r=!Pr;r&&Br(t,!0);let i=Y,a=setTimeout(()=>t.abort(),8e3),o=async e=>{let r=await n(e,{signal:t.signal,cache:`no-store`});return{ok:r.ok,status:r.status,body:r.ok?await r.json():null}};try{let[e,n]=await Promise.allSettled([o(`/api/directory`),i?o(`/api/v1/watch-parties`):Promise.resolve(null)]);if(Fr!==t||i!==Y||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(Mr=e.value.body.streams??[],Pr=!0,s.directory.dataset.available=String(Mr.length>0),go()),n.status===`fulfilled`&&n.value&&(n.value.ok?(Nr=n.value.body.parties??[],Pr=!0):[401,403].includes(n.value.status)&&(Nr=[])),Lr(),!Pr&&!j&&P(s.partiesNote,()=>p(`Could not refresh parties.`))}finally{clearTimeout(a),r&&Br(t,!1),Fr===t&&(Fr=null)}}s.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.partyCode.value.trim();t!==``&&(async()=>{try{let e=await n(`/api/v1/watch-parties/${encodeURIComponent(t)}`),r=await e.json().catch(()=>({}));if(!e.ok){T=r.error??`No party found with that invite code.`,V();return}s.partyCode.value=``,window.location.href=r.links.nixampUrl}catch{T=`Could not look up that party. Try again.`,V()}})()});async function Hr(){if(!Y){s.connectionsNote.hidden=!0,s.connectionsList.hidden=!0;return}try{let e=await n(`/api/v1/oauth/connections`);if(!e.ok){s.connectionsNote.hidden=!0,s.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];s.connectionsNote.hidden=t.length===0,s.connectionsList.hidden=t.length===0,L(s.connectionsList,...t.map(e=>{let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.clientName;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.scope.split(` `).filter(Boolean).join(`, `),r.append(i,a);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,P(o,()=>p(`Disconnect`)),o.addEventListener(`click`,()=>{(async()=>{try{await n(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Hr()})()}),t.append(r,o),t}))}catch{s.connectionsNote.hidden=!0,s.connectionsList.hidden=!0}}let Ur=new Set,K=e=>{try{return new URL(e).origin}catch{return e}},Wr=e=>[...Ur].some(t=>K(t)===K(e));async function Gr(){if(!Y){Ur=new Set,s.favoritesPanel.hidden=!0,Jr();return}try{let e=await n(`/api/v1/favorites`);if(!e.ok){s.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];Ur=new Set(t.map(e=>e.url)),s.favoritesPanel.hidden=t.length===0,s.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,L(s.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)}),qr(e.url,e.name)),t}))}catch{s.favoritesPanel.hidden=!0}Jr()}async function Kr(e,t,r){try{if(!(r?await n(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await n(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){T=r?`Could not save that favourite.`:`Could not remove that favourite.`,V();return}}catch{T=`could not reach nixamp.com`,V();return}if(r)Ur.add(e);else for(let t of[...Ur])K(t)===K(e)&&Ur.delete(t);await Gr()}function qr(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Wr(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=[...Ur].find(t=>K(t)===K(e))??e;Kr(Wr(e)?i:e,t,!Wr(e)).then(r)}),n}function Jr(){let e=d===`remote`?z.shareLink:``;if(s.favHere.hidden=!(Y&&e),s.favHere.hidden)return;let t=Wr(e);s.favHere.textContent=t?`♥`:`♡`,s.favHere.dataset.on=t?`yes`:`no`,s.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,s.favHere.setAttribute(`aria-label`,s.favHere.title)}c(s.copyNow,`copy`),s.copyNow.addEventListener(`click`,()=>{Io(R.source,s.copyNow,`✓`)});function Yr(e){if(e===``||e===Le)return;Le=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),P(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),s.logList.prepend(t);s.logList.children.length>100;)s.logList.lastElementChild?.remove()}let Xr=3e3,q=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,Zr=``,Qr=``,$r=null,ei=!1,ti=new Set,ni=``,ri=null,ii=!1,ai=On(e=>localStorage.getItem(e)),J=Cn(e=>localStorage.getItem(e)),oi=new Set,si=new Set,ci=null,li=``,ui=``,Y=``,di=(()=>{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()}`}})(),fi=null,X=!1,pi=``,mi=!1,hi=!1,gi=``,_i=0,vi=!1,yi=!1;try{s.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let bi=new Un(()=>{yi=!0,vi&&(s.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),xi=()=>{let e=Number(s.transcriptBackgroundLevel.value);bi.setLevel(e/100),s.transcriptBackgroundValue.value=`${e}%`,F(s.transcriptBackgroundLevel,`aria-valuetext`,()=>f.number(e/100,{style:`percent`})),s.transcriptBackgroundLevel.disabled=!s.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(s.transcriptBackgroundLevel.value=e)}catch{}xi(),s.transcriptBackgroundLevel.addEventListener(`input`,()=>{xi();try{localStorage.setItem(`nixamp.backgroundLevel`,s.transcriptBackgroundLevel.value)}catch{}});let Si=new Kn({account:()=>q===``?Y:``,changed:()=>ta()});W(`translation-buy-tools`).append(Si.button()),Si.refresh();let Ci=new Wn({reconnecting:()=>Z.reset(),line:(e,t)=>{ji=0,Mi.push(e),$i(),Z.push(e,t,0)},status:e=>{s.transcriptAudioNote.textContent=e},failed:e=>{pi=e,ui=e,X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei(),s.transcriptAudioNote.textContent=`${e} Original audio restored.`,Si.refresh()}}),Z=new Ln({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(Ci.audio(String(e))):n(e,t)),playing:()=>R.playing,volume:()=>R.volume,active:e=>{vi=e,R.translatedAudio(e),bi.active(e&&R.playing&&s.transcriptBackground.checked)},status:e=>{s.transcriptAudioNote.textContent=e+(yi&&vi?` · background unavailable`:``)},failed:()=>{ui=s.transcriptAudioNote.textContent||`Translated audio stopped.`,X=!1,s.transcriptAudio.checked=!1,Ei()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!Y||q!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!fi||fi.channel!==t.channel||fi.expires<Date.now()+2e4||fi.remaining<t.text.length){let r=await n(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),i=await r.json();if(!r.ok||!i.token||!i.expires)throw Error(i.error||`Sign in to enable translated audio.`);fi={channel:t.channel,token:i.token,expires:i.expires,remaining:2e3}}return fi.remaining-=t.text.length,{authorization:`Bearer ${fi.token}`}}}),wi=new pn({fetcher:(e,t)=>{let r=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&r.set(`x-nixamp-translation-session`,di),n(e,{...t,headers:r})},language:()=>J,speakers:()=>s.transcriptAudio.checked,voices:()=>ci?.voices??[],channel:()=>di,status:e=>{!mi&&!X&&(pi=e),s.transcriptNote.textContent=e},failed:()=>{X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei()},lines:e=>{ji=0,Mi.push(...e),$i(),Oi(),s.transcriptAudio.checked&&Z.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:J,channel:di,speaker:e.speaker,voice:wi.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),Ti=new Bn(e=>{mi&&R.playing&&wi.push(e)});function Ei(){_i++,mi=!1,hi=!1,gi=``,Ti.stop(),wi.reset(),Ci.stop(),bi.stop(),Z.reset(),L(s.transcriptSpeakers)}async function Di(){if((mi||hi)&&gi===R.mediaKey)return;Ei();let e=_i;hi=!0,gi=R.mediaKey;try{if(!Y||q!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=R.audioInput();if(yi=!1,s.transcriptAudio.checked&&s.transcriptBackground.checked&&bi.start(t.context,t.node).then(t=>{t&&e===_i&&bi.active(vi&&R.playing&&s.transcriptBackground.checked)}),s.transcriptAudio.checked&&d===`remote`&&O)await Ci.start(ra(),J),Si.refresh();else{if(s.transcriptAudio.checked&&await Si.startSession(di),e!==_i)return;await Ti.start(t.context,t.node,s.transcriptAudio.checked?2:5)}if(e!==_i)return;mi=!0,X=!0,ji=0,Pi??=setInterval($i,250),s.transcriptNote.textContent=s.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==_i)return;X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei(),pi=t instanceof Error?t.message:`This audio could not be captured.`,s.transcriptNote.textContent=pi}finally{e===_i&&(hi=!1)}}function Oi(){let e=[...wi.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(s.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];P(n,()=>`${p(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,F(i,`aria-label`,()=>`${p(`Speaker voices`)}: ${r}`);for(let e of ci?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,Z.reset()}),e.append(i),s.transcriptSpeakers.append(e)}s.transcriptVoiceSettings.hidden=!s.transcriptAudio.checked;for(let e of s.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[s.audio,s.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(R.showingVideo?s.video:s.audio)&&Ei()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(R.showingVideo?s.video:s.audio)&&X&&ai&&R.playing&&Di()});e.addEventListener(`volumechange`,()=>{Z.setVolume()})}let ki=``,Ai=null,ji=Tn(6,!1),Mi=[],Ni=[],Pi=null;function Fi(){if(d!==`remote`)return null;let{base:e}=gt(Ro());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=O?O.id:A?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Ii(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${q}/api/v1/trollbox?${n.toString()}`}function Li(){let e=Fi(),t=e?`${e.server}|${e.channel}`:``;t!==Zr&&(Zr=t,Qr=``,ti.clear(),s.trollboxList.replaceChildren(),$r&&clearTimeout($r),$r=null,s.trollboxPanel.hidden=e===null,s.trollboxForm.hidden=!0,Ui(!1),e&&(P(s.trollboxNote,()=>`The room for ${vt()||e.channel}. Loading…`),zi()))}function Ri(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);P(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 zi(){let e=Fi(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===Zr&&!ei){ei=!0;try{let r=await n(Ii(e,Qr)),i=await r.json().catch(()=>({}));if(t!==Zr)return;if(!r.ok){s.trollboxNote.textContent=i.error??`The trollbox is not answering.`;return}let a=(i.messages??[]).filter(e=>!ti.has(e.id));for(let e of a)ti.add(e.id),s.trollboxList.append(Ri(e)),Qr=e.createdAt;for(;s.trollboxList.children.length>200;)s.trollboxList.firstElementChild?.remove();let o=i.you??``,c=ni!==o;ni=o,l.hidden=o!==``,q!==``&&(l.href=`${q}/?url=${encodeURIComponent(Ro())}&play=${encodeURIComponent(`channel:${e.channel}`)}#account-panel`),c&&(fi=null,ta()),s.trollboxForm.hidden=o===``,s.trollboxEditLabel.hidden=o===``||!Bi,o===``&&Ui(!1),P(s.trollboxNote,()=>o===``?q===``?`The room for ${vt()||e.channel}. Sign in to say something.`:`The room for ${vt()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${vt()||e.channel}.`)}catch{t===Zr&&(s.trollboxNote.textContent=`The trollbox is not answering.`)}finally{ei=!1,t===Zr&&($r=setTimeout(()=>{document.visibilityState===`visible`?zi():$r=setTimeout(()=>void zi(),Xr)},Xr))}}}s.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Fi(),r=s.trollboxInput.value.trim();t&&r!==``&&(s.trollboxInput.disabled=!0,(async()=>{try{let e=await n(`${q}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:r})}),i=await e.json().catch(()=>({}));if(!e.ok||!i.message){s.trollboxNote.textContent=i.error??`that did not send`;return}s.trollboxInput.value=``,ti.has(i.message.id)||(ti.add(i.message.id),s.trollboxList.append(Ri(i.message)),Qr=i.message.createdAt)}catch{s.trollboxNote.textContent=`The trollbox is not answering.`}finally{s.trollboxInput.disabled=!1}})())});let Bi=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Vi=Bi?vn(e=>MediaRecorder.isTypeSupported(e)):``;s.trollboxMic.hidden=!Bi;function Hi(e){s.trollboxNote.textContent=e,Yr(e)}function Ui(e){let t=ri;if(!t)return;ri=null,clearTimeout(t.stop),clearInterval(t.tick),s.trollboxMic.setAttribute(`aria-pressed`,`false`),s.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(()=>Gi(new Blob(t.chunks,{type:t.recorder.mimeType||Vi||`audio/webm`}),t.startedAt))}async function Wi(){if(ri||ii||ni===``||!Fi())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){Hi(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,Vi?{mimeType:Vi}:{})}catch{for(let t of e.getTracks())t.stop();Hi(`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();ri={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>Ui(!0),_n),tick:setInterval(()=>{s.trollboxMic.textContent=yn(r,Date.now())},500)},t.start(250),s.trollboxMic.setAttribute(`aria-pressed`,`true`),s.trollboxMic.textContent=yn(r,r),Hi(`Listening. Tap the mic again when you have said it (${Math.round(_n/1e3)} s at most).`)}async function Gi(e,t){let r=Fi();if(r&&ni!==``){if(Date.now()-t<400||e.size===0){Hi(`That was too short to hear. Tap, say it, then tap again.`);return}ii=!0,s.trollboxMic.disabled=!0,s.trollboxMic.textContent=`…`,Hi(`Hearing you…`);try{let t=new AudioContext,i;try{i=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let a=new OfflineAudioContext(1,Math.max(1,Math.ceil(i.duration*gn)),gn),o=a.createBufferSource();o.buffer=i,o.connect(a.destination),o.start();let c=ln((await a.startRendering()).getChannelData(0),gn),l=s.trollboxEdit.checked,u=new URLSearchParams(l?{}:{server:r.server,channel:r.channel}),d=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(d)&&u.set(`language`,d);let f=await n(`${q}/api/v1/speech/transcribe?${u.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([c.buffer],{type:`audio/wav`})}),p=await f.json().catch(()=>({}));if(!f.ok){Hi(p.error??`nixamp.com could not hear that.`);return}let m=(p.text??``).trim();if(m===``){Hi(`Heard nothing. Try again, closer to the mic.`);return}if(l||!p.message){let e=s.trollboxInput.value.trimEnd();s.trollboxInput.value=(e===``?m:`${e} ${m}`).slice(0,500),Hi(`Heard: “${m}”. Send it, or fix it first.`);return}Fi()&&!ti.has(p.message.id)&&(ti.add(p.message.id),s.trollboxList.append(Ri(p.message)),Qr=p.message.createdAt),Hi(`Said: “${p.message.body}”`)}catch{Hi(`That recording could not be read here.`)}finally{ii=!1,s.trollboxMic.disabled=!1,s.trollboxMic.textContent=`🎤`}}}s.trollboxMic.addEventListener(`click`,()=>{ri?Ui(!0):Wi()});try{s.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}s.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,s.trollboxEdit.checked?`on`:`off`)}catch{}Hi(s.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Ki(){try{let e=await n(`${q}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){s.personaNote.textContent=t.error??`Could not read your profile.`;return}s.personaHandle.value=t.chosen?t.handle??``:``,F(s.personaHandle,`placeholder`,()=>t.handle||p(`handle`)),s.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,s.personaProfile.value=t.profile??``;let r=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;s.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${qi(t.voice??``)}${r}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${qi(t.voice??``)}${r}.`}catch{s.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function qi(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`}s.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.personaHandle.value.trim(),r={voice:s.personaVoice.value,profile:s.personaProfile.value.trim()};t!==``&&(r.handle=t),s.personaNote.textContent=`Saving…`,(async()=>{try{let e=await n(`${q}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(r)}),t=await e.json().catch(()=>({}));if(!e.ok){s.personaNote.textContent=t.error??`that did not save`;return}await Ki()}catch{s.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&ri&&Ui(!0)});function Ji(){return d===`remote`&&O?{id:O.id,name:O.name,hls:O.video&&Xe()}:R.loaded||M?{id:di,name:vt()||`This audio`,hls:!1}:null}function Yi(){Ei(),fi=null,oi.clear(),si.clear(),Ai?.close(),Ai=null,Pi&&clearInterval(Pi),Pi=null,Mi=[],Ni=[],s.transcriptList.replaceChildren(),s.subtitle.hidden=!0,s.subtitle.textContent=``}function Xi(){let e=Ji(),t=`${e?.id??``}|${R.mediaKey}|${ai}|${J}|${s.transcriptAudio.checked}|${X}|${Y}`;if(t!==ki){if(ki=t,Yi(),s.transcriptPanel.hidden=!1,s.transcriptOn.checked=ai&&(!!O||X||s.transcriptAudio.checked),s.transcriptLanguage.options.length===0)for(let e of Sn){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),P(t,()=>e.code?e.label:p(`Original (auto-detect)`)),s.transcriptLanguage.append(t)}if(s.transcriptLanguage.value=J,ta(),na(),!e){s.transcriptNote.textContent=`Play something to see its captions.`;return}if(!ai){s.transcriptNote.textContent=`Captions are off.`;return}if(pi){s.transcriptNote.textContent=pi;return}s.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,s.transcriptAudio.checked||X?R.playing?Di():s.transcriptNote.textContent=`Press Play to start listening.`:d===`remote`&&O?Zi(e,t):s.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Zi(e,t){let r=6,i=J?`?language=${encodeURIComponent(J)}`:``;try{let a=await n(z.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${i}`)),o=await a.json().catch(()=>({}));if(t!==ki)return;if(!a.ok){s.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){Y&&q===``?(X=!0,Xi()):s.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}r=o.backlog??r}catch{t===ki&&(s.transcriptNote.textContent=`The server did not answer about captions.`);return}ji=Tn(r,e.hls);let a=new EventSource(z.url(`/api/channels/${encodeURIComponent(e.id)}/captions${i}`));Ai=a;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}`;oi.has(e)||(oi.add(e),oi.size>600&&oi.delete(oi.values().next().value),Mi.push(n),t&&s.transcriptAudio.checked&&si.add(n))}};a.addEventListener(`hello`,n=>{if(t!==ki)return;let i=JSON.parse(n.data);ji=Tn(i.backlog??r,e.hls),o(i.lines??[]);let a=Sn.find(e=>e.code===i.language)?.label??i.language,c=Sn.find(e=>e.code===J)?.label??J;if(s.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:J?`${a||`Detected audio`} → ${c}`:`Original audio · ${a||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${q||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,s.transcriptNote.append(` `,e,`.`)}}),a.addEventListener(`line`,n=>{if(t!==ki)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),a=Sn.find(e=>e.code===i)?.label??i,c=Sn.find(e=>e.code===J)?.label??J;s.transcriptNote.textContent=J?`${e.name} · ${a||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${a||`detecting…`}`}),a.addEventListener(`error`,()=>{t===ki&&a.readyState===EventSource.CLOSED&&(s.transcriptNote.textContent=`Captions stopped; the server went away.`)}),Pi=setInterval($i,250)}function Qi(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),P(n,()=>kn(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=wn(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 $i(){let e=Date.now(),{ready:t,still:n}=En(Mi,e,ji);Mi=n;for(let e of t)if(Ni.push(e),s.transcriptList.append(Qi(e)),si.delete(e)&&s.transcriptAudio.checked&&J){let t=new URLSearchParams({at:String(e.at),language:J,voice:`auto`});Z.push(e,z.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),ji)}for(;Ni.length>200;)Ni.shift();for(;s.transcriptList.children.length>200;)s.transcriptList.firstElementChild?.remove();let r=Dn(Ni,e,ji),i=s.transcriptList.children,a=r?Ni.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let o=R.playing&&r!==null&&!s.video.hidden&&s.video.offsetHeight>0;s.subtitle.hidden=!o,o&&r&&(s.subtitle.textContent!==r.text&&(s.subtitle.textContent=r.text),s.subtitle.style.top=`${s.video.offsetTop+s.video.offsetHeight-s.subtitle.offsetHeight-10}px`)}s.transcriptOn.addEventListener(`change`,()=>{ai=s.transcriptOn.checked,X=ai&&(!O||s.transcriptAudio.checked),ai||(s.transcriptAudio.checked=!1,Z.disable());try{localStorage.setItem(bn,ai?`on`:`off`)}catch{}Xi()}),s.transcriptLanguage.addEventListener(`change`,()=>{pi=``,ui=``,J=Cn(()=>s.transcriptLanguage.value),!J&&s.transcriptAudio.checked&&(s.transcriptAudio.checked=!1,X=!1,Z.disable());try{J?localStorage.setItem(xn,J):localStorage.removeItem(xn)}catch{}Xi()});function ea(){if(J)return J;let e=navigator.language.split(`-`)[0]||`en`;return Sn.some(t=>t.code===e)&&ci?.languages.includes(e)?e:`en`}function ta(){let e=Y!==``&&q===``,t=e&&Si.loaded()&&!!Ji()&&!!ci?.languages.includes(ea());s.transcriptAudio.disabled=!t,s.transcriptVoiceSettings.contains(document.activeElement)||(s.transcriptVoiceSettings.hidden=!s.transcriptAudio.checked),t?s.transcriptAudio.checked||P(s.transcriptAudioNote,()=>ui||p(`Original audio.`)):(s.transcriptAudio.checked=!1,Z.disable(),s.transcriptAudioNote.textContent=e?Ji()?Si.loaded()?ui||(ci?`Audio translation is unavailable for this language.`:`Loading voices…`):Si.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function na(){if(!Y||q!==``)return;let e=`/api/v1/speech/voices`;if(li!==e){li=e,ci=null,ui=``,ta();try{let t=await n(e,{signal:AbortSignal.timeout(1e4)}),r=await t.json();if(li!==e)return;if(!t.ok)throw Error(r.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(r.voices)||!Array.isArray(r.languages))throw Error(`This server needs an update for translated audio.`);ci=r}catch(t){if(li!==e)return;ui=t instanceof Error?t.message:`Translated audio is unavailable.`}ta()}}s.transcriptBackground.addEventListener(`change`,()=>{xi();try{localStorage.setItem(`nixamp.backgroundSound`,s.transcriptBackground.checked?`on`:`off`)}catch{}if(bi.stop(),yi=!1,s.transcriptBackground.checked&&s.transcriptAudio.checked&&R.playing){let e=_i,t=R.audioInput();bi.start(t.context,t.node).then(t=>{t&&e===_i&&bi.active(vi&&R.playing&&s.transcriptBackground.checked)})}}),s.transcriptAudio.addEventListener(`change`,()=>{if(pi=``,ui=``,si.clear(),s.transcriptAudio.checked&&!Si.ready()){s.transcriptAudio.checked=!1,Si.open(s.transcriptAudio);return}if(s.transcriptAudio.checked){J=ea();try{localStorage.setItem(xn,J)}catch{}ai=!0,X=!0,Z.enable()}else X=!1,Z.disable();Xi()});function ra(){if(M)return M.url;if(d!==`remote`)return``;let{base:e,key:t}=gt(Ro());if(e===``)return``;if(O)return mt(e,`/api/channels/${encodeURIComponent(O.id)}`,t);if(A?.kind===`live`)return mt(e,`/api/live`,t);if(R.source===``)return``;try{let n=new URL(R.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function ia(){let e=ra();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function aa(){return d===`remote`?O?Lo(`channel:${O.id}`):A?.kind===`live`||ut()?Lo(`live`):``:``}s.shareNow.addEventListener(`click`,()=>{let e=ia();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${pt()} on nixamp`,url:e}).catch(()=>void 0);return}Io(e,s.shareNow,`Copied`)}),s.copyNixamp.addEventListener(`click`,()=>{let e=aa();e!==``&&Io(e,s.copyNixamp,`✓`)});async function oa(){let e=aa();if(e===``||s.schoolLive.disabled)return;let t=s.schoolLive.textContent;s.schoolLive.disabled=!0,s.schoolLive.textContent=`Opening a classroom…`;let r={"content-type":`application/json`};try{let t=await n(`/api/v1/events`,{method:`POST`,headers:r,body:JSON.stringify({kind:`class`,title:Qe(pt())||`Live class`,broadcastUrl:e,visibility:`public`})}),i=await t.json().catch(()=>({}));if(!t.ok||!i.event)throw Error(i.error??`the class could not be made`);let a=i.event,o=await n(`/api/v1/events/${encodeURIComponent(a.id)}/start`,{method:`POST`,headers:r,body:JSON.stringify({version:a.version})}),s=`https://backtoschool.help/live/${encodeURIComponent(a.slug)}`;T=o.ok?`Your class is live on backtoschool.help: ${s}`:`The class is made but not started yet. Open it to start: ${s}`,V(),globalThis.open(s,`_blank`,`noopener`)}catch(e){T=`Could not open a classroom: ${e.message}`,V()}finally{s.schoolLive.disabled=!1,s.schoolLive.textContent=t}}s.schoolLive.addEventListener(`click`,()=>{oa()}),s.favHere.addEventListener(`click`,()=>{let e=Ro()||z.shareLink;if(!e)return;let t=[...Ur].find(t=>K(t)===K(e))??e;Kr(Wr(e)?t:e,m||z.address,!Wr(e)).then(Jr)});let sa=i?o:200,ca=[],Q=null,la=null,ua=``,da=[],fa=0,pa=null,ma=0,ha=null,ga=null,_a=new Map;function va(e,t){ma++,ha?.abort(),pa&&clearTimeout(pa),pa=null,Ge(s.catalogsList),Ge(s.catalogsEntries),Q=e,la=t,ua=``,s.catalogsFilter.value=``,da=[],fa=0,s.catalogsEntries.setAttribute(`aria-busy`,`false`),Sa(),e&&t!==null&&Da(0)}function ya(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 ba(){let e=z.url(`/api/catalogs`);if(ga?.url===e)return ga.promise;let t=xa(e).finally(()=>{ga?.promise===t&&(ga=null)});return ga={url:e,promise:t},t}async function xa(e){if(d!==`remote`){s.catalogsPanel.hidden=!0;return}let t;try{t=await n(e)}catch{e===z.url(`/api/catalogs`)&&(s.catalogsPanel.hidden=!0);return}if(d===`remote`&&e===z.url(`/api/catalogs`)){if(!t.ok){s.catalogsPanel.hidden=!0;return}ca=(await t.json().catch(()=>({}))).catalogs??[],Q&&=ca.find(e=>e.id===Q?.id)??null,Q||(la=null),s.catalogsPanel.hidden=!1,Sa()}}function Sa(){let e=!s.adminPanel.hidden;s.catalogsForm.hidden=!e;let t=ca.reduce((e,t)=>e+t.live,0),n=ca.reduce((e,t)=>e+t.vod,0);s.catalogsNote.textContent=ca.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${ca.length} ${ca.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,Ca();let r=Q!==null&&la!==null;if(s.catalogsList.hidden=r,s.catalogsFilter.hidden=!r,s.catalogsEntries.hidden=!r,r){Oa();return}if(Q){Ta(Q);return}L(s.catalogsList,...ca.map(t=>wa(t,e)))}function Ca(){let e=Q!==null;if(s.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`,()=>va(null,null),!1),n(),t(Q?.name??``,()=>va(Q,null),la===null)];la!==null&&r.push(n(),t(la===``?`All groups`:la,()=>void 0,!0)),s.catalogsCrumbs.replaceChildren(...r)}function wa(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`,P(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 ${ya(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`,()=>{va(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`,()=>{Aa(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,P(r,()=>p(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Fo(n,r,()=>ja(e),()=>void ba())}),n.append(t,r)}return n}async function Ta(e){let t=z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),r=`${t}:${e.refreshedAt}:${e.entries}`,i;s.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=_a.get(r);e||(_a.size>=20&&_a.delete(_a.keys().next().value),e=n(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),_a.set(r,e)),i=await e}catch{if(_a.delete(r),Q?.id!==e.id||la!==null||t!==z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;s.catalogsList.setAttribute(`aria-busy`,`false`),T=`Could not read the groups in ${e.name}.`,V();return}if(Q?.id!==e.id||la!==null||t!==z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;s.catalogsList.setAttribute(`aria-busy`,`false`);let a=[Ea(`All groups`,``,e.entries,e.live,e.vod),...i.map(e=>Ea(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];L(s.catalogsList,...a)}function Ea(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`,P(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`,()=>{va(Q,t)}),a.append(o,l),a}async function Da(e){let t=Q,r=la;if(!t||r===null)return;let i=++ma;ha?.abort();let a=new AbortController;ha=a;let o=z.url(`/api/catalogs`);s.catalogsEntries.setAttribute(`aria-busy`,`true`);let c=new URLSearchParams({group:r,q:ua,offset:String(e),limit:String(sa)}),l;try{let e=await n(z.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${c}`),{signal:a.signal});if(!e.ok)throw Error(String(e.status));l=await e.json()}catch{if(a.signal.aborted||i!==ma)return;s.catalogsEntries.setAttribute(`aria-busy`,`false`),T=`Could not read ${t.name}.`,Oa(),V();return}i===ma&&Q?.id===t.id&&la===r&&o===z.url(`/api/catalogs`)&&(s.catalogsEntries.setAttribute(`aria-busy`,`false`),fa=l.total??0,da=e===0?l.entries??[]:[...da,...l.entries??[]],Oa())}function Oa(){let e=Q;if(!e)return;let t=da.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?ze(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`,()=>{ka(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,c(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`;Io(z.url(i),r,`✓`)}),n.append(r)}return qe()&&n.append(nt(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(da.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=ua?`Nothing called "${ua}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(da.length<fa){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,P(n,()=>`Show more (${da.length.toLocaleString(f.language)} of ${fa.toLocaleString(f.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),Ge(s.catalogsEntries,!1),n.disabled=!0,Da(da.length)}),e.append(n),t.push(e)}L(s.catalogsEntries,...t)}async function ka(e,t,r){r?.classList.add(`loading`),T=`Starting ${t.title}…`;let i={catalog:{id:e.id,name:e.name},entry:t};try{await k(async()=>{let r,a={};try{r=await n(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),a=await r.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!r.ok){T=a.error??`${t.title} would not play.`;return}let o=a.name||t.title;if(a.kind===`live`&&a.channel){await ko({id:a.channel,name:o,video:!0},!0,{kind:`channel`,...i});return}if(a.kind===`vod`&&a.url){O=null,E=-1,A={kind:`vod`,...i},Ae(o,`title`),await R.load({title:o,artist:``,album:``,duration:0,url:z.url(a.url),video:!0,objectUrl:!1},!0),qn(!0),T=`Playing ${o}.`;return}T=`${t.title} would not play.`})}finally{r?.classList.remove(`loading`),V()}}async function Aa(e){G(`Reading ${e.name} again…`);try{let t=await n(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),r=await t.json().catch(()=>({}));G(t.ok?`${r.catalog?.name??e.name}: ${(r.catalog?.entries??0).toLocaleString(f.language)} entries.`:r.error??`that did not work`)}catch{G(`could not reach the server`)}ba()}async function ja(e){try{let t=await n(z.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(G(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return G(`could not reach the server`),!1}return Q?.id===e.id&&(Q=null,la=null),!0}s.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.catalogSource.value.trim(),r=s.catalogName.value.trim();t&&(async()=>{G(`Reading ${r||t}…`);try{let e=await n(z.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:r})}),i=await e.json().catch(()=>({}));if(!e.ok){G(i.error??`that did not work`);return}G(`${i.catalog?.name??r??t}: ${(i.catalog?.entries??0).toLocaleString(f.language)} entries.`),s.catalogSource.value=``,s.catalogName.value=``}catch{G(`could not reach the server`)}ba()})()}),s.catalogsFilter.addEventListener(`input`,()=>{ma++,ha?.abort(),pa&&clearTimeout(pa),pa=setTimeout(()=>{pa=null,ua=s.catalogsFilter.value.trim(),Da(0)},250)});let Ma=async()=>{L(s.serversList);try{let e=await n(`/api/v1/servers`);if(!e.ok){s.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ne=new Map(t.map(e=>[K(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),s.serversPanel.hidden=!1,s.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`),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.url,r.append(i,a);let o=e.key?`${e.url}/admin/${e.key}`:e.url,[c,l]=ie({name:e.name,view:o,admin:o});Dt(e.url).then(n=>{if(n!==null){a.textContent=`${e.url} · ${n}`;return}a.textContent=`${e.url} · not answering`,t.classList.add(`offline`),c.disabled=!0,l.disabled=!0,c.title=l.title=`That machine is not answering. Start nixamp on it.`});let u=qa()===K(e.url),d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=u?`✓ Default`:`Make default`,d.title=u?`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`,d.addEventListener(`click`,()=>{Ja(u?``:K(e.url)),Ma()});let f=document.createElement(`button`);f.type=`button`,f.className=`ghost`,f.textContent=`Forget`,f.addEventListener(`click`,()=>{(async()=>{f.disabled=!0;try{await n(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await Ma()}catch{f.disabled=!1}})()}),t.append(r,c,l,d,f),s.serversList.append(t)}}catch{s.serversPanel.hidden=!0}},Na=async()=>{L(s.followingList);try{let e=await n(`/api/v1/follows`);if(!e.ok){s.followingNote.hidden=!0;return}let t=(await e.json()).following??[];s.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name||`a nixamp`;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.live?`live now`:`not streaming`,r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,P(o,()=>p(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await n(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),s.followingList.children.length===0&&(s.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(r,o),s.followingList.append(t)}}catch{s.followingNote.hidden=!0}},Pa=(e,t)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`ghost follow`,P(r,()=>p(`Follow`)),r.setAttribute(`aria-label`,`Follow ${t}`);let i=e=>{P(r,()=>e?`Following`:p(`Follow`)),r.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await n(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&i((await t.json()).following===!0)}catch{}})(),r.addEventListener(`click`,()=>{(async()=>{let t=r.dataset.following===`yes`;r.disabled=!0;try{(await n(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(i(!t),Na())}catch{}finally{r.disabled=!1}})()}),r},Fa=async()=>{let e=ye();if(!e.supported)return s.notifyNote.textContent=e.message,!1;try{return await Ee({vapidKeyUrl:`/api/v1/notify/key`,serviceWorkerUrl:`/sw.js`,saveUrl:`/api/v1/notify/subscribe`}),s.notifyNote.textContent=`This device will be told.`,!0}catch(e){return s.notifyNote.textContent=e instanceof xe&&e.reason!==`save-failed`?e.message:`Could not set this device up.`,!1}},Ia=async()=>{try{await Oe({removeUrl:`/api/v1/notify/subscribe`})}catch{}},La=async e=>{try{let t=await n(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),r=await t.json();s.notifyPhoneNote.textContent=t.ok?``:r.error??`that did not save`,t.ok&&typeof r.phone==`string`&&(s.notifyPhone.value=r.phone)}catch{s.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Ra=async()=>{try{let e=await n(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();s.notifyEmail.checked=t.wantsEmail!==!1,s.notifySms.checked=t.wantsSms===!0,s.notifyPhone.value=t.phone??``;let r=ye(),i=r.supported&&r.permission===`granted`?await De()!==null:!1;s.notifyWeb.checked=t.wantsWeb!==!1&&i,s.notifyNote.textContent=i?`Get told when someone you follow goes live.`:r.message??`Turn on “On this device” to be told here.`}catch{}};s.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(s.notifyWeb.checked){let e=await Fa();s.notifyWeb.checked=e,await La({wantsWeb:e});return}await Ia(),await La({wantsWeb:!1}),s.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),s.notifyEmail.addEventListener(`change`,()=>{La({wantsEmail:s.notifyEmail.checked})}),s.notifySms.addEventListener(`change`,()=>{(async()=>{if(s.notifySms.checked&&!s.notifyPhone.value.trim()){s.notifyPhoneNote.textContent=`Add a phone number first.`,s.notifySms.checked=!1;return}await La({wantsSms:s.notifySms.checked})})()}),s.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),La({phone:s.notifyPhone.value.trim()})});let za=!1,Ba=!1,Va=`nixamp.welcome`,Ha=()=>{let e=!1;try{e=localStorage.getItem(Va)===`hidden`}catch{}s.welcome.hidden=!Ba||Y!==``||e},Ua=t=>{document.dispatchEvent(new CustomEvent(`nixamp:account`,{detail:{email:t}}));let n=t!==null;Si.refresh(),li=``,fi=null,n||(X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei()),Xi(),s.notifyPanel.hidden=!n,n?(Ra(),Na(),Ma()):(s.serversPanel.hidden=!0,s.followingNote.hidden=!0,L(s.followingList),s.recentNote.hidden=!0,s.recentList.replaceChildren()),s.accountForm.hidden=n,s.accountProviders.hidden=n||s.accountProviders.childElementCount===0,s.accountSignOut.hidden=!n,s.personaForm.hidden=!n,s.personaNote.hidden=!n,n&&Ki(),s.accountNote.textContent=n?`Signed in as ${t}.`:za?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,P(s.accountSubmit,()=>p(za?`Create account`:`Sign in`)),P(s.accountToggle,()=>za?`I have one`:p(`Create one`)),s.accountPassword.autocomplete=za?`new-password`:`current-password`,s.accountForgot.hidden=za,e&&(s.accountForgot.target=`_blank`,s.accountForgot.rel=`noopener`),Ha()},Wa=async()=>{let e=[];Ba=!1;try{let t=await n(`/api/v1/auth/providers`);t.ok&&(Ba=!0,e=(await t.json()).providers??[])}catch{}s.accountProviders.replaceChildren(),s.accountProviders.hidden=e.length===0,s.accountPanel.hidden=!Ba,s.accountElsewhere.hidden=Ba,Ha();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}`,s.accountProviders.append(e)}},Ga=async()=>{try{let e=await n(`/api/v1/auth/me`),t=await e.json();Y=e.ok?t.account?.id??``:``,Ua(e.ok?t.account?.email??`you`:null)}catch{Y=``,Ua(null)}if(z.session=``,Y!==``){try{let e=await n(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));z.session=e.ok&&typeof t.token==`string`?t.token:``}catch{z.session=``}d===`remote`&&Er()}Gr(),Vr(),Hr(),Ya();let e=await Ka();if(Ie!==``){let t=Ie;Ie=``,e?x=`golive:${t}`:Yn(t)}};async function Ka(){if(Y===``||d===`remote`||Fe!==``)return!1;let e=[];try{let t=await n(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=qa(),r=[...e].sort((e,n)=>Number(K(n.url)===t)-Number(K(e.url)===t));for(let e of r)if(await Dt(e.url,void 0,e.key)!==null)return d!==`remote`&&(b=!1,x=``,s.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,T=`Connecting to ${e.name}, your server…`,V(),s.remoteForm.requestSubmit(),!0);return!1}function qa(){try{return localStorage.getItem(tr)??``}catch{return``}}function Ja(e){try{e===``?localStorage.removeItem(tr):localStorage.setItem(tr,e)}catch{}}function Ya(){if(Fe===``)return;let e=Fe;Fe=``,s.remoteUrl.value=e,s.remoteForm.requestSubmit()}s.accountToggle.addEventListener(`click`,()=>{za=!za,Ua(null)}),s.welcomeCreate.addEventListener(`click`,()=>{za=!0,Ua(null),s.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),s.accountEmail.focus({preventScroll:!0})}),s.welcomeBrowse.addEventListener(`click`,()=>{s.directory.hidden?s.browse.click():s.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),s.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Va,`hidden`)}catch{}s.welcome.hidden=!0}),s.accountForm.addEventListener(`submit`,r=>{r.preventDefault();let i=s.accountEmail.value.trim(),a=s.accountPassword.value;(async()=>{s.accountSubmit.disabled=!0;try{let r=await n(`/api/v1/auth/${za?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:i,password:a})}),o=await r.json();if(!r.ok){s.accountNote.textContent=o.error??`that did not work`;return}e&&(t=o.token??``),Y=o.account?.id??``,s.accountPassword.value=``,Ua(o.account?.email??i),Er(),Ya()}catch{s.accountNote.textContent=`could not reach nixamp.com`}finally{s.accountSubmit.disabled=!1}})()}),s.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await n(`/api/v1/auth/logout`,{method:`POST`})}catch{}t=``,Y=``,Ua(null),Vr(),z.close(),E=-1,d=`local`,se=`idle`,w=``,s.remoteUrl.value=``,s.sharePanel.hidden=!0,s.publishPanel.hidden=!0,s.adminPanel.hidden=!0,s.catalogsPanel.hidden=!0,s.listenOnly.hidden=!0,Co(!1);try{localStorage.removeItem(er)}catch{}T=`Signed out, and disconnected from the server.`,Er(),V()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Fe=t,x=e.get(`play`)??``,te=Math.max(0,Number(e.get(`t`)??`0`)||0),s.remoteUrl.value=t,T=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(s.linkUrl.value=n,t!==``&&x===``?x=`link:${n}`:t===``&&(Ie=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=ht(r);t?(Fe=t.view,x=t.what,te=Math.max(0,Number(e.get(`t`)??`0`)||0),s.remoteUrl.value=t.view,T=`Opening the stream you were sent…`):(s.linkUrl.value=r,Ie=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Xa=[`zone-top`,`zone-main`],Za=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Qa=e=>e.parentElement&&Xa.includes(e.parentElement.id)?e.parentElement:null,$a=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,eo=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Za(e)&&Qa(e)!==null),to=e=>e.dataset.title??e.id,no=new Map,ro=eo().map((e,t)=>(no.set(e.id,{zone:Qa(e)?.id??``,col:$a(e),index:t}),e.id)),$=nn();try{$=an(localStorage.getItem(tn))}catch{}let io=()=>$.order.length>0||Object.keys($.placement).length>0;function ao(){$.order=eo().map(e=>e.id);try{localStorage.setItem(tn,on($))}catch{}}function oo(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 so(){if(e)return;for(let e of eo()){let t=$.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Xa.includes(i.id)&&oo(e,i,r===`a`||r===`b`?r:``)}let t=sn(eo().map(e=>e.id),$.order);for(let e of Xa){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(Za),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 eo())e.toggleAttribute(`data-collapsed`,$.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,$.closed.includes(e.id))}function co(e,t){e.toggleAttribute(`data-collapsed`,t),e===s.panelsPanel&&s.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),$.collapsed=cn($.collapsed,e.id,t),ao(),go()}function lo(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===s.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===s.panelsPanel&&s.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===s.partiesPanel&&!t&&Vr(),t&&n&&s.panelsToggle.focus({preventScroll:!0}),$.closed=cn($.closed,e.id,t),ao(),go()}function uo(e,t,n){let r=Qa(t);r&&e!==t&&(oo(e,r,$a(t)),n?t.after(e):t.before(e),$.placement[e.id]=`${r.id}:${$a(t)}`,ao(),go())}let fo=null,po=()=>{for(let e of eo())e.classList.remove(`drop-before`,`drop-after`)},mo=(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 ho(){for(let e of eo()){let t=to(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n));let r=n.querySelector(`.panel-heading-text`);if(!r){r=document.createElement(`span`),r.className=`panel-heading-text`;let e=document.createElement(`span`);e.className=`panel-loading-spinner`,e.setAttribute(`aria-hidden`,`true`),n.replaceChildren(r,e)}if(r.textContent!==t&&(r.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let i=document.createElement(`span`);i.className=`panel-tools`;let a=mo(`≡`,`Move ${to(e)}: Alt plus Up or Down, or drag`,()=>void 0);a.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=eo().filter(t=>Qa(t)===Qa(e)&&$a(t)===$a(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(uo(e,r,t.key===`ArrowDown`),a.focus({preventScroll:!0}))}),a.classList.add(`grip`),a.draggable=!0,a.addEventListener(`dragstart`,t=>{fo=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),a.addEventListener(`dragend`,()=>{fo=null,e.classList.remove(`dragging`),po()});let o=mo(`▁`,`Shade ${to(e)} to its title`,()=>co(e,!e.hasAttribute(`data-collapsed`)));o.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let s=mo(`✕`,`Hide ${to(e)}; the Panels list turns it back on`,()=>lo(e,!0));e.id===`transcript-panel`&&i.append(Si.button()),i.append(a,o,s),e.prepend(i),e.addEventListener(`dragover`,t=>{if(!fo||fo===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;po(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!fo||fo===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);po(),uo(fo,e,n)})}}function go(){if(s.panelsPanel.hidden||s.panelsList.contains(document.activeElement))return;let e=eo().filter(e=>e!==s.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,F(i,`aria-label`,()=>`${to(e)} on`),i.addEventListener(`change`,()=>lo(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,P(a,()=>to(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});s.panelsList.replaceChildren(...e)}function _o(){$=nn();for(let e of ro){let t=document.getElementById(e),n=no.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(oo(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}$.order=[...ro],so(),$=nn();try{localStorage.removeItem(tn)}catch{}go()}function vo(e){if(!e||io())return;let t=Qa(s.adminPanel);if(!t)return;let n=[...t.children].filter(Za).find(e=>$a(e)===$a(s.adminPanel));n&&n!==s.adminPanel&&n.before(s.adminPanel),s.adminPanel.removeAttribute(`data-collapsed`),s.adminPanel.removeAttribute(`data-closed`)}s.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=s.panelsPanel.hidden||s.panelsPanel.hasAttribute(`data-closed`)||s.panelsPanel.hasAttribute(`data-collapsed`);s.panelsPanel.hidden=!t,s.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(s.panelsPanel.hasAttribute(`data-closed`)&&lo(s.panelsPanel,!1),s.panelsPanel.hasAttribute(`data-collapsed`)&&co(s.panelsPanel,!1),go(),s.panelsPanel.showPopover?.(),s.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):s.panelsPanel.hidePopover?.()}),s.panelsPanel.addEventListener(`toggle`,()=>{let e=s.panelsPanel.matches(`:popover-open`);s.panelsToggle.setAttribute(`aria-expanded`,String(e&&!s.panelsPanel.hasAttribute(`data-collapsed`))),e||(s.panelsPanel.hidden=!0)}),s.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof s.panelsPanel.hidePopover!=`function`&&(s.panelsPanel.hidden=!0,s.panelsToggle.setAttribute(`aria-expanded`,`false`),s.panelsToggle.focus({preventScroll:!0}))}),s.panelsReset.addEventListener(`click`,_o),s.panelsSave.addEventListener(`click`,()=>{ao();let e=s.panelsSave.textContent??`Save setup`;s.panelsSave.textContent=`Saved`,window.setTimeout(()=>{s.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{ho(),go()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),ho(),so(),Wa(),Ga(),Er(),ur(),s.browse.addEventListener(`click`,()=>{if(!s.directory.hidden){s.directory.hidden=!0;return}gr(),s.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),s.disconnect.addEventListener(`click`,()=>{z.close(),s.listenOnly.hidden=!0,E=-1,s.sharePanel.hidden=!0,s.publishPanel.hidden=!0,s.adminPanel.hidden=!0,s.catalogsPanel.hidden=!0,F(s.catalogsPanel,`data-title`,()=>p(`Catalogs on this server`)),m=``,ae=``,Jr(),Co(!1),d=`local`,se=`idle`,w=``,V()});async function yo(){if(d!==`remote`||z.shareLink===``){s.sharePanel.hidden=!0;return}s.sharePanel.hidden=!1;let e=Ro(),t=globalThis.location.origin;s.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,s.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,s.sharePhone.hidden=!0,s.shareSend.hidden=!0,s.liveControls.hidden=!0;let r=``;try{let e=await n(`/api/directory`);e.ok&&(r=(await e.json()).callIn??``)}catch{}Ne=r,bt();let i=null;try{let r=await n(z.url(`/api/live/state`));r.ok&&(i=await r.json()),i?.url&&(e=i.url,ae=i.url,s.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(i){if(je=i.live,Me=i.live?i.code:``,Ne=r,s.liveControls.hidden=s.adminPanel.hidden||!i.possible,s.goLive.hidden=i.live,s.stopLive.hidden=!i.live,s.sharePhone.hidden=!1,!i.live){s.sharePhone.textContent=i.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(!r){s.sharePhone.textContent=`Listed. The code for the phone line is ${i.code}.`,s.shareSend.hidden=!1;return}s.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),Wo(r),document.createTextNode(` and key `),Wo(i.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),s.shareSend.hidden=!1}}let bo=null,xo=null,So=0,Co=e=>{bo&&clearInterval(bo),bo=null,So+=1,xo?.abort(),xo=null,j=null,Lr(),e&&(wo(),bo=setInterval(()=>{document.visibilityState===`visible`&&wo()},Rr))};async function wo(){if(d!==`remote`||xo)return;let e=new AbortController;xo=e;let t=j===null;t&&Br(e,!0);let r=So,i=z.url(`/api/streams`),a=setTimeout(()=>e.abort(),8e3);try{let t=await n(i,{signal:e.signal,cache:`no-store`});if(!t.ok)return;let a=await t.json();if(e.signal.aborted||r!==So||d!==`remote`||i!==z.url(`/api/streams`))return;_=a.server.carries!==!1,a.server.name&&a.server.name!==m&&(m=a.server.name,s.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${m}`),Jr()),j=a,zo(a),V(),To(a)}catch{}finally{clearTimeout(a),t&&Br(e,!1),xo===e&&(xo=null)}}function To(e){Lr(),O&&In()}function Eo(e){let t=ct(),n=e.restreams??[],r=[],i=e.server.playing,a=!s.adminPanel.hidden;i&&r.push(Bo({key:`live`,title:Ye(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${Ye(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&&Oo(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:Lo(`live`)}:{},direct:i?z.url(`/api/live`):``}));for(let e of n)r.push(Bo({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:()=>{At(e.at)},link:``,direct:z.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=z.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}×`),a&&t.error&&i.push(t.error),r.push(Bo({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{ko({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:Lo(`channel:${t.id}`),direct:n,onRestart:(a||Ke&&Y!==``&&t.startedBy===Y)&&t.via===`pull`?()=>{Mo(t.id,t.name)}:void 0,onStop:a||Ke&&Y!==``&&t.startedBy===Y?()=>Po(t.id,t.name):void 0,onRename:a||Ke&&Y!==``&&t.startedBy===Y?()=>{No(t.id,t.name)}:void 0}))}return r}async function Do(){if(d===`remote`)try{if((await n(z.media(B(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;T=Y===``?`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.`,Y===``&&s.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),V()}catch{}}async function Oo(e){E=-1,O=null,A={kind:`live`},Ae(e,`auto`),await k(()=>R.load({title:e||`Live`,artist:``,album:``,duration:0,url:z.url(`/api/live`),video:!0,objectUrl:!1},!0)),qn(!0),T=`Watching what this server is playing. Everyone here sees the same thing.`,V()}async function ko(e,t=!0,n){let r=j?.channels.find(t=>t.id===e.id);!e.playlist&&r?.playlist&&(e={...e,playlist:r.playlist}),E=-1,O=e,t&&(de=0),t&&(A=n??{kind:`channel`}),t&&Ae(e.name,A?.link||Qn(e.name)?`auto`:`channel`);let i=e.video&&Xe(),a=e.video&&((e.playlist?.length??0)>1||e.id.startsWith(`folder-`));await k(()=>R.load({title:e.name,artist:``,album:``,duration:0,url:z.url(i||a?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),qn(e.video),O===e&&(T=`Watching ${e.name}, live on this server.`),V()}function Ao(){let e=O;return e?Pe?!0:de>=5?(T=`${e.name} stopped, and did not come back.`,O=null,A=null,V(),!0):(de+=1,T=`${e.name} started over; rejoining…`,V(),Pe=setTimeout(()=>{Pe=null,O===e&&ko(e,!1)},2e3),!0):!1}function jo(e){s.partiesNote.hidden=!1,s.partiesNote.textContent=e,G(e)}async function Mo(e,t){jo(`Restarting ${t}…`);try{let r=await n(z.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),i=await r.json().catch(()=>({}));jo(r.ok?`${t} is dialling its source again.`:i.error??`that did not work`)}catch{jo(`could not reach the server`)}wo()}async function No(e,t){let r=globalThis.prompt(`Call ${t}…`,t);if(r===null)return;let i=r.trim();if(i!==``&&i!==t){jo(`Renaming ${t}…`);try{let r=await n(z.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:i})}),a=await r.json().catch(()=>({}));jo(r.ok?`${t} is now ${i}.`:a.error??`that did not work`)}catch{jo(`could not reach the server`)}O?.id===e&&(O={...O,name:i}),wo(),V()}}async function Po(e,t){jo(`Taking ${t} off the air…`);try{let r=await n(z.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),i=await r.json().catch(()=>({}));if(jo(r.ok?`${t} is off the air.`:i.error??`that did not work`),!r.ok)return!1}catch{return jo(`could not reach the server`),!1}return O?.id===e&&(O=null,R.stop()),!0}function Fo(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 Io(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{T=e,V();return}n===`✓`||n===`✓`?c(t,`check`):P(t,()=>p(n)),setTimeout(()=>{t.innerHTML=r},1200)}function Lo(e,t=0){let n=Ro();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 Ro(){if(ae!==``)return ae;let e=d===`remote`?z.shareLink:``;return/\/admin\//.test(e)?``:e}function zo(e){if(x===``)return;let t=x;if(t===`live`){x=``,e.server.playing?Oo(e.server.nowPlaying):(T=`Nothing is playing on this server right now.`,V());return}if(t.startsWith(`link:`)){x=``,Yn(t.slice(5));return}if(t.startsWith(`golive:`)){x=``,s.linkUrl.value=t.slice(7),Er().then(()=>dr());return}if(t.startsWith(`track:`)){x=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&At(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&&(x=``,ko({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Bo(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${y(z.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 o=document.createElement(`button`);o.type=`button`,o.className=`button`,tt(o,e.playLabel??`Join party`),o.hidden=e.key.startsWith(`channel:`)&&O?.id===e.key.slice(8),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,c(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Io(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Io(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,n=>{Fo(t,n,e.onStop,()=>void wo())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,F(o,`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=`⋯`,F(u,`aria-label`,()=>`${p(`Show more`)}: ${e.title}`),a.removeChild(o),l.append(u,a),t.append(n,o),a.childElementCount&&t.append(l),t}let Vo=``;function Ho(e,t){Vo=e;let n=e!==``&&t===e;s.loadHome.hidden=e===``,s.homeNote.hidden=e===``,e!==``&&(s.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,s.loadHome.disabled=!1)}s.loadHome.addEventListener(`click`,()=>{Vo!==``&&(s.loadHome.disabled=!0,G(`Reading this server's files…`),(async()=>{try{let e=await n(z.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Vo})}),t=await e.json();G(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{G(`could not reach the server`)}finally{s.loadHome.disabled=!1}})())});let Uo=async e=>{s.goLive.disabled=!0,s.stopLive.disabled=!0,s.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await n(z.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),r=await t.json();s.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${r.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:r.error??`that did not work`}catch{s.shareNote.textContent=`could not reach the server`}finally{s.goLive.disabled=!1,s.stopLive.disabled=!1,await yo()}};s.goLive.addEventListener(`click`,()=>void Uo(!0)),s.stopLive.addEventListener(`click`,()=>void Uo(!1));function Wo(e){let t=document.createElement(`b`);return t.textContent=e,t}s.shareCopy.addEventListener(`click`,()=>{s.shareLink.select(),navigator.clipboard?.writeText(s.shareLink.value).then(()=>{s.shareNote.textContent=`Copied. Send it to anybody.`},()=>{s.shareNote.textContent=`Copy it from the box above.`})}),s.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=s.shareTo.value.trim();t!==``&&(async()=>{s.shareNote.textContent=`Sending…`;try{let e=await n(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:Ro()})}),r=await e.json();s.shareNote.textContent=e.ok?`Sent to ${r.sent??t}.`:r.error??`that did not send`,e.ok&&(s.shareTo.value=``)}catch{s.shareNote.textContent=`could not send that`}})()}),s.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(rr,s.listenHere.checked?`1`:`0`)}catch{}d===`remote`&&(async()=>{s.listenHere.checked?(await z.send({type:`stop`}),await Vt(C.index)):(R.stop(),E=-1),V()})()}),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===s.transport)switch(e.key){case` `:e.preventDefault(),Ut();return;case`s`:qt();return;case`n`:case`ArrowRight`:Kt(1);return;case`p`:case`ArrowLeft`:Kt(-1);return;case`ArrowDown`:e.preventDefault(),At(Math.min(st()-1,B()+1));return;case`ArrowUp`:e.preventDefault(),At(Math.max(0,B()-1));return}});let Go=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Go=e,s.install.hidden=!1}),s.install.addEventListener(`click`,()=>{Go?.prompt(),Go=null,s.install.hidden=!0});try{let e=localStorage.getItem(nr);e!==null&&(s.volume.value=String(Math.round(Number(e)*100)),R.volume=Number(e));let t=localStorage.getItem(er);t&&(s.remoteUrl.value=t),localStorage.getItem(rr)===`0`&&(s.listenHere.checked=!1)}catch{}(async()=>{if(s.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await Dt(e)===null)return;let t=await wt(e);t&&t.trackCount!==0&&(s.remoteUrl.value=e,d=`remote`,T=``,z.connect(e),Co(!0),ba(),V())})(),Vr();let Ko=()=>{document.visibilityState===`visible`&&!s.partiesPanel.hasAttribute(`data-closed`)&&Vr()},qo=setInterval(Ko,Rr);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(Vr(),wo())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(qo),bo&&clearInterval(bo),Fr?.abort(),xo?.abort(),Fr=null,xo=null,So+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(qo),qo=setInterval(Ko,Rr),Ko(),d===`remote`&&Co(!0))}),(()=>{if(ar||Fe!==``)return;let e=()=>R.source!==``||R.playing||he()||O!==null,t=async()=>{try{let e=await(await n(`/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``},r=new Audio;r.volume=.7;let i=()=>{ar=!0},a=()=>{document.removeEventListener(`pointerdown`,a),document.removeEventListener(`keydown`,a),i(),setTimeout(()=>{e()||R.playJingle(r).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return r.src=t,R.playJingle(r).then(i,()=>{document.addEventListener(`pointerdown`,a,{once:!0}),document.addEventListener(`keydown`,a,{once:!0})})})})(),V(),requestAnimationFrame(Hn)}or(),Ie(),I(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{e as n,u as t};
22
+ `))>=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`){if(this.options.error?.(e))return;throw dn(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=`${this.options.scheme??`live-translate`}:${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(dn(`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)}});if(this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t,e),e.audio===!1){let e=this.clips.get(t);e.ended=!0,e.taken=!0,e.controller.close()}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)}},zn=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,Bn=class extends Fn{constructor(e){super(e,{workletUrl:zn,processor:`nixamp-audio-tap`})}},Vn=3,Hn=1,Un=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*Hn: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*Vn: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?Hn:Vn):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?Hn:Vn):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}},Wn=class extends Rn{constructor(e){super({path:`/api/v1/speech/shared`,scheme:`nixamp-shared`,...e})}},Gn=e=>new Intl.NumberFormat(f.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),U=e=>document.getElementById(e),Kn=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=U(`translation-purchase`);plan=U(`translation-plan`);coin=U(`translation-coin`);buy=U(`translation-checkout`);note=U(`translation-purchase-note`);checkoutLink=U(`translation-checkout-link`);constructor(e){this.options=e,U(`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})}),U(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),U(`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=`$`,F(e,`title`,()=>p(`Buy translated audio`)),F(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 P(t,()=>`${e.name} · ${Gn(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${p(`Audio credit`)}: ${Gn(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?` · ✓`:``}`:``;P(U(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),P(U(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),P(U(`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.`:``),U(`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));U(`translation-plan-description`).textContent=`${Gn(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,U(`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,U(`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}}},qn=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,Jn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,Yn=/\s+(?:vs\.?|v\.?|at|@)\s+/i,Xn=/^(?: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 Zn(e){let t=e.replace(Jn,``).replace(Jn,``).trim().split(Yn);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!Xn.test(t)})}function Qn(e){let t=String(e??``).trim();return t===``?!1:Zn(t.replace(qn,``))||Zn(t)}function $n(e,t){if(e.dataset.longStringScroller===`true`)return;e.dataset.longStringScroller=`true`,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=!1,o=null,s=()=>{n=0;let c=matchMedia(`(prefers-reduced-motion: reduce)`).matches?r:i+(r-i)*.22;if(i=Math.abs(r-c)<.5?r:c,t.style.setProperty(`--path-shift`,`${i}px`),Math.abs(r-i)>=.5){n=requestAnimationFrame(s);return}a&&(a=!1,delete t.dataset.pan,t.style.removeProperty(`--path-shift`),o=setTimeout(()=>{o=null,e.style.removeProperty(`min-height`)},280))},c=()=>{n||=requestAnimationFrame(s)};e.addEventListener(`pointerenter`,n=>{n.pointerType===`mouse`&&matchMedia(`(hover: hover) and (pointer: fine)`).matches&&(o!==null&&(clearTimeout(o),o=null),e.style.minHeight=`${e.getBoundingClientRect().height}px`,a=!1,t.dataset.pan=`true`)}),e.addEventListener(`pointermove`,n=>{if(t.dataset.pan!==`true`)return;let i=getComputedStyle(e),a=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),o=Math.max(0,t.scrollWidth-(e.clientWidth-a));if(o<=0)return;let s=e.getBoundingClientRect(),l=Math.max(0,Math.min(1,(n.clientX-s.left)/Math.max(1,s.width)));if(l<=.02)r=0;else if(l>=.98)r=-o;else{let e=l*l*(3-2*l);r=-o*e}c()}),e.addEventListener(`pointerleave`,()=>{r=0,a=!0,c()})}var er=`nixamp.remote`,tr=`nixamp.defaultServer`,nr=`nixamp.volume`,rr=`nixamp.listenHere`,ir=1e4,ar=!1;function W(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function or(){let e=new URLSearchParams(location.search).get(`embed`)===`1`,t=``;function n(e,n){let r=new URL(e instanceof Request?e.url:String(e),location.href);if(!t||r.origin!==location.origin||!r.pathname.startsWith(`/api/v1/`))return globalThis.fetch(e,n);let i=new Headers(n?.headers??(e instanceof Request?e.headers:void 0));return i.set(`authorization`,`Bearer ${t}`),globalThis.fetch(e,{...n,headers:i})}document.body.classList.toggle(`classroom-embed`,e);let r=null;try{r=localStorage.getItem(Bt)}catch{}let i=Ht(navigator.userAgent,location.search,navigator.maxTouchPoints,r);if(document.body.classList.toggle(`tv`,i),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Bt,i?`1`:`0`)}catch{}let a=document.getElementById(`tv-toggle`);a&&(P(a,()=>i?`TV mode: on`:p(`TV mode`)),a.title=i?`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.`,a.addEventListener(`click`,()=>{try{localStorage.setItem(Bt,i?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let o=Wt(i),s={status:W(`status`),source:W(`source`),install:W(`install`),video:W(`video`),audio:W(`audio`),title:W(`title-line`),album:W(`album-line`),meta:W(`meta-line`),metaBlurb:W(`meta-blurb`),liveLine:W(`live-line`),downloadNow:W(`download-now`),wayInHere:W(`way-in-here`),embed:W(`embed`),embedFrame:W(`embed-frame`),linkForm:W(`link-form`),linkUrl:W(`link-url`),linkServer:W(`link-server`),linkGoLive:W(`link-go-live`),goLiveNow:W(`go-live-now`),elapsed:W(`elapsed`),total:W(`total`),seek:W(`seek`),fullscreen:W(`fullscreen`),copyNow:W(`copy-now`),copyNixamp:W(`copy-nixamp`),schoolLive:W(`school-live`),canvas:W(`spectrum`),glyphs:W(`glyphs`),levels:W(`levels`),playlist:W(`playlist`),livePlaylist:W(`live-playlist`),livePlaylistPanel:W(`live-playlist-panel`),playlistPager:W(`playlist-pager`),crumbs:W(`crumbs`),filter:W(`filter`),playlistTitle:W(`playlist-panel`),note:W(`note`),linkNote:W(`link-note`),logList:W(`log-list`),files:W(`files`),folder:W(`folder`),remoteUrl:W(`remote-url`),remoteServer:W(`remote-server`),remoteForm:W(`remote-form`),remoteState:W(`remote-state`),disconnect:W(`disconnect`),browse:W(`browse`),panelsToggle:W(`panels-toggle`),panelsPanel:W(`panels-panel`),panelsList:W(`panels-list`),panelsSave:W(`panels-save`),panelsReset:W(`panels-reset`),accountForm:W(`account-form`),accountEmail:W(`account-email`),accountPassword:W(`account-password`),accountSubmit:W(`account-submit`),accountToggle:W(`account-toggle`),accountForgot:W(`account-forgot`),accountProviders:W(`account-providers`),accountPanel:W(`account-panel`),accountElsewhere:W(`account-elsewhere`),welcome:W(`welcome`),welcomeCreate:W(`welcome-create`),welcomeBrowse:W(`welcome-browse`),welcomeHide:W(`welcome-hide`),accountSignOut:W(`account-signout`),accountNote:W(`account-note`),personaForm:W(`persona-form`),personaHandle:W(`persona-handle`),personaVoice:W(`persona-voice`),personaProfile:W(`persona-profile`),personaNote:W(`persona-note`),adminPanel:W(`admin-panel`),adminNote:W(`admin-note`),adminSaid:W(`admin-said`),adminConnections:W(`admin-connections`),publishPanel:W(`publish-panel`),publishNote:W(`publish-note`),publishList:W(`publish-list`),adminRestream:W(`admin-restream`),adminReplace:W(`admin-replace`),adminSource:W(`admin-source`),adminName:W(`admin-name`),adminAdd:W(`admin-add`),homeNote:W(`home-note`),loadHome:W(`load-home`),directory:W(`directory`),recentNote:W(`recent-note`),recentList:W(`recent-list`),followingNote:W(`following-note`),followingList:W(`following-list`),serversPanel:W(`servers-panel`),serversNote:W(`servers-note`),serversList:W(`servers-list`),favoritesPanel:W(`favorites-panel`),favoritesNote:W(`favorites-note`),favoritesList:W(`favorites-list`),favHere:W(`fav-here`),partyRoom:W(`party-room`),partyTitle:W(`party-title`),partyMeta:W(`party-meta`),partyRoomNote:W(`party-note`),partyWatch:W(`party-watch`),partyCopy:W(`party-copy`),partyEnd:W(`party-end`),partyChat:W(`party-chat`),partyChatForm:W(`party-chat-form`),partyChatInput:W(`party-chat-input`),partyChatSend:W(`party-chat-send`),partyChatNote:W(`party-chat-note`),partiesPanel:W(`parties-panel`),partiesNote:W(`parties-note`),partiesList:W(`parties-list`),partyForm:W(`party-form`),partyCode:W(`party-code`),partyJoin:W(`party-join`),connectionsNote:W(`connections-note`),connectionsList:W(`connections-list`),catalogsPanel:W(`catalogs-panel`),catalogsNote:W(`catalogs-note`),catalogsForm:W(`catalogs-form`),catalogSource:W(`catalog-source`),catalogName:W(`catalog-name`),catalogsList:W(`catalogs-list`),catalogsCrumbs:W(`catalogs-crumbs`),catalogsFilter:W(`catalogs-filter`),catalogsEntries:W(`catalogs-entries`),notifyPanel:W(`notify-panel`),notifyNote:W(`notify-note`),notifyWeb:W(`notify-web`),notifyEmail:W(`notify-email`),notifySms:W(`notify-sms`),notifyPhone:W(`notify-phone`),notifyPhoneForm:W(`notify-phone-form`),notifyPhoneNote:W(`notify-phone-note`),directoryNote:W(`directory-note`),directoryList:W(`directory-list`),sharePanel:W(`share-panel`),trollboxPanel:W(`trollbox-panel`),trollboxNote:W(`trollbox-note`),trollboxList:W(`trollbox-list`),trollboxForm:W(`trollbox-form`),trollboxInput:W(`trollbox-input`),trollboxMic:W(`trollbox-mic`),trollboxEdit:W(`trollbox-edit`),trollboxEditLabel:W(`trollbox-edit-label`),transcriptPanel:W(`transcript-panel`),transcriptNote:W(`transcript-note`),transcriptOn:W(`transcript-on`),transcriptLanguage:W(`transcript-language`),transcriptAudio:W(`transcript-audio`),transcriptVoiceSettings:W(`transcript-voice-settings`),transcriptBackground:W(`transcript-background`),transcriptBackgroundLevel:W(`transcript-background-level`),transcriptBackgroundValue:W(`transcript-background-value`),transcriptAudioNote:W(`transcript-audio-note`),transcriptSpeakers:W(`transcript-speakers`),transcriptList:W(`transcript-list`),subtitle:W(`subtitle`),shareNote:W(`share-note`),shareLink:W(`share-link`),shareCopy:W(`share-copy`),sharePhone:W(`share-phone`),shareSend:W(`share-send`),liveControls:W(`live-controls`),goLive:W(`go-live`),stopLive:W(`stop-live`),shareTo:W(`share-to`),listenOnly:W(`listen-only`),listenHere:W(`listen-here`),volume:W(`volume`),volumeToggle:W(`volume-toggle`),prev:W(`prev`),playPause:W(`play-pause`),transport:W(`transport`),stop:W(`stop`),next:W(`next`),shareNow:W(`share-now`),refreshPlayer:W(`refresh-player`),appVersion:W(`app-version`)};s.appVersion.textContent=`nixamp 0.34.0`;let c=(e,t)=>{Re(e,t)};c(s.copyNixamp,`link`);let l=document.createElement(`a`);if(l.className=`button`,l.href=`#account-panel`,l.hidden=!0,P(l,()=>p(`Sign in`)),s.trollboxNote.after(l),e){let e=document.createElement(`div`);e.className=`classroom-caption-controls`,e.append(s.transcriptOn.closest(`label`),s.transcriptLanguage.closest(`label`)),s.transcriptPanel.prepend(e),s.transcriptPanel.classList.remove(`panel`,`col-b`),s.transcriptPanel.hidden=!1,document.querySelector(`.classroom-player`).append(s.transcriptPanel),document.querySelector(`#app`).append(s.trollboxPanel);let t=document.createElement(`dialog`);t.className=`classroom-sign-in`,F(t,`aria-label`,()=>p(`Sign in`));let n=document.createElement(`button`);n.type=`button`,n.className=`button`,P(n,()=>p(`Close`)),n.addEventListener(`click`,()=>t.close()),s.accountPanel.classList.remove(`panel`,`col-a`),t.append(n,s.accountPanel),document.body.append(t),l.addEventListener(`click`,e=>{e.preventDefault(),t.showModal()}),t.addEventListener(`close`,()=>{(l.hidden?s.trollboxList:l).focus({preventScroll:!0})})}let u=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,d=`local`,m=``,h=[],g=``,_=!0,v=``;function y(e){try{return new URL(e).origin}catch{return e}}let b=!1,ee=globalThis.location?.search??``,x=``,te=0,ne=new Map,re=e=>ne.get(K(e))??null;function ie(e,t){let n=n=>{b=n,x=``,s.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),s.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,c(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`,c(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:Y?`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=``,S=[],oe=0,C=dt(),se=`idle`,w=``,T=`Pick files, or connect to a nixamp running somewhere else.`,ce=!1,E=-1,D=null,le=0,O=null;function ue(e){return e?/^https?:\/\//i.test(e)?e:z.url(e):``}let de=0,fe=0,pe=!1,he=()=>!R.needsInteraction&&(fe>0||pe);async function k(e){fe+=1,V();try{return await e()}finally{--fe,V()}}let A=null,j=null,_e=``,ve=null,be=``,M=null,Se=null,Ce=0;function we(){s.embed.hidden||(s.embedFrame.src=`about:blank`),s.embed.hidden=!0}let Te=null,N=``,ke=null;function Ae(e,t,r=null,i=!1){let a=`${t}|${e}`;if(N=a,ke&&clearTimeout(ke),ke=null,!i){if(Te?.key===a)return;Te=null}if(d!==`remote`||e.trim()===``)return;let o=new URLSearchParams({name:e,kind:t});r&&o.set(`year`,String(r)),n(z.url(`/api/enrich?${o}`)).then(e=>e.ok?e.json():{match:null}).then(n=>{if(N!==a)return;Te={key:a,match:n.match??null},V();let i=Te.match;i?.kind===`fixture`&&Lt(i)!==`post`&&(ke=setTimeout(()=>{ke=null,!(N!==a||R.source===``&&!O)&&Ae(e,t,r,!0)},6e4))}).catch(()=>void 0)}let je=!1,Me=``,Ne=``,Pe=null,Fe=``,Ie=``,Le=``,Ve=Array(24).fill(0),He=Array(24).fill(0),Ue=[],I=()=>d===`remote`&&!s.listenHere.checked,We=()=>d===`remote`&&!s.adminPanel.hidden,Ke=!1,qe=()=>We()||d===`remote`&&Ke;function Xe(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:s.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function $e(){if(d!==`remote`||M)return null;if(A?.catalog&&A.entry)return{kind:`entry`,catalog:A.catalog,entry:A.entry};if(O)return{kind:`channel`,id:O.id,name:O.name};let e=C.tracks[B()];return e&&(R.source!==``||I())?{kind:`track`,index:B(),name:_t(e)}:null}async function et(e,t){t.disabled=!0;let r=e.kind===`entry`?e.entry.title:e.name;T=`Putting ${r} on the air…`,V();try{let i=``,a=``,o=!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`,s=await n(z.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),c=await s.json().catch(()=>({}));if(!s.ok){T=s.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:c.error??`${r} would not go on the air.`,V();return}a=e.kind===`channel`?e.id:c.channel??``,o=c.video!==!1,i=`channel:${a}`}if(We()&&(je?await n(z.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await Uo(!0)),await yo(),wo(),a!==``&&O?.id!==a){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 ko({id:a,name:r,video:o},!0,t)}let s=Lo(i),c=Me?` Call ${Ne||`the line`} and key ${Me} to talk about it.`:``;s===``?T=`${r} is on the air and you are watching it.${c}`:(await Io(s,t,`✓`),T=`${r} is on the air and you are watching it. Link copied.${c}`),V()}catch{T=`could not reach the server`,V()}finally{t.disabled=!1}}function tt(e,t=`Join party`){c(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);P(n,()=>` ${p(t)}`),e.append(n),F(e,`title`,()=>p(/join/i.test(t)?`Join live`:t))}tt(s.partyJoin);function nt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,c(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(),et(e(),n)}),n}let R=new lt({audio:s.audio,video:s.video},{readable:e=>z.owns(e),onTime:(e,t)=>{let n=S[oe];d===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),V()},onEnded:()=>{Ao()||or()||It()||d===`remote`&&E<0&&!I()||Kt(1)},onState:()=>V(),onBusy:e=>{pe!==e&&(pe=e,V())},onError:e=>{if(!Ao()&&!(Ce!==0&&Date.now()-Ce<2e3)){if(Se&&e===`this browser cannot play that format`){let e=Se.url;if(Se=null,Ce=Date.now(),qe()){T=`That site will not let a page play it directly; going live with it on ${m||`the server`} instead.`,V(),s.linkUrl.value=e,dr();return}T=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,V();return}T=e,V(),Do()}}}),rt=s.video.closest(`section`)??s.video.parentElement;rt&&(async()=>{if(R.enableAds(rt,await ge({},ee)),me(ee)){let e=()=>{rt.scrollIntoView({block:`center`}),R.playAdNow()};addEventListener(`pointerdown`,e,{once:!0}),addEventListener(`keydown`,e,{once:!0})}})();let at=()=>I()&&!R.jinglePlaying,z=new St({onSnapshot:e=>{let t=e.tracks!==void 0||C.index!==e.index;if(C=ft(C,e),x.startsWith(`track:`)&&C.tracks.length>0){let e=Number(x.slice(6));if(x=``,Number.isInteger(e)&&e>=0&&e<C.tracks.length){let t=te;Vt(e).then(()=>{t>0&&(R.seek(t),setTimeout(()=>R.seek(t),600))})}}at()&&(Ve=e.bars.length>0?e.bars:Ve,He=Pt(He,Ve)),V(),t&&j&&To(j)},onStatus:(e,t)=>{se=e,w=t??``,V()}}),st=()=>d===`remote`?C.tracks.length:S.length,B=()=>d===`remote`?I()||E<0?C.index:Math.min(E,Math.max(0,C.tracks.length-1)):oe,ct=()=>{let e=j?.server.nowPlaying||`Live`;return(!ve||ve.tracks!==C.tracks||ve.index!==C.index||ve.fallback!==e)&&(ve={tracks:C.tracks,index:C.index,fallback:e,value:Ze(C.tracks,C.index,e)}),ve.value},ut=()=>d===`remote`&&!O&&A?.kind===`live`,pt=()=>ut()?ct().fullTitle:vt(),_t=e=>{let t=Be(e);return e.folder?`${e.folder} / ${t}`:t},vt=()=>{if(O){let e=O.id,t=j?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||O.name}if(M)return M.label;if(ut())return ct().title;let e=d===`remote`?C.tracks[B()]:S[B()];return e?_t(e):p(`Nothing loaded.`)},yt=()=>{if(O)return`live on this server`;if(M)return`playing here, in this browser`;if(ut()){let{context:e,position:t}=ct();return[e,t,`live on ${m||`this server`}`].filter(Boolean).join(` · `)}return(d===`remote`?C.tracks[B()]:S[B()])?.album||`—`};function bt(){if(d!==`remote`||O===null&&A?.kind!==`live`){s.liveLine.hidden=!0,s.liveLine.replaceChildren(),delete s.liveLine.dataset.drawn;return}let e=m||`this server`,t=O?O.name:ct().fullTitle,n=[O?`Live on ${e}: `:`Live from ${e}, now playing: `,Wo(t)],r=O?j?.channels.find(e=>e.id===O?.id)?.code??``:je?Me:``;if(r){let e=Ne?document.createElement(`a`):Wo(`the line`);Ne&&(e.textContent=Ne,e.setAttribute(`href`,`tel:${Ne.replace(/[^+\d]/g,``)}`)),n.push(`. To talk about it, call `,e,` and key `,Wo(r),`.`)}let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);s.liveLine.dataset.drawn!==i&&(s.liveLine.dataset.drawn=i,s.liveLine.hidden=!1,s.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let xt=()=>I()?C.tracks[B()]?.duration??0:R.duration,Ct=()=>I()?C.position:R.position,kt=()=>I()?C.playing:R.playing;async function At(e){if(d===`remote`){if(I()){await z.send({type:`play`,index:e});return}await Vt(e);return}let t=S[e];t&&(oe=e,O=null,A={kind:`file`},await k(()=>R.load(t,!0)),qn(t.video),Jn(),V())}function It(){return!D||D.length<2?!1:(le=(le+1)%D.length,At(D[le]),!0)}function Rt(e){e.length!==0&&(D=[...e],le=0,At(D[0]))}async function Vt(e){let t=C.tracks[e];t&&(E=e,O=null,A={kind:`file`},Ae(t.title,`auto`),await k(()=>R.load({title:_t(t),artist:t.artist,album:t.album,duration:t.duration,url:z.media(e,0),video:t.video===!0,objectUrl:!1},!0)),qn(t.video===!0),Jn())}async function Ut(){if(R.needsInteraction){await R.play(),V();return}if(I()){await z.send({type:`toggle`});return}st()!==0&&(R.playing?R.pause():R.position>0?await R.play():await At(B()),V())}async function Kt(e){D=null;let t=st();if(t!==0){if(I()){await z.send({type:e>0?`next`:`prev`});return}await At((B()+e+t)%t)}}async function qt(){if(D=null,we(),M=null,Se=null,I()){await z.send({type:`stop`});return}O=null,A=null,R.stop(),Ve=Array(24).fill(0),He=[...Ve],V()}let Jt=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Yt=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],Zt=``;function $t(){let e=[],t=``,n=null,r=O?j?.channels.find(e=>e.id===O?.id):void 0;O&&r?.ended&&be!==O.id&&(be=O.id,Yr(`${O.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=R.source===``&&!O&&!(I()&&C.tracks[B()]);if(!i){O&&r?.ended?e.push(`ENDED`):O?e.push(A?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):A?.kind===`vod`?e.push(`ON DEMAND`):A?.kind===`live`?e.push(`LIVE`):d===`remote`&&I()?e.push(`ON THE SERVER`):e.push(`FILE`),!s.video.hidden&&s.video.videoWidth>0?e.push(`${s.video.videoWidth}×${s.video.videoHeight}`):s.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 ${ze(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),We()&&r.error&&e.push(r.error)):d===`remote`&&!O?(C.tracks[B()]&&st()>0&&e.push(`${ut()?`library track`:`track`} ${B()+1} of ${st()}`),I()&&j&&e.push(`${j.server.playing?`playing`:`stopped`} on ${m||`the server`}`)):d===`local`&&st()>0&&e.push(`track ${B()+1} of ${st()}`),A?.catalog!==void 0&&(A.kind===`channel`?O!==null:A.kind===`vod`&&R.source!==``)&&A?.catalog&&(e.push(A.entry?.group?`${A.catalog.name} › ${A.entry.group}`:A.catalog.name),t=A.entry?.logo??``),t===``&&O&&(t=ue(r?.art??O.art));let i=Te?.key===N?Te.match:null;if(i?.kind===`fixture`)n=zt(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(O&&A?.link){let t=``;try{t=new URL(A.link.url).hostname.replace(/^www\./,``)}catch{}e.push(A.link.extractor&&A.link.extractor!==`direct`&&A.link.extractor!==`generic`?`${A.link.extractor} · ${t}`:t||`link`)}je&&Me&&I()&&!O&&A?.kind!==`live`&&e.push(Ne?`☎ ${Ne} · key ${Me}`:`☎ code ${Me}`)}let a=Te?.key===N?Te.match:null,o=!i&&!n&&a?.summary?a.summary:``,c=e.map(e=>/^on air \d/.test(e)?`on air`:e),l=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${c.join(`|`)}|${o}`;if(l===Zt){let t=s.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}Zt=l,s.meta.hidden=e.length===0,s.metaBlurb.textContent=o,s.metaBlurb.hidden=o===``;let u=[];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)),u.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=a?.kind===`title`&&t===a.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),u.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,u.push(e)}s.meta.replaceChildren(...u)}function V(){let e=st(),t=kt(),n=he();P(s.status,()=>p(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),s.status.dataset.playing=n?`loading`:String(t),P(s.title,()=>vt()),s.title.classList.toggle(`with-context`,ut()),s.album.classList.toggle(`with-context`,ut()),(ut()||O)&&Jn(),bt(),$t(),s.goLiveNow.hidden=!qe()||O!==null||ut()||$e()===null;let r=t?`${pt()} · ${u}`:u;document.title!==r&&(document.title=r),s.copyNow.hidden=R.source===``,s.copyNixamp.hidden=aa()===``,s.schoolLive.hidden=aa()===``||!Ba||Y===``,s.shareNow.hidden=ia()===``,Li(),Xi(),s.downloadNow.hidden=!(O&&A?.link?.download),cr(),s.album.textContent=yt();let i=Ct(),a=xt();s.elapsed.textContent=ze(i),s.total.textContent=a>0?ze(a):`--:--`,ce||(s.seek.value=String(a>0?Math.round(i/a*1e3):0),s.seek.disabled=a<=0||I()),s.playPause.textContent=t?`❚❚`:`▶`,F(s.playPause,`aria-label`,()=>p(t?`Pause`:`Play`)),F(s.seek,`aria-valuetext`,()=>`${ze(R.position)} ${f.language===`en`?`of`:`/`} ${ze(R.duration)}`),F(s.volume,`aria-valuetext`,()=>f.number(Number(s.volume.value)/100,{style:`percent`})),F(s.playlistTitle,`data-title`,()=>d===`remote`?`Files on ${m||`this server`} (${e.toLocaleString(f.language)})`:`${p(`Playlist`)} (${f.number(e)})`),P(s.source,()=>d===`remote`?`connected · ${m||z.address.replace(/^https?:\/\//,``)||`—`}`:S.length>0?`local · ${S.length} files`:p(`no source`)),U(),P(s.remoteState,()=>d===`remote`?`${se}${w?` — ${w}`:``}`:p(`not connected`)),s.remoteState.dataset.status=d===`remote`?se:`idle`,s.disconnect.hidden=d!==`remote`;let o=R.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:d===`remote`&&C.note!==``?C.note:T;s.note.textContent=o,s.note.hidden=o===``,s.linkNote.textContent=o,s.linkNote.hidden=o===``,Yr(o),In(),s.glyphs.textContent=Ve.map(Yt).join(``);let[c,l]=at()?C.levels:R.levels();s.levels.textContent=Jt(c,l)}let rn=``,H=``,un=0;function dn(e){Ge(s.playlist),H=e,un=0,rn=``,In()}function fn(e,t,n,r,i){if(s.playlistPager.hidden=n<=1,n<=1){s.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{Ge(s.playlist),un=t,rn=``,In()}),i},o=document.createElement(`span`);o.className=`pager-where`,P(o,()=>`${r+1}–${i} of ${e.toLocaleString(f.language)}`),s.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),o,a(`Next ›`,t+1,`The page after this one`))}function mn(e){if(s.crumbs.hidden=!e,!e)return;let t=H===``?[]:H.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`,()=>dn(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))}),s.crumbs.replaceChildren(...r)}function hn(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 o=document.createElement(`button`);if(o.type=`button`,o.className=`row-main`,o.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),o.append(i,a),r.replaceChildren(o),o.addEventListener(`click`,t=>{t.stopPropagation(),dn(H===``?e:`${H}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,c(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),Rt(n)}),r.append(i)}return d===`remote`&&n.length>0&&qe()&&r.append(nt(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let An=null,jn=``,Mn=``,Nn=[],Pn=(e,t)=>{t.title=t.textContent??``,$n(e,t)};function Fn(e,t){let n=document.createElement(`span`);n.className=`name row-file`,n.textContent=e;let r=document.createElement(`span`);r.className=`row-path`,r.textContent=t;let i=document.createElement(`span`);i.className=`row-label`;let a=document.createElement(`span`);a.className=`row-value`,a.append(n);let o=document.createElement(`span`);return o.className=`row-value`,o.append(r),i.append(a),Pn(a,n),Pn(o,r),{label:i,pathView:o}}function In(){let e=(O?j?.channels.find(e=>e.id===O?.id):void 0)?.playlist,t=!!(O&&e?.length);s.livePlaylistPanel.hidden===t&&(s.livePlaylistPanel.hidden=!t);let n=t?O.id:``,r=t?e:[];if(Mn!==n||Nn.length!==r.length||Nn.some((e,t)=>e!==r[t])){Mn=n,Nn=r;let e=r.map((e,t)=>{let n=document.createElement(`li`);n.className=`row file-row live-file-row`,n.dataset.index=String(t);let r=document.createElement(`span`);r.className=`n`,r.textContent=String(t+1);let{label:i,pathView:a}=Fn(e.slice(e.lastIndexOf(`/`)+1),e),o=document.createElement(`span`);return o.className=`row-main`,o.append(i,r),n.append(o,a),n});L(s.livePlaylist,...e)}let i=d===`remote`?C.tracks:S,a=`${d}:${O?.id??``}:${H}:${s.filter.value}:${un}:${qe()}:${s.adminPanel.hidden}`;if(rn&&An===i&&jn===a){Rn();return}An=i,jn=a;let l=d===`remote`?C.tracks.map(e=>({name:Be(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):S.map(e=>({name:Be(e),seconds:e.duration,group:``,folder:``,remote:!1})),u=s.filter.value.trim().toLowerCase(),f=l.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>u===``||`${e.folder}/${e.name}`.toLowerCase().includes(u)),p=e=>u!==``||H===``||e===H||e.startsWith(`${H}/`),m=e=>e===H,h=e=>{let t=H===``?e:e.slice(H.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},g=new Map;for(let e of f){if(!p(e.folder)||m(e.folder))continue;let t=h(e.folder);t!==``&&g.set(t,(g.get(t)??0)+1)}let _=f.filter(e=>m(e.folder)&&p(e.folder)),v=[...g].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),y=Gt(v.length+_.length,un,o);un=y.page;let b=v.slice(y.from,y.to),ee=_.slice(Math.max(0,y.from-v.length),Math.max(0,y.to-v.length)),x=`${d}:${H}:${u}:${y.page}/${o}:${v.join(`,`)}:${_.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(x!==rn){rn=x,mn(u===``&&(v.length>0||H!==``)),fn(v.length+_.length,y.page,y.pages,y.from,y.to);let e=[];for(let[t,n]of b){let r=H===``?t:`${H}/${t}`,i=f.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(hn(t,n,i))}let t=``,n=_.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(zn(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 o=r.folder?`${r.folder} / ${r.name}`:r.name,{label:s,pathView:l}=Fn(r.name,r.folder?`${r.folder}/${r.name}`:r.name),u=document.createElement(`span`);u.className=`time`,u.textContent=r.seconds>0?ze(r.seconds):`--:--`;let f=document.createElement(`button`);f.type=`button`,f.className=`row-main`,f.setAttribute(`aria-label`,`Play ${o}${r.seconds>0?`, ${ze(r.seconds)}`:``}`),f.append(s,a,u),i.append(f);let p=document.createElement(`span`);p.className=`row-play-glyph`,c(p,`play`),i.append(p),d===`remote`&&qe()&&O===null&&!ut()&&i.append(nt(()=>({kind:`track`,index:r.index,name:o}),o)),i.classList.add(`file-row`),i.append(l),e.push(i)}L(s.playlist,...e)}Rn()}function Rn(){let e=O?j?.channels.find(e=>e.id===O?.id):void 0;if(e?.playlist&&e.playlist.length>0){let t=e.entry??0;for(let e of Array.from(s.livePlaylist.children)){let n=e,r=Number(n.dataset.index),i=Number.isInteger(r)&&r===t;n.classList.toggle(`selected`,i),n.classList.toggle(`playing`,i),n.classList.toggle(`live-file-current`,i),i?n.setAttribute(`aria-current`,`true`):n.removeAttribute(`aria-current`)}for(let n of Array.from(s.playlist.children)){let r=n,i=Number(r.dataset.index),a=C.tracks[i],o=a?`${a.folder?`${a.folder}/`:``}${Be(a)}`:``,s=!!o&&o===e.playlist[t];r.classList.toggle(`selected`,s),r.classList.toggle(`playing`,!1),s?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}return}for(let e of Array.from(s.livePlaylist.children)){let t=e;t.classList.remove(`selected`,`playing`,`live-file-current`),t.removeAttribute(`aria-current`)}let t=B(),n=kt();for(let e of Array.from(s.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 zn(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!==``&&!s.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(),Fo(t,n,()=>Vn(e),()=>In())}),t.append(n)}return t}async function Vn(e){try{let t=await n(z.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),r=await t.json();return G(t.ok?`Removed ${r.removed??0} tracks from ${e}.`:r.error??`that did not work`),t.ok}catch{return G(`could not reach the server`),!1}}function Hn(){let e=s.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(at())He=Pt(He,Ve);else{let e=R.read();e.length>0&&(Ue.length!==25&&(Ue=jt(24,e.length)),Ve=Nt(Ve,Mt(e,Ue)),He=Pt(He,Ve))}if(i){let t=getComputedStyle(document.documentElement);Ft(i,{width:e.width,height:e.height},Ve,He,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(kt()||R.jinglePlaying){s.glyphs.textContent=Ve.map(Yt).join(``);let[e,t]=at()?C.levels:R.levels();s.levels.textContent=Jt(e,t)}if(kt()){s.elapsed.textContent=ze(Ct());let e=xt();!ce&&e>0&&(s.seek.value=String(Math.round(Ct()/e*1e3)))}requestAnimationFrame(Hn)}let Gn=``;function U(){if(d!==`remote`){s.wayInHere.hidden=!0,Gn=``;return}let e=We()&&!b,t=ae||z.address,n=e?null:re(z.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Gn)return;Gn=r;let[i,a]=ie({name:m||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,s.wayInHere.replaceChildren(i,a),s.wayInHere.hidden=!1}function qn(e){s.video.hidden=!e,s.fullscreen.hidden=!e,we(),M=null,Se=null}function Jn(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=O?ue(j?.channels.find(e=>e.id===O?.id)?.art??O.art):``,t=JSON.stringify([vt(),yt(),e]);t!==_e&&(_e=t,navigator.mediaSession.metadata=new MediaMetadata({title:vt(),album:yt(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void Ut()),navigator.mediaSession.setActionHandler(`pause`,()=>void Ut()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void Kt(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void Kt(-1)))}document.addEventListener(`click`,()=>{R.resumeAfterInteraction().catch(()=>{})}),s.filter.addEventListener(`input`,()=>{un=0,rn=``,In()}),s.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())}),s.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(D=null,At(n))}),s.fullscreen.addEventListener(`click`,()=>{let e=s.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),s.prev.addEventListener(`click`,()=>void Kt(-1)),s.next.addEventListener(`click`,()=>void Kt(1)),s.stop.addEventListener(`click`,()=>void qt()),s.playPause.addEventListener(`click`,()=>void Ut());async function Yn(e){let t=en(e,Xe());if(!t){if(!qe()){T=d===`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.`,V();return}await sr(e);return}if(O=null,R.stop(),t.kind===`embed`){A={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},qn(!1),s.embedFrame.src=t.src,s.embed.hidden=!1,M={url:e,label:t.label,kind:`embed`},T=`Playing ${t.label} here, in this browser.`,V();return}if(t.kind===`list`){await Xn(e,t.label);return}A={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await k(()=>R.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),qn(t.video),M={url:e,label:t.label,kind:`direct`},T=`Playing ${t.label} here, in this browser.`,V()}async function Xn(e,t){T=`Reading ${t}…`,V();let r=``;try{let t=await n(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);r=await t.text()}catch(e){T=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,V();return}let i=Qt(r,e);if(i.entries.length===0){T=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,V();return}Se={url:e,title:i.title||t,entries:i.entries,at:0},await Zn()}async function Zn(){let e=Se,t=e?.entries[e.at];if(!e||!t)return;let n=Xt(t.url);A={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await k(()=>R.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),Se!==null&&(qn(n),M={url:e.url,label:e.title,kind:`direct`},Se=e,T=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,V())}function or(){let e=Se;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Zn(),!0)}async function sr(e){if(d!==`remote`){T=`Pick a server to go live on, or connect to one, to put a link on the air.`,V();return}T=`Asking ${m||`the server`} to fetch ${e}…`,V(),await k(async()=>{let t,r={};try{t=await n(z.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),r=await t.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!t.ok||!r.channel){T=r.error??`that link would not play.`;return}try{await n(z.url(`/api/channels/${encodeURIComponent(r.channel)}/keep`),{method:`POST`})}catch{}await ko({id:r.channel,name:r.name||e,video:r.video!==!1,art:r.art},!0,{kind:`channel`,link:{url:e,extractor:r.extractor??``,download:r.download===!0,live:r.live===!0,video:r.video!==!1}}),(r.entries??0)>1&&(T=`${r.name||e} is on the air: ${r.entries} entries, played in turn.`)}),V()}s.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.linkUrl.value.trim();t!==``&&Yn(t)});function cr(){let e=d===`remote`?z.address:``,t=h.filter(t=>y(t.url)!==y(e)),n=JSON.stringify({here:e,name:m,carries:_,others:t});if(n===g||document.activeElement===s.linkServer)return;g=n;let r=[];if(e!==``&&_){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${m||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}s.linkServer.replaceChildren(...r),s.linkServer.value=e!==``&&!_&&t[0]?t[0].url:``,s.linkServer.hidden=t.length===0}function lr(){let e=d===`remote`?y(z.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!h.some(t=>y(t.url)===e)){let n=document.createElement(`option`);n.value=z.address,n.textContent=m||e,t.push(n)}for(let e of h){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}s.remoteServer.replaceChildren(...t);let r=h.find(t=>y(t.url)===e);s.remoteServer.value=r?.url??``}async function ur(){try{let e=await n(`/api/directory`);if(!e.ok)return;h=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),cr(),lr()}catch{}}async function dr(){let e=s.linkUrl.value.trim()||M?.url||``;if(e===``){T=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,V();return}let t=s.linkServer.value;if(t!==``&&(d!==`remote`||y(t)!==y(z.address))){let n=h.find(e=>e.url===t)?.name??t;v=e,T=`Connecting to ${n} to go live with it…`,V(),fr(t);return}if(d!==`remote`){T=h.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,V();return}if(!_){T=`${m||`This server`} has no ffmpeg, so it cannot carry a link.`+(h.length>0?` Pick a server to go live on, beside the link.`:``),V();return}if(!qe()){T=`Sign in to nixamp.com to go live here, or use the server's control link.`,V();return}await sr(e)}function fr(e){let t=s.linkUrl.value.trim();b=!0,x=``,s.remoteUrl.value=e,s.remoteForm.requestSubmit(),s.linkUrl.value=t}s.linkGoLive.addEventListener(`click`,()=>{dr()}),s.linkServer.addEventListener(`change`,()=>{let e=s.linkServer.value;e!==``&&fr(e)}),s.downloadNow.addEventListener(`click`,()=>{let e=A?.link;if(!e||d!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(z.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),T=`Fetching it through the server; your browser will save it when it arrives.`,V()}),s.goLiveNow.addEventListener(`click`,()=>{let e=$e();e&&et(e,s.goLiveNow)}),s.seek.addEventListener(`input`,()=>{ce=!0}),s.seek.addEventListener(`change`,()=>{let e=xt();e>0&&R.seek(Number(s.seek.value)/1e3*e),ce=!1}),s.volume.addEventListener(`input`,()=>{let e=Number(s.volume.value)/100;R.volume=e,s.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),s.volumeToggle.textContent=e===0?`🔇`:`🔊`,F(s.volumeToggle,`aria-label`,()=>p(e===0?`Unmute`:`Mute`));try{localStorage.setItem(nr,String(e))}catch{}}),s.volumeToggle.addEventListener(`click`,()=>{let e=Number(s.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(nr));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}s.volume.value=e?String(t):`0`,s.volume.dispatchEvent(new Event(`input`))}),s.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let pr=e=>{e.addEventListener(`change`,()=>{let t=it(Array.from(e.files??[]));if(t.length===0){T=`Nothing playable in that selection.`,V();return}ot(S),S=t,oe=0,d=`local`,z.close(),Co(!1),T=``,At(0)})};pr(s.files),pr(s.folder),s.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.remoteUrl.value,{base:n,key:r}=gt(t);if(n===``){T=`That is not an address.`,V();return}(async()=>{se=`connecting`,V();let e=Ot(n);if(e){se=`error`,w=e,T=e,v=``,d=`local`,V();return}if(await Dt(n,void 0,r)===null){se=`error`;let e=Tt(n);w=e?`needs the server's name`:`not answering`,T=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,v=``,d=`local`,V();return}let i=await Et(n,r);if(i){se=`error`,w=i,T=i,v=``,d=`local`,V();return}d=`remote`,T=``;try{localStorage.setItem(er,t.trim())}catch{}z.connect(t),Co(!0),ba(),Er(),yo(),V()})()}),s.remoteServer.addEventListener(`change`,()=>{let e=s.remoteServer.value;e!==``&&(b=!1,x=``,s.remoteUrl.value=e,s.remoteForm.requestSubmit())});let mr=``,hr=null,gr=async(e=!1)=>{s.directory.hidden=!1,e||(s.directoryNote.textContent=`Looking for live streams…`,L(s.directoryList)),hr||=setInterval(()=>{!s.directory.hidden&&document.visibilityState===`visible`&&gr(!0)},ir);let t;try{let r=await n(`/api/directory`);if(!r.ok)throw Error(String(r.status));let i=await r.json();t=i.streams??[],h=t.map(e=>({name:e.name,url:e.url})),cr();let a=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:i.recent??[],me:Y});if(e&&a===mr)return;mr=a,kr(i.recent??[])}catch{e||(s.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(L(s.directoryList),t.length===0){s.directoryNote.textContent=`Nobody is streaming right now.`;return}s.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`),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`);a.className=`detail`;let o=[`${e.tracks.toLocaleString(f.language)} files to browse`];e.playing!==!1&&e.nowPlaying?o.push(`playing ${e.nowPlaying}`):o.push(`player idle`),e.code&&o.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),a.textContent=o.join(` · `),a.title=a.textContent,r.append(i,a);let l=e.admin??re(e.url),u=(t,n=``)=>{b=t,x=n,s.remoteUrl.value=t?e.url:l??e.url,s.directory.hidden=!0,document.body.classList.remove(`route-directory`),s.remoteForm.requestSubmit()},d=document.createElement(`ul`);d.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let o=e.lineup?.find(e=>e.name===t);if(o?.art&&/^https?:\/\//i.test(o.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=o.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}o?.about&&(r.title=o.about);let s=document.createElement(`button`);s.type=`button`,s.className=`icon`,c(s,`party`),s.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),s.title=`Join live: ${t} on ${e.name}`,s.addEventListener(`click`,()=>u(!0,`channel:${t}`));let f=document.createElement(`button`);f.type=`button`,f.className=`icon`,c(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:${o?.id??t}`)}`;f.addEventListener(`click`,e=>{e.stopPropagation(),Io(p,f,`✓`)});let m=document.createElement(`button`);m.type=`button`,m.className=`icon`,c(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(o?.id??t)}`,h=n.toString()}catch{}if(m.addEventListener(`click`,e=>{e.stopPropagation(),Io(h,m,`✓`)}),n.append(r,s,f,m),o?.startedBy&&Y&&o.startedBy===Y&&l){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,c(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),u(!1,`channel:${o?.id??t}`)}),n.append(e)}d.append(n)}let[p,m]=ie({name:e.name,view:e.url,admin:l},()=>{s.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(r,p,m),Y&&t.append(qr(e.url,e.name)),e.ownerId&&Y&&e.ownerId!==Y&&t.append(Pa(e.ownerId,e.name)),d.childElementCount>0&&t.append(d),e.ownerId&&Y&&e.ownerId===Y){let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Take off the list`,r.addEventListener(`click`,t=>{t.stopPropagation(),r.disabled=!0,(async()=>{try{let t=await n(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),r=await t.json().catch(()=>({}));s.directoryNote.textContent=t.ok?`${e.name} is off the list.`:r.error??`that did not work`}catch{s.directoryNote.textContent=`could not reach the directory`}finally{await gr()}})()}),t.append(r)}s.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!s.directory.hidden&&gr(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),gr()}let _r=/^\/live\/([^/]+)\/?$/.exec(location.pathname);if(_r){document.body.classList.add(`route-party`),s.partyRoom.hidden=!1;let e=decodeURIComponent(_r[1]??``),t=null,r=0,i=``,a=new Set,o=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}`},c=(e,t=!1)=>{let n=t?s.partyChatNote:s.partyRoomNote;n.hidden=e===``,n.textContent=e},l=()=>{if(!t)return;let e=t.party.playing?(Date.now()-r)/1e3:0,n=t.party.positionNow+e,i=[t.event.status===`live`?t.party.playing?`▶ ${o(n)}`:`❚❚ ${o(n)}`:`ended`,t.party.mediaTitle,`code ${t.party.partyCode}`,t.host?`yours`:``].filter(Boolean);s.partyMeta.textContent=i.join(` · `)},u=()=>{if(!t)return;document.title=`${t.event.title} — nixamp`,s.partyTitle.textContent=t.event.title||t.party.partyCode;let e=t.links.partyUrl||t.party.partyUrl;s.partyWatch.href=e||`#`,s.partyWatch.hidden=e===``;let n=t.party.origin;try{n=new URL(e).hostname}catch{}s.partyWatch.title=`The film plays on ${n} (opens in a new tab)`,s.partyEnd.hidden=!t.host||t.event.status!==`live`;let r=t.event.chatEnabled!==!1&&t.event.status===`live`;s.partyChatForm.hidden=!r,s.partyChatInput.disabled=!r||Y===``,s.partyChatSend.disabled=!r||Y===``,c(r?Y===``?`Sign in to say something; everybody can read.`:``:t.event.status===`live`?`Chat is off for this party.`:`This party has ended.`,!0),l()},d=async()=>{try{let i=await n(`/api/v1/watch-parties/${encodeURIComponent(e)}`,{cache:`no-store`});if(!i.ok){c(i.status===404?`No party here. It may have ended, or the link is not one.`:`Could not open this party. Try again in a moment.`);return}t=await i.json(),r=Date.now(),c(``),u()}catch{c(`Could not open this party. Try again in a moment.`)}},f=async()=>{if(t&&t.event.chatEnabled!==!1)try{let e=new URL(`/api/v1/events/${encodeURIComponent(t.event.id)}/chat`,location.origin);i&&e.searchParams.set(`after`,i);let r=await n(e.toString(),{cache:`no-store`});if(!r.ok)return;let o=((await r.json()).messages??[]).filter(e=>!a.has(e.id));if(!o.length){if(!s.partyChat.childElementCount){let e=document.createElement(`li`);e.className=`hint`,e.textContent=`No messages yet. Say hi!`,s.partyChat.replaceChildren(e)}return}s.partyChat.querySelector(`.hint`)&&s.partyChat.replaceChildren();let c=s.partyChat.scrollHeight-s.partyChat.scrollTop-s.partyChat.clientHeight<60;for(let e of o){a.add(e.id),i=e.createdAt;let t=document.createElement(`li`),n=document.createElement(`b`);n.textContent=e.authorName,t.append(n,document.createTextNode(e.body)),s.partyChat.append(t)}for(;s.partyChat.childElementCount>200;)s.partyChat.firstElementChild?.remove();c&&(s.partyChat.scrollTop=s.partyChat.scrollHeight)}catch{}};s.partyChatForm.addEventListener(`submit`,e=>{e.preventDefault();let r=s.partyChatInput.value.trim();t&&r!==``&&(s.partyChatSend.disabled=!0,(async()=>{try{let e=await n(`/api/v1/events/${encodeURIComponent(t.event.id)}/chat`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({body:r})}),i=await e.json().catch(()=>({}));if(!e.ok){c(i.error??`That did not send.`,!0);return}s.partyChatInput.value=``,c(``,!0),await f()}catch{c(`That did not send.`,!0)}finally{s.partyChatSend.disabled=Y===``}})())}),s.partyCopy.addEventListener(`click`,()=>{navigator.clipboard?.writeText(t?.links.nixampUrl||location.href).then(()=>{s.partyCopy.textContent=`Copied`,setTimeout(()=>{s.partyCopy.textContent=`Copy room link`},2e3)},()=>c(`Could not copy that.`))}),s.partyEnd.addEventListener(`click`,()=>{t&&t.host&&(async()=>{if(!(await n(`/api/v1/watch-parties/${encodeURIComponent(t.party.partyCode)}/end`,{method:`POST`})).ok){c(`Could not end it.`);return}await d()})()}),(async()=>{await d(),await f()})(),setInterval(l,1e3),setInterval(()=>void d(),1e4),setInterval(()=>void f(),4e3),document.addEventListener(`nixamp:account`,()=>u())}let vr=null,yr=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,br=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,xr=``,Sr=``,Cr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===xr)return;xr=t,s.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)}s.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,``],[yr(t.network),`network-${t.network}`],[br(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)}s.adminConnections.append(e)}};function G(e){s.adminSaid.textContent=e,s.adminSaid.hidden=e===``}let wr=async()=>{try{let e=await n(z.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),r=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,i=t.active??0;s.adminNote.textContent=r===0?`${i} listening now.`:`${i} listening now, and ${r} with the page open.`,Cr(t.connections??[]),Tr(t.publish??[],(t.channels??[]).map(e=>e.id)),Ho(t.home??``,t.root??``),wo()}catch{s.adminNote.textContent=`lost touch with the server`}};function Tr(e,t){s.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Sr)return;if(Sr=n,e.length===0){L(s.publishList);return}let r=e.length-t.length;s.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,L(s.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`,P(o,()=>p(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let Er=async()=>{if(d!==`remote`){s.adminPanel.hidden=!0,s.publishPanel.hidden=!0,vr&&clearInterval(vr),vr=null;return}let e=!1,t=null,r=!1,i=!1;try{let a=await n(z.url(`/api/admin`));if(a.ok){let n=await a.json();e=n.allowed===!0,t=n.as??null,r=n.claimed===!0,i=n.member===!0}}catch{e=!1}let a=e||i;b&&(e=!1),Ke=a&&!e;let o=s.partiesList.dataset.adminMode!==String(e);if(s.adminPanel.hidden=!e,o&&(s.partiesList.dataset.adminMode=String(e),s.partiesList.querySelectorAll(`details[open]`).forEach(e=>e.removeAttribute(`open`)),Lr()),vo(e),v!==``){let e=v;v=``,qe()?sr(e):(T=`Sign in to nixamp.com to go live here.`,V())}if(vr&&clearInterval(vr),vr=null,wo(),ba(),yo(),s.listenOnly.hidden=e,!e){s.listenOnly.textContent=r?`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}s.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,wr(),vr=setInterval(()=>void wr(),2e3)};function Dr(e,t,r){let i=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;G(`Starting ${t||e}…`),(async()=>{try{let a=await n(z.url(`/api/channels/${encodeURIComponent(i)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...r===void 0?{source:e}:{at:r},...t?{name:t}:{}})}),o=await a.json();if(!a.ok){G(o.error??`that did not work`);return}G(`${o.channel?.name||t||e} is on the air.`),s.adminSource.value=``,s.adminName.value=``,yo(),wo()}catch{G(`could not reach the server`)}})()}s.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=s.adminSource.value.trim();t&&Dr(t,s.adminName.value.trim())}),s.adminAdd.addEventListener(`click`,()=>{let e=s.adminSource.value.trim();if(!e)return;G(`Reading ${e}…`);let t=s.adminReplace.checked,r=s.adminName.value.trim();(async()=>{try{let i=await n(z.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...r?{name:r}:{},...t?{replace:!0}:{}})}),a=await i.json();G(i.ok?t?`Now serving ${e}.`:a.added===0?`Everything there was already in the playlist.`:`Added ${a.added??0} tracks from ${e}.`:a.error??`that did not work`),i.ok&&(s.adminSource.value=``,s.adminName.value=``,yo(),wo())}catch{G(`could not reach the server`)}})()});let Or=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`},kr=e=>{let t=[],n=Y?e.filter(e=>e.ownerId&&e.ownerId!==Y):[];if(s.recentNote.hidden=n.length===0,n.length===0){L(s.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 ${Or(e.endedAt)}`:`ended ${Or(e.endedAt)}`,r.append(i,a),n.append(r,Pa(e.ownerId,e.name)),t.push(n)}L(s.recentList,...t)},Ar=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 jr(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?`▶ ${Ar(e.party.positionNow)}`:`❚❚ ${Ar(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`,tt(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=`⋯`,F(c,`aria-label`,()=>`${p(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let Mr=[],Nr=[],Pr=!1,Fr=null,Ir=``;function Lr(){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=d===`remote`&&j?y(z.address):``;for(let e of Mr){let r=y(e.url);if(!r||r===n)continue;let i=[],a=(t,n)=>{let a=document.createElement(`li`);a.dataset.liveKey=`${r}:${t}`,a.className=`party-row`;let o=document.createElement(`span`);o.className=`party-name`,o.textContent=n,o.title=n;let c=document.createElement(`button`);c.type=`button`,tt(c),F(c,`aria-label`,()=>`${p(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{b=!0,x=t,s.remoteUrl.value=e.url,s.remoteForm.requestSubmit()}),a.append(o,c),i.push(a)};e.playing!==!1&&e.nowPlaying&&a(`live`,Ye(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);a(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&j&&t(n,j.server.name||m||n,Eo(j));for(let e of Nr){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=jr(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...s.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),Je(e.querySelector(`ul`),n.rows),i.push(e)}Je(s.partiesList,i),s.partiesNote.hidden=e.size>0,e.size||P(s.partiesNote,()=>p(Pr?`No parties live right now.`:`Loading…`))}let Rr=5e3,zr=new Set,Br=(e,t)=>{t?zr.add(e):zr.delete(e),zr.size?s.partiesPanel.dataset.loading=`true`:delete s.partiesPanel.dataset.loading};async function Vr(){if(e||(Ir!==Y&&(Fr?.abort(),Fr=null,Nr=[],Ir=Y,Lr()),Fr))return;let t=new AbortController;Fr=t;let r=!Pr;r&&Br(t,!0);let i=Y,a=setTimeout(()=>t.abort(),8e3),o=async e=>{let r=await n(e,{signal:t.signal,cache:`no-store`});return{ok:r.ok,status:r.status,body:r.ok?await r.json():null}};try{let[e,n]=await Promise.allSettled([o(`/api/directory`),i?o(`/api/v1/watch-parties`):Promise.resolve(null)]);if(Fr!==t||i!==Y||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(Mr=e.value.body.streams??[],Pr=!0,s.directory.dataset.available=String(Mr.length>0),go()),n.status===`fulfilled`&&n.value&&(n.value.ok?(Nr=n.value.body.parties??[],Pr=!0):[401,403].includes(n.value.status)&&(Nr=[])),Lr(),!Pr&&!j&&P(s.partiesNote,()=>p(`Could not refresh parties.`))}finally{clearTimeout(a),r&&Br(t,!1),Fr===t&&(Fr=null)}}s.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.partyCode.value.trim();t!==``&&(async()=>{try{let e=await n(`/api/v1/watch-parties/${encodeURIComponent(t)}`),r=await e.json().catch(()=>({}));if(!e.ok){T=r.error??`No party found with that invite code.`,V();return}s.partyCode.value=``,window.location.href=r.links.nixampUrl}catch{T=`Could not look up that party. Try again.`,V()}})()});async function Hr(){if(!Y){s.connectionsNote.hidden=!0,s.connectionsList.hidden=!0;return}try{let e=await n(`/api/v1/oauth/connections`);if(!e.ok){s.connectionsNote.hidden=!0,s.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];s.connectionsNote.hidden=t.length===0,s.connectionsList.hidden=t.length===0,L(s.connectionsList,...t.map(e=>{let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.clientName;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.scope.split(` `).filter(Boolean).join(`, `),r.append(i,a);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,P(o,()=>p(`Disconnect`)),o.addEventListener(`click`,()=>{(async()=>{try{await n(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Hr()})()}),t.append(r,o),t}))}catch{s.connectionsNote.hidden=!0,s.connectionsList.hidden=!0}}let Ur=new Set,K=e=>{try{return new URL(e).origin}catch{return e}},Wr=e=>[...Ur].some(t=>K(t)===K(e));async function Gr(){if(!Y){Ur=new Set,s.favoritesPanel.hidden=!0,Jr();return}try{let e=await n(`/api/v1/favorites`);if(!e.ok){s.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];Ur=new Set(t.map(e=>e.url)),s.favoritesPanel.hidden=t.length===0,s.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,L(s.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)}),qr(e.url,e.name)),t}))}catch{s.favoritesPanel.hidden=!0}Jr()}async function Kr(e,t,r){try{if(!(r?await n(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await n(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){T=r?`Could not save that favourite.`:`Could not remove that favourite.`,V();return}}catch{T=`could not reach nixamp.com`,V();return}if(r)Ur.add(e);else for(let t of[...Ur])K(t)===K(e)&&Ur.delete(t);await Gr()}function qr(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Wr(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=[...Ur].find(t=>K(t)===K(e))??e;Kr(Wr(e)?i:e,t,!Wr(e)).then(r)}),n}function Jr(){let e=d===`remote`?z.shareLink:``;if(s.favHere.hidden=!(Y&&e),s.favHere.hidden)return;let t=Wr(e);s.favHere.textContent=t?`♥`:`♡`,s.favHere.dataset.on=t?`yes`:`no`,s.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,s.favHere.setAttribute(`aria-label`,s.favHere.title)}c(s.copyNow,`copy`),s.copyNow.addEventListener(`click`,()=>{Io(R.source,s.copyNow,`✓`)});function Yr(e){if(e===``||e===Le)return;Le=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),P(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),s.logList.prepend(t);s.logList.children.length>100;)s.logList.lastElementChild?.remove()}let Xr=3e3,q=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,Zr=``,Qr=``,$r=null,ei=!1,ti=new Set,ni=``,ri=null,ii=!1,ai=On(e=>localStorage.getItem(e)),J=Cn(e=>localStorage.getItem(e)),oi=new Set,si=new Set,ci=null,li=``,ui=``,Y=``,di=(()=>{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()}`}})(),fi=null,X=!1,pi=``,mi=!1,hi=!1,gi=``,_i=0,vi=!1,yi=!1;try{s.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let bi=new Un(()=>{yi=!0,vi&&(s.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),xi=()=>{let e=Number(s.transcriptBackgroundLevel.value);bi.setLevel(e/100),s.transcriptBackgroundValue.value=`${e}%`,F(s.transcriptBackgroundLevel,`aria-valuetext`,()=>f.number(e/100,{style:`percent`})),s.transcriptBackgroundLevel.disabled=!s.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(s.transcriptBackgroundLevel.value=e)}catch{}xi(),s.transcriptBackgroundLevel.addEventListener(`input`,()=>{xi();try{localStorage.setItem(`nixamp.backgroundLevel`,s.transcriptBackgroundLevel.value)}catch{}});let Si=new Kn({account:()=>q===``?Y:``,changed:()=>ta()});W(`translation-buy-tools`).append(Si.button()),Si.refresh();let Ci=new Wn({reconnecting:()=>Z.reset(),line:(e,t)=>{ji=0,Mi.push(e),$i(),Z.push(e,t,0)},status:e=>{s.transcriptAudioNote.textContent=e},failed:e=>{pi=e,ui=e,X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei(),s.transcriptAudioNote.textContent=`${e} Original audio restored.`,Si.refresh()}}),Z=new Ln({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(Ci.audio(String(e))):n(e,t)),playing:()=>R.playing,volume:()=>R.volume,active:e=>{vi=e,R.translatedAudio(e),bi.active(e&&R.playing&&s.transcriptBackground.checked)},status:e=>{s.transcriptAudioNote.textContent=e+(yi&&vi?` · background unavailable`:``)},failed:()=>{ui=s.transcriptAudioNote.textContent||`Translated audio stopped.`,X=!1,s.transcriptAudio.checked=!1,Ei()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!Y||q!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!fi||fi.channel!==t.channel||fi.expires<Date.now()+2e4||fi.remaining<t.text.length){let r=await n(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),i=await r.json();if(!r.ok||!i.token||!i.expires)throw Error(i.error||`Sign in to enable translated audio.`);fi={channel:t.channel,token:i.token,expires:i.expires,remaining:2e3}}return fi.remaining-=t.text.length,{authorization:`Bearer ${fi.token}`}}}),wi=new pn({fetcher:(e,t)=>{let r=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&r.set(`x-nixamp-translation-session`,di),n(e,{...t,headers:r})},language:()=>J,speakers:()=>s.transcriptAudio.checked,voices:()=>ci?.voices??[],channel:()=>di,status:e=>{!mi&&!X&&(pi=e),s.transcriptNote.textContent=e},failed:()=>{X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei()},lines:e=>{ji=0,Mi.push(...e),$i(),Oi(),s.transcriptAudio.checked&&Z.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:J,channel:di,speaker:e.speaker,voice:wi.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),Ti=new Bn(e=>{mi&&R.playing&&wi.push(e)});function Ei(){_i++,mi=!1,hi=!1,gi=``,Ti.stop(),wi.reset(),Ci.stop(),bi.stop(),Z.reset(),L(s.transcriptSpeakers)}async function Di(){if((mi||hi)&&gi===R.mediaKey)return;Ei();let e=_i;hi=!0,gi=R.mediaKey;try{if(!Y||q!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=R.audioInput();if(yi=!1,s.transcriptAudio.checked&&s.transcriptBackground.checked&&bi.start(t.context,t.node).then(t=>{t&&e===_i&&bi.active(vi&&R.playing&&s.transcriptBackground.checked)}),s.transcriptAudio.checked&&d===`remote`&&O)await Ci.start(ra(),J),Si.refresh();else{if(s.transcriptAudio.checked&&await Si.startSession(di),e!==_i)return;await Ti.start(t.context,t.node,s.transcriptAudio.checked?2:5)}if(e!==_i)return;mi=!0,X=!0,ji=0,Pi??=setInterval($i,250),s.transcriptNote.textContent=s.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==_i)return;X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei(),pi=t instanceof Error?t.message:`This audio could not be captured.`,s.transcriptNote.textContent=pi}finally{e===_i&&(hi=!1)}}function Oi(){let e=[...wi.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(s.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];P(n,()=>`${p(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,F(i,`aria-label`,()=>`${p(`Speaker voices`)}: ${r}`);for(let e of ci?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,Z.reset()}),e.append(i),s.transcriptSpeakers.append(e)}s.transcriptVoiceSettings.hidden=!s.transcriptAudio.checked;for(let e of s.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[s.audio,s.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(R.showingVideo?s.video:s.audio)&&Ei()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(R.showingVideo?s.video:s.audio)&&X&&ai&&R.playing&&Di()});e.addEventListener(`volumechange`,()=>{Z.setVolume()})}let ki=``,Ai=null,ji=Tn(6,!1),Mi=[],Ni=[],Pi=null;function Fi(){if(d!==`remote`)return null;let{base:e}=gt(Ro());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=O?O.id:A?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Ii(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${q}/api/v1/trollbox?${n.toString()}`}function Li(){let e=Fi(),t=e?`${e.server}|${e.channel}`:``;t!==Zr&&(Zr=t,Qr=``,ti.clear(),s.trollboxList.replaceChildren(),$r&&clearTimeout($r),$r=null,s.trollboxPanel.hidden=e===null,s.trollboxForm.hidden=!0,Ui(!1),e&&(P(s.trollboxNote,()=>`The room for ${vt()||e.channel}. Loading…`),zi()))}function Ri(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);P(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 zi(){let e=Fi(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===Zr&&!ei){ei=!0;try{let r=await n(Ii(e,Qr)),i=await r.json().catch(()=>({}));if(t!==Zr)return;if(!r.ok){s.trollboxNote.textContent=i.error??`The trollbox is not answering.`;return}let a=(i.messages??[]).filter(e=>!ti.has(e.id));for(let e of a)ti.add(e.id),s.trollboxList.append(Ri(e)),Qr=e.createdAt;for(;s.trollboxList.children.length>200;)s.trollboxList.firstElementChild?.remove();let o=i.you??``,c=ni!==o;ni=o,l.hidden=o!==``,q!==``&&(l.href=`${q}/?url=${encodeURIComponent(Ro())}&play=${encodeURIComponent(`channel:${e.channel}`)}#account-panel`),c&&(fi=null,ta()),s.trollboxForm.hidden=o===``,s.trollboxEditLabel.hidden=o===``||!Bi,o===``&&Ui(!1),P(s.trollboxNote,()=>o===``?q===``?`The room for ${vt()||e.channel}. Sign in to say something.`:`The room for ${vt()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${vt()||e.channel}.`)}catch{t===Zr&&(s.trollboxNote.textContent=`The trollbox is not answering.`)}finally{ei=!1,t===Zr&&($r=setTimeout(()=>{document.visibilityState===`visible`?zi():$r=setTimeout(()=>void zi(),Xr)},Xr))}}}s.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Fi(),r=s.trollboxInput.value.trim();t&&r!==``&&(s.trollboxInput.disabled=!0,(async()=>{try{let e=await n(`${q}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:r})}),i=await e.json().catch(()=>({}));if(!e.ok||!i.message){s.trollboxNote.textContent=i.error??`that did not send`;return}s.trollboxInput.value=``,ti.has(i.message.id)||(ti.add(i.message.id),s.trollboxList.append(Ri(i.message)),Qr=i.message.createdAt)}catch{s.trollboxNote.textContent=`The trollbox is not answering.`}finally{s.trollboxInput.disabled=!1}})())});let Bi=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Vi=Bi?vn(e=>MediaRecorder.isTypeSupported(e)):``;s.trollboxMic.hidden=!Bi;function Hi(e){s.trollboxNote.textContent=e,Yr(e)}function Ui(e){let t=ri;if(!t)return;ri=null,clearTimeout(t.stop),clearInterval(t.tick),s.trollboxMic.setAttribute(`aria-pressed`,`false`),s.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(()=>Gi(new Blob(t.chunks,{type:t.recorder.mimeType||Vi||`audio/webm`}),t.startedAt))}async function Wi(){if(ri||ii||ni===``||!Fi())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){Hi(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,Vi?{mimeType:Vi}:{})}catch{for(let t of e.getTracks())t.stop();Hi(`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();ri={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>Ui(!0),_n),tick:setInterval(()=>{s.trollboxMic.textContent=yn(r,Date.now())},500)},t.start(250),s.trollboxMic.setAttribute(`aria-pressed`,`true`),s.trollboxMic.textContent=yn(r,r),Hi(`Listening. Tap the mic again when you have said it (${Math.round(_n/1e3)} s at most).`)}async function Gi(e,t){let r=Fi();if(r&&ni!==``){if(Date.now()-t<400||e.size===0){Hi(`That was too short to hear. Tap, say it, then tap again.`);return}ii=!0,s.trollboxMic.disabled=!0,s.trollboxMic.textContent=`…`,Hi(`Hearing you…`);try{let t=new AudioContext,i;try{i=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let a=new OfflineAudioContext(1,Math.max(1,Math.ceil(i.duration*gn)),gn),o=a.createBufferSource();o.buffer=i,o.connect(a.destination),o.start();let c=ln((await a.startRendering()).getChannelData(0),gn),l=s.trollboxEdit.checked,u=new URLSearchParams(l?{}:{server:r.server,channel:r.channel}),d=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(d)&&u.set(`language`,d);let f=await n(`${q}/api/v1/speech/transcribe?${u.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([c.buffer],{type:`audio/wav`})}),p=await f.json().catch(()=>({}));if(!f.ok){Hi(p.error??`nixamp.com could not hear that.`);return}let m=(p.text??``).trim();if(m===``){Hi(`Heard nothing. Try again, closer to the mic.`);return}if(l||!p.message){let e=s.trollboxInput.value.trimEnd();s.trollboxInput.value=(e===``?m:`${e} ${m}`).slice(0,500),Hi(`Heard: “${m}”. Send it, or fix it first.`);return}Fi()&&!ti.has(p.message.id)&&(ti.add(p.message.id),s.trollboxList.append(Ri(p.message)),Qr=p.message.createdAt),Hi(`Said: “${p.message.body}”`)}catch{Hi(`That recording could not be read here.`)}finally{ii=!1,s.trollboxMic.disabled=!1,s.trollboxMic.textContent=`🎤`}}}s.trollboxMic.addEventListener(`click`,()=>{ri?Ui(!0):Wi()});try{s.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}s.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,s.trollboxEdit.checked?`on`:`off`)}catch{}Hi(s.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Ki(){try{let e=await n(`${q}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){s.personaNote.textContent=t.error??`Could not read your profile.`;return}s.personaHandle.value=t.chosen?t.handle??``:``,F(s.personaHandle,`placeholder`,()=>t.handle||p(`handle`)),s.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,s.personaProfile.value=t.profile??``;let r=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;s.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${qi(t.voice??``)}${r}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${qi(t.voice??``)}${r}.`}catch{s.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function qi(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`}s.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.personaHandle.value.trim(),r={voice:s.personaVoice.value,profile:s.personaProfile.value.trim()};t!==``&&(r.handle=t),s.personaNote.textContent=`Saving…`,(async()=>{try{let e=await n(`${q}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(r)}),t=await e.json().catch(()=>({}));if(!e.ok){s.personaNote.textContent=t.error??`that did not save`;return}await Ki()}catch{s.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&ri&&Ui(!0)});function Ji(){return d===`remote`&&O?{id:O.id,name:O.name,hls:O.video&&Xe()}:R.loaded||M?{id:di,name:vt()||`This audio`,hls:!1}:null}function Yi(){Ei(),fi=null,oi.clear(),si.clear(),Ai?.close(),Ai=null,Pi&&clearInterval(Pi),Pi=null,Mi=[],Ni=[],s.transcriptList.replaceChildren(),s.subtitle.hidden=!0,s.subtitle.textContent=``}function Xi(){let e=Ji(),t=`${e?.id??``}|${R.mediaKey}|${ai}|${J}|${s.transcriptAudio.checked}|${X}|${Y}`;if(t!==ki){if(ki=t,Yi(),s.transcriptPanel.hidden=!1,s.transcriptOn.checked=ai&&(!!O||X||s.transcriptAudio.checked),s.transcriptLanguage.options.length===0)for(let e of Sn){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),P(t,()=>e.code?e.label:p(`Original (auto-detect)`)),s.transcriptLanguage.append(t)}if(s.transcriptLanguage.value=J,ta(),na(),!e){s.transcriptNote.textContent=`Play something to see its captions.`;return}if(!ai){s.transcriptNote.textContent=`Captions are off.`;return}if(pi){s.transcriptNote.textContent=pi;return}s.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,s.transcriptAudio.checked||X?R.playing?Di():s.transcriptNote.textContent=`Press Play to start listening.`:d===`remote`&&O?Zi(e,t):s.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Zi(e,t){let r=6,i=J?`?language=${encodeURIComponent(J)}`:``;try{let a=await n(z.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${i}`)),o=await a.json().catch(()=>({}));if(t!==ki)return;if(!a.ok){s.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){Y&&q===``?(X=!0,Xi()):s.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}r=o.backlog??r}catch{t===ki&&(s.transcriptNote.textContent=`The server did not answer about captions.`);return}ji=Tn(r,e.hls);let a=new EventSource(z.url(`/api/channels/${encodeURIComponent(e.id)}/captions${i}`));Ai=a;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}`;oi.has(e)||(oi.add(e),oi.size>600&&oi.delete(oi.values().next().value),Mi.push(n),t&&s.transcriptAudio.checked&&si.add(n))}};a.addEventListener(`hello`,n=>{if(t!==ki)return;let i=JSON.parse(n.data);ji=Tn(i.backlog??r,e.hls),o(i.lines??[]);let a=Sn.find(e=>e.code===i.language)?.label??i.language,c=Sn.find(e=>e.code===J)?.label??J;if(s.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:J?`${a||`Detected audio`} → ${c}`:`Original audio · ${a||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${q||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,s.transcriptNote.append(` `,e,`.`)}}),a.addEventListener(`line`,n=>{if(t!==ki)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),a=Sn.find(e=>e.code===i)?.label??i,c=Sn.find(e=>e.code===J)?.label??J;s.transcriptNote.textContent=J?`${e.name} · ${a||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${a||`detecting…`}`}),a.addEventListener(`error`,()=>{t===ki&&a.readyState===EventSource.CLOSED&&(s.transcriptNote.textContent=`Captions stopped; the server went away.`)}),Pi=setInterval($i,250)}function Qi(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),P(n,()=>kn(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=wn(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 $i(){let e=Date.now(),{ready:t,still:n}=En(Mi,e,ji);Mi=n;for(let e of t)if(Ni.push(e),s.transcriptList.append(Qi(e)),si.delete(e)&&s.transcriptAudio.checked&&J){let t=new URLSearchParams({at:String(e.at),language:J,voice:`auto`});Z.push(e,z.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),ji)}for(;Ni.length>200;)Ni.shift();for(;s.transcriptList.children.length>200;)s.transcriptList.firstElementChild?.remove();let r=Dn(Ni,e,ji),i=s.transcriptList.children,a=r?Ni.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let o=R.playing&&r!==null&&!s.video.hidden&&s.video.offsetHeight>0;s.subtitle.hidden=!o,o&&r&&(s.subtitle.textContent!==r.text&&(s.subtitle.textContent=r.text),s.subtitle.style.top=`${s.video.offsetTop+s.video.offsetHeight-s.subtitle.offsetHeight-10}px`)}s.transcriptOn.addEventListener(`change`,()=>{ai=s.transcriptOn.checked,X=ai&&(!O||s.transcriptAudio.checked),ai||(s.transcriptAudio.checked=!1,Z.disable());try{localStorage.setItem(bn,ai?`on`:`off`)}catch{}Xi()}),s.transcriptLanguage.addEventListener(`change`,()=>{pi=``,ui=``,J=Cn(()=>s.transcriptLanguage.value),!J&&s.transcriptAudio.checked&&(s.transcriptAudio.checked=!1,X=!1,Z.disable());try{J?localStorage.setItem(xn,J):localStorage.removeItem(xn)}catch{}Xi()});function ea(){if(J)return J;let e=navigator.language.split(`-`)[0]||`en`;return Sn.some(t=>t.code===e)&&ci?.languages.includes(e)?e:`en`}function ta(){let e=Y!==``&&q===``,t=e&&Si.loaded()&&!!Ji()&&!!ci?.languages.includes(ea());s.transcriptAudio.disabled=!t,s.transcriptVoiceSettings.contains(document.activeElement)||(s.transcriptVoiceSettings.hidden=!s.transcriptAudio.checked),t?s.transcriptAudio.checked||P(s.transcriptAudioNote,()=>ui||p(`Original audio.`)):(s.transcriptAudio.checked=!1,Z.disable(),s.transcriptAudioNote.textContent=e?Ji()?Si.loaded()?ui||(ci?`Audio translation is unavailable for this language.`:`Loading voices…`):Si.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function na(){if(!Y||q!==``)return;let e=`/api/v1/speech/voices`;if(li!==e){li=e,ci=null,ui=``,ta();try{let t=await n(e,{signal:AbortSignal.timeout(1e4)}),r=await t.json();if(li!==e)return;if(!t.ok)throw Error(r.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(r.voices)||!Array.isArray(r.languages))throw Error(`This server needs an update for translated audio.`);ci=r}catch(t){if(li!==e)return;ui=t instanceof Error?t.message:`Translated audio is unavailable.`}ta()}}s.transcriptBackground.addEventListener(`change`,()=>{xi();try{localStorage.setItem(`nixamp.backgroundSound`,s.transcriptBackground.checked?`on`:`off`)}catch{}if(bi.stop(),yi=!1,s.transcriptBackground.checked&&s.transcriptAudio.checked&&R.playing){let e=_i,t=R.audioInput();bi.start(t.context,t.node).then(t=>{t&&e===_i&&bi.active(vi&&R.playing&&s.transcriptBackground.checked)})}}),s.transcriptAudio.addEventListener(`change`,()=>{if(pi=``,ui=``,si.clear(),s.transcriptAudio.checked&&!Si.ready()){s.transcriptAudio.checked=!1,Si.open(s.transcriptAudio);return}if(s.transcriptAudio.checked){J=ea();try{localStorage.setItem(xn,J)}catch{}ai=!0,X=!0,Z.enable()}else X=!1,Z.disable();Xi()});function ra(){if(M)return M.url;if(d!==`remote`)return``;let{base:e,key:t}=gt(Ro());if(e===``)return``;if(O)return mt(e,`/api/channels/${encodeURIComponent(O.id)}`,t);if(A?.kind===`live`)return mt(e,`/api/live`,t);if(R.source===``)return``;try{let n=new URL(R.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function ia(){let e=ra();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function aa(){return d===`remote`?O?Lo(`channel:${O.id}`):A?.kind===`live`||ut()?Lo(`live`):``:``}s.shareNow.addEventListener(`click`,()=>{let e=ia();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${pt()} on nixamp`,url:e}).catch(()=>void 0);return}Io(e,s.shareNow,`Copied`)}),s.copyNixamp.addEventListener(`click`,()=>{let e=aa();e!==``&&Io(e,s.copyNixamp,`✓`)});async function oa(){let e=aa();if(e===``||s.schoolLive.disabled)return;let t=s.schoolLive.textContent;s.schoolLive.disabled=!0,s.schoolLive.textContent=`Opening a classroom…`;let r={"content-type":`application/json`};try{let t=await n(`/api/v1/events`,{method:`POST`,headers:r,body:JSON.stringify({kind:`class`,title:Qe(pt())||`Live class`,broadcastUrl:e,visibility:`public`})}),i=await t.json().catch(()=>({}));if(!t.ok||!i.event)throw Error(i.error??`the class could not be made`);let a=i.event,o=await n(`/api/v1/events/${encodeURIComponent(a.id)}/start`,{method:`POST`,headers:r,body:JSON.stringify({version:a.version})}),s=`https://backtoschool.help/live/${encodeURIComponent(a.slug)}`;T=o.ok?`Your class is live on backtoschool.help: ${s}`:`The class is made but not started yet. Open it to start: ${s}`,V(),globalThis.open(s,`_blank`,`noopener`)}catch(e){T=`Could not open a classroom: ${e.message}`,V()}finally{s.schoolLive.disabled=!1,s.schoolLive.textContent=t}}s.schoolLive.addEventListener(`click`,()=>{oa()}),s.favHere.addEventListener(`click`,()=>{let e=Ro()||z.shareLink;if(!e)return;let t=[...Ur].find(t=>K(t)===K(e))??e;Kr(Wr(e)?t:e,m||z.address,!Wr(e)).then(Jr)});let sa=i?o:200,ca=[],Q=null,la=null,ua=``,da=[],fa=0,pa=null,ma=0,ha=null,ga=null,_a=new Map;function va(e,t){ma++,ha?.abort(),pa&&clearTimeout(pa),pa=null,Ge(s.catalogsList),Ge(s.catalogsEntries),Q=e,la=t,ua=``,s.catalogsFilter.value=``,da=[],fa=0,s.catalogsEntries.setAttribute(`aria-busy`,`false`),Sa(),e&&t!==null&&Da(0)}function ya(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 ba(){let e=z.url(`/api/catalogs`);if(ga?.url===e)return ga.promise;let t=xa(e).finally(()=>{ga?.promise===t&&(ga=null)});return ga={url:e,promise:t},t}async function xa(e){if(d!==`remote`){s.catalogsPanel.hidden=!0;return}let t;try{t=await n(e)}catch{e===z.url(`/api/catalogs`)&&(s.catalogsPanel.hidden=!0);return}if(d===`remote`&&e===z.url(`/api/catalogs`)){if(!t.ok){s.catalogsPanel.hidden=!0;return}ca=(await t.json().catch(()=>({}))).catalogs??[],Q&&=ca.find(e=>e.id===Q?.id)??null,Q||(la=null),s.catalogsPanel.hidden=!1,Sa()}}function Sa(){let e=!s.adminPanel.hidden;s.catalogsForm.hidden=!e;let t=ca.reduce((e,t)=>e+t.live,0),n=ca.reduce((e,t)=>e+t.vod,0);s.catalogsNote.textContent=ca.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${ca.length} ${ca.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,Ca();let r=Q!==null&&la!==null;if(s.catalogsList.hidden=r,s.catalogsFilter.hidden=!r,s.catalogsEntries.hidden=!r,r){Oa();return}if(Q){Ta(Q);return}L(s.catalogsList,...ca.map(t=>wa(t,e)))}function Ca(){let e=Q!==null;if(s.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`,()=>va(null,null),!1),n(),t(Q?.name??``,()=>va(Q,null),la===null)];la!==null&&r.push(n(),t(la===``?`All groups`:la,()=>void 0,!0)),s.catalogsCrumbs.replaceChildren(...r)}function wa(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`,P(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 ${ya(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`,()=>{va(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`,()=>{Aa(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,P(r,()=>p(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Fo(n,r,()=>ja(e),()=>void ba())}),n.append(t,r)}return n}async function Ta(e){let t=z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),r=`${t}:${e.refreshedAt}:${e.entries}`,i;s.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=_a.get(r);e||(_a.size>=20&&_a.delete(_a.keys().next().value),e=n(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),_a.set(r,e)),i=await e}catch{if(_a.delete(r),Q?.id!==e.id||la!==null||t!==z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;s.catalogsList.setAttribute(`aria-busy`,`false`),T=`Could not read the groups in ${e.name}.`,V();return}if(Q?.id!==e.id||la!==null||t!==z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;s.catalogsList.setAttribute(`aria-busy`,`false`);let a=[Ea(`All groups`,``,e.entries,e.live,e.vod),...i.map(e=>Ea(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];L(s.catalogsList,...a)}function Ea(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`,P(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`,()=>{va(Q,t)}),a.append(o,l),a}async function Da(e){let t=Q,r=la;if(!t||r===null)return;let i=++ma;ha?.abort();let a=new AbortController;ha=a;let o=z.url(`/api/catalogs`);s.catalogsEntries.setAttribute(`aria-busy`,`true`);let c=new URLSearchParams({group:r,q:ua,offset:String(e),limit:String(sa)}),l;try{let e=await n(z.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${c}`),{signal:a.signal});if(!e.ok)throw Error(String(e.status));l=await e.json()}catch{if(a.signal.aborted||i!==ma)return;s.catalogsEntries.setAttribute(`aria-busy`,`false`),T=`Could not read ${t.name}.`,Oa(),V();return}i===ma&&Q?.id===t.id&&la===r&&o===z.url(`/api/catalogs`)&&(s.catalogsEntries.setAttribute(`aria-busy`,`false`),fa=l.total??0,da=e===0?l.entries??[]:[...da,...l.entries??[]],Oa())}function Oa(){let e=Q;if(!e)return;let t=da.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?ze(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`,()=>{ka(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,c(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`;Io(z.url(i),r,`✓`)}),n.append(r)}return qe()&&n.append(nt(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(da.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=ua?`Nothing called "${ua}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(da.length<fa){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,P(n,()=>`Show more (${da.length.toLocaleString(f.language)} of ${fa.toLocaleString(f.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),Ge(s.catalogsEntries,!1),n.disabled=!0,Da(da.length)}),e.append(n),t.push(e)}L(s.catalogsEntries,...t)}async function ka(e,t,r){r?.classList.add(`loading`),T=`Starting ${t.title}…`;let i={catalog:{id:e.id,name:e.name},entry:t};try{await k(async()=>{let r,a={};try{r=await n(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),a=await r.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!r.ok){T=a.error??`${t.title} would not play.`;return}let o=a.name||t.title;if(a.kind===`live`&&a.channel){await ko({id:a.channel,name:o,video:!0},!0,{kind:`channel`,...i});return}if(a.kind===`vod`&&a.url){O=null,E=-1,A={kind:`vod`,...i},Ae(o,`title`),await R.load({title:o,artist:``,album:``,duration:0,url:z.url(a.url),video:!0,objectUrl:!1},!0),qn(!0),T=`Playing ${o}.`;return}T=`${t.title} would not play.`})}finally{r?.classList.remove(`loading`),V()}}async function Aa(e){G(`Reading ${e.name} again…`);try{let t=await n(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),r=await t.json().catch(()=>({}));G(t.ok?`${r.catalog?.name??e.name}: ${(r.catalog?.entries??0).toLocaleString(f.language)} entries.`:r.error??`that did not work`)}catch{G(`could not reach the server`)}ba()}async function ja(e){try{let t=await n(z.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(G(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return G(`could not reach the server`),!1}return Q?.id===e.id&&(Q=null,la=null),!0}s.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=s.catalogSource.value.trim(),r=s.catalogName.value.trim();t&&(async()=>{G(`Reading ${r||t}…`);try{let e=await n(z.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:r})}),i=await e.json().catch(()=>({}));if(!e.ok){G(i.error??`that did not work`);return}G(`${i.catalog?.name??r??t}: ${(i.catalog?.entries??0).toLocaleString(f.language)} entries.`),s.catalogSource.value=``,s.catalogName.value=``}catch{G(`could not reach the server`)}ba()})()}),s.catalogsFilter.addEventListener(`input`,()=>{ma++,ha?.abort(),pa&&clearTimeout(pa),pa=setTimeout(()=>{pa=null,ua=s.catalogsFilter.value.trim(),Da(0)},250)});let Ma=async()=>{L(s.serversList);try{let e=await n(`/api/v1/servers`);if(!e.ok){s.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ne=new Map(t.map(e=>[K(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),s.serversPanel.hidden=!1,s.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`),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.url,r.append(i,a);let o=e.key?`${e.url}/admin/${e.key}`:e.url,[c,l]=ie({name:e.name,view:o,admin:o});Dt(e.url).then(n=>{if(n!==null){a.textContent=`${e.url} · ${n}`;return}a.textContent=`${e.url} · not answering`,t.classList.add(`offline`),c.disabled=!0,l.disabled=!0,c.title=l.title=`That machine is not answering. Start nixamp on it.`});let u=qa()===K(e.url),d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=u?`✓ Default`:`Make default`,d.title=u?`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`,d.addEventListener(`click`,()=>{Ja(u?``:K(e.url)),Ma()});let f=document.createElement(`button`);f.type=`button`,f.className=`ghost`,f.textContent=`Forget`,f.addEventListener(`click`,()=>{(async()=>{f.disabled=!0;try{await n(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await Ma()}catch{f.disabled=!1}})()}),t.append(r,c,l,d,f),s.serversList.append(t)}}catch{s.serversPanel.hidden=!0}},Na=async()=>{L(s.followingList);try{let e=await n(`/api/v1/follows`);if(!e.ok){s.followingNote.hidden=!0;return}let t=(await e.json()).following??[];s.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name||`a nixamp`;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.live?`live now`:`not streaming`,r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,P(o,()=>p(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await n(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),s.followingList.children.length===0&&(s.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(r,o),s.followingList.append(t)}}catch{s.followingNote.hidden=!0}},Pa=(e,t)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`ghost follow`,P(r,()=>p(`Follow`)),r.setAttribute(`aria-label`,`Follow ${t}`);let i=e=>{P(r,()=>e?`Following`:p(`Follow`)),r.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await n(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&i((await t.json()).following===!0)}catch{}})(),r.addEventListener(`click`,()=>{(async()=>{let t=r.dataset.following===`yes`;r.disabled=!0;try{(await n(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(i(!t),Na())}catch{}finally{r.disabled=!1}})()}),r},Fa=async()=>{let e=ye();if(!e.supported)return s.notifyNote.textContent=e.message,!1;try{return await Ee({vapidKeyUrl:`/api/v1/notify/key`,serviceWorkerUrl:`/sw.js`,saveUrl:`/api/v1/notify/subscribe`}),s.notifyNote.textContent=`This device will be told.`,!0}catch(e){return s.notifyNote.textContent=e instanceof xe&&e.reason!==`save-failed`?e.message:`Could not set this device up.`,!1}},Ia=async()=>{try{await Oe({removeUrl:`/api/v1/notify/subscribe`})}catch{}},La=async e=>{try{let t=await n(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),r=await t.json();s.notifyPhoneNote.textContent=t.ok?``:r.error??`that did not save`,t.ok&&typeof r.phone==`string`&&(s.notifyPhone.value=r.phone)}catch{s.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Ra=async()=>{try{let e=await n(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();s.notifyEmail.checked=t.wantsEmail!==!1,s.notifySms.checked=t.wantsSms===!0,s.notifyPhone.value=t.phone??``;let r=ye(),i=r.supported&&r.permission===`granted`?await De()!==null:!1;s.notifyWeb.checked=t.wantsWeb!==!1&&i,s.notifyNote.textContent=i?`Get told when someone you follow goes live.`:r.message??`Turn on “On this device” to be told here.`}catch{}};s.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(s.notifyWeb.checked){let e=await Fa();s.notifyWeb.checked=e,await La({wantsWeb:e});return}await Ia(),await La({wantsWeb:!1}),s.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),s.notifyEmail.addEventListener(`change`,()=>{La({wantsEmail:s.notifyEmail.checked})}),s.notifySms.addEventListener(`change`,()=>{(async()=>{if(s.notifySms.checked&&!s.notifyPhone.value.trim()){s.notifyPhoneNote.textContent=`Add a phone number first.`,s.notifySms.checked=!1;return}await La({wantsSms:s.notifySms.checked})})()}),s.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),La({phone:s.notifyPhone.value.trim()})});let za=!1,Ba=!1,Va=`nixamp.welcome`,Ha=()=>{let e=!1;try{e=localStorage.getItem(Va)===`hidden`}catch{}s.welcome.hidden=!Ba||Y!==``||e},Ua=t=>{document.dispatchEvent(new CustomEvent(`nixamp:account`,{detail:{email:t}}));let n=t!==null;Si.refresh(),li=``,fi=null,n||(X=!1,s.transcriptAudio.checked=!1,Z.disable(),Ei()),Xi(),s.notifyPanel.hidden=!n,n?(Ra(),Na(),Ma()):(s.serversPanel.hidden=!0,s.followingNote.hidden=!0,L(s.followingList),s.recentNote.hidden=!0,s.recentList.replaceChildren()),s.accountForm.hidden=n,s.accountProviders.hidden=n||s.accountProviders.childElementCount===0,s.accountSignOut.hidden=!n,s.personaForm.hidden=!n,s.personaNote.hidden=!n,n&&Ki(),s.accountNote.textContent=n?`Signed in as ${t}.`:za?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,P(s.accountSubmit,()=>p(za?`Create account`:`Sign in`)),P(s.accountToggle,()=>za?`I have one`:p(`Create one`)),s.accountPassword.autocomplete=za?`new-password`:`current-password`,s.accountForgot.hidden=za,e&&(s.accountForgot.target=`_blank`,s.accountForgot.rel=`noopener`),Ha()},Wa=async()=>{let e=[];Ba=!1;try{let t=await n(`/api/v1/auth/providers`);t.ok&&(Ba=!0,e=(await t.json()).providers??[])}catch{}s.accountProviders.replaceChildren(),s.accountProviders.hidden=e.length===0,s.accountPanel.hidden=!Ba,s.accountElsewhere.hidden=Ba,Ha();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}`,s.accountProviders.append(e)}},Ga=async()=>{try{let e=await n(`/api/v1/auth/me`),t=await e.json();Y=e.ok?t.account?.id??``:``,Ua(e.ok?t.account?.email??`you`:null)}catch{Y=``,Ua(null)}if(z.session=``,Y!==``){try{let e=await n(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));z.session=e.ok&&typeof t.token==`string`?t.token:``}catch{z.session=``}d===`remote`&&Er()}Gr(),Vr(),Hr(),Ya();let e=await Ka();if(Ie!==``){let t=Ie;Ie=``,e?x=`golive:${t}`:Yn(t)}};async function Ka(){if(Y===``||d===`remote`||Fe!==``)return!1;let e=[];try{let t=await n(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=qa(),r=[...e].sort((e,n)=>Number(K(n.url)===t)-Number(K(e.url)===t));for(let e of r)if(await Dt(e.url,void 0,e.key)!==null)return d!==`remote`&&(b=!1,x=``,s.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,T=`Connecting to ${e.name}, your server…`,V(),s.remoteForm.requestSubmit(),!0);return!1}function qa(){try{return localStorage.getItem(tr)??``}catch{return``}}function Ja(e){try{e===``?localStorage.removeItem(tr):localStorage.setItem(tr,e)}catch{}}function Ya(){if(Fe===``)return;let e=Fe;Fe=``,s.remoteUrl.value=e,s.remoteForm.requestSubmit()}s.accountToggle.addEventListener(`click`,()=>{za=!za,Ua(null)}),s.welcomeCreate.addEventListener(`click`,()=>{za=!0,Ua(null),s.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),s.accountEmail.focus({preventScroll:!0})}),s.welcomeBrowse.addEventListener(`click`,()=>{s.directory.hidden?s.browse.click():s.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),s.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Va,`hidden`)}catch{}s.welcome.hidden=!0}),s.accountForm.addEventListener(`submit`,r=>{r.preventDefault();let i=s.accountEmail.value.trim(),a=s.accountPassword.value;(async()=>{s.accountSubmit.disabled=!0;try{let r=await n(`/api/v1/auth/${za?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:i,password:a})}),o=await r.json();if(!r.ok){s.accountNote.textContent=o.error??`that did not work`;return}e&&(t=o.token??``),Y=o.account?.id??``,s.accountPassword.value=``,Ua(o.account?.email??i),Er(),Ya()}catch{s.accountNote.textContent=`could not reach nixamp.com`}finally{s.accountSubmit.disabled=!1}})()}),s.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await n(`/api/v1/auth/logout`,{method:`POST`})}catch{}t=``,Y=``,Ua(null),Vr(),z.close(),E=-1,d=`local`,se=`idle`,w=``,s.remoteUrl.value=``,s.sharePanel.hidden=!0,s.publishPanel.hidden=!0,s.adminPanel.hidden=!0,s.catalogsPanel.hidden=!0,s.listenOnly.hidden=!0,Co(!1);try{localStorage.removeItem(er)}catch{}T=`Signed out, and disconnected from the server.`,Er(),V()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Fe=t,x=e.get(`play`)??``,te=Math.max(0,Number(e.get(`t`)??`0`)||0),s.remoteUrl.value=t,T=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(s.linkUrl.value=n,t!==``&&x===``?x=`link:${n}`:t===``&&(Ie=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=ht(r);t?(Fe=t.view,x=t.what,te=Math.max(0,Number(e.get(`t`)??`0`)||0),s.remoteUrl.value=t.view,T=`Opening the stream you were sent…`):(s.linkUrl.value=r,Ie=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Xa=[`zone-top`,`zone-main`],Za=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Qa=e=>e.parentElement&&Xa.includes(e.parentElement.id)?e.parentElement:null,$a=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,eo=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Za(e)&&Qa(e)!==null),to=e=>e.dataset.title??e.id,no=new Map,ro=eo().map((e,t)=>(no.set(e.id,{zone:Qa(e)?.id??``,col:$a(e),index:t}),e.id)),$=nn();try{$=an(localStorage.getItem(tn))}catch{}let io=()=>$.order.length>0||Object.keys($.placement).length>0;function ao(){$.order=eo().map(e=>e.id);try{localStorage.setItem(tn,on($))}catch{}}function oo(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 so(){if(e)return;for(let e of eo()){let t=$.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Xa.includes(i.id)&&oo(e,i,r===`a`||r===`b`?r:``)}let t=sn(eo().map(e=>e.id),$.order);for(let e of Xa){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(Za),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 eo())e.toggleAttribute(`data-collapsed`,$.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,$.closed.includes(e.id))}function co(e,t){e.toggleAttribute(`data-collapsed`,t),e===s.panelsPanel&&s.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),$.collapsed=cn($.collapsed,e.id,t),ao(),go()}function lo(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===s.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===s.panelsPanel&&s.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===s.partiesPanel&&!t&&Vr(),t&&n&&s.panelsToggle.focus({preventScroll:!0}),$.closed=cn($.closed,e.id,t),ao(),go()}function uo(e,t,n){let r=Qa(t);r&&e!==t&&(oo(e,r,$a(t)),n?t.after(e):t.before(e),$.placement[e.id]=`${r.id}:${$a(t)}`,ao(),go())}let fo=null,po=()=>{for(let e of eo())e.classList.remove(`drop-before`,`drop-after`)},mo=(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 ho(){for(let e of eo()){let t=to(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n));let r=n.querySelector(`.panel-heading-text`);if(!r){r=document.createElement(`span`),r.className=`panel-heading-text`;let e=document.createElement(`span`);e.className=`panel-loading-spinner`,e.setAttribute(`aria-hidden`,`true`),n.replaceChildren(r,e)}if(r.textContent!==t&&(r.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let i=document.createElement(`span`);i.className=`panel-tools`;let a=mo(`≡`,`Move ${to(e)}: Alt plus Up or Down, or drag`,()=>void 0);a.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=eo().filter(t=>Qa(t)===Qa(e)&&$a(t)===$a(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(uo(e,r,t.key===`ArrowDown`),a.focus({preventScroll:!0}))}),a.classList.add(`grip`),a.draggable=!0,a.addEventListener(`dragstart`,t=>{fo=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),a.addEventListener(`dragend`,()=>{fo=null,e.classList.remove(`dragging`),po()});let o=mo(`▁`,`Shade ${to(e)} to its title`,()=>co(e,!e.hasAttribute(`data-collapsed`)));o.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let s=mo(`✕`,`Hide ${to(e)}; the Panels list turns it back on`,()=>lo(e,!0));e.id===`transcript-panel`&&i.append(Si.button()),i.append(a,o,s),e.prepend(i),e.addEventListener(`dragover`,t=>{if(!fo||fo===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;po(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!fo||fo===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);po(),uo(fo,e,n)})}}function go(){if(s.panelsPanel.hidden||s.panelsList.contains(document.activeElement))return;let e=eo().filter(e=>e!==s.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,F(i,`aria-label`,()=>`${to(e)} on`),i.addEventListener(`change`,()=>lo(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,P(a,()=>to(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});s.panelsList.replaceChildren(...e)}function _o(){$=nn();for(let e of ro){let t=document.getElementById(e),n=no.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(oo(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}$.order=[...ro],so(),$=nn();try{localStorage.removeItem(tn)}catch{}go()}function vo(e){if(!e||io())return;let t=Qa(s.adminPanel);if(!t)return;let n=[...t.children].filter(Za).find(e=>$a(e)===$a(s.adminPanel));n&&n!==s.adminPanel&&n.before(s.adminPanel),s.adminPanel.removeAttribute(`data-collapsed`),s.adminPanel.removeAttribute(`data-closed`)}s.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=s.panelsPanel.hidden||s.panelsPanel.hasAttribute(`data-closed`)||s.panelsPanel.hasAttribute(`data-collapsed`);s.panelsPanel.hidden=!t,s.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(s.panelsPanel.hasAttribute(`data-closed`)&&lo(s.panelsPanel,!1),s.panelsPanel.hasAttribute(`data-collapsed`)&&co(s.panelsPanel,!1),go(),s.panelsPanel.showPopover?.(),s.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):s.panelsPanel.hidePopover?.()}),s.panelsPanel.addEventListener(`toggle`,()=>{let e=s.panelsPanel.matches(`:popover-open`);s.panelsToggle.setAttribute(`aria-expanded`,String(e&&!s.panelsPanel.hasAttribute(`data-collapsed`))),e||(s.panelsPanel.hidden=!0)}),s.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof s.panelsPanel.hidePopover!=`function`&&(s.panelsPanel.hidden=!0,s.panelsToggle.setAttribute(`aria-expanded`,`false`),s.panelsToggle.focus({preventScroll:!0}))}),s.panelsReset.addEventListener(`click`,_o),s.panelsSave.addEventListener(`click`,()=>{ao();let e=s.panelsSave.textContent??`Save setup`;s.panelsSave.textContent=`Saved`,window.setTimeout(()=>{s.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{ho(),go()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),ho(),so(),Wa(),Ga(),Er(),ur(),s.browse.addEventListener(`click`,()=>{if(!s.directory.hidden){s.directory.hidden=!0;return}gr(),s.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),s.disconnect.addEventListener(`click`,()=>{z.close(),s.listenOnly.hidden=!0,E=-1,s.sharePanel.hidden=!0,s.publishPanel.hidden=!0,s.adminPanel.hidden=!0,s.catalogsPanel.hidden=!0,F(s.catalogsPanel,`data-title`,()=>p(`Catalogs on this server`)),m=``,ae=``,Jr(),Co(!1),d=`local`,se=`idle`,w=``,V()});async function yo(){if(d!==`remote`||z.shareLink===``){s.sharePanel.hidden=!0;return}s.sharePanel.hidden=!1;let e=Ro(),t=globalThis.location.origin;s.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,s.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,s.sharePhone.hidden=!0,s.shareSend.hidden=!0,s.liveControls.hidden=!0;let r=``;try{let e=await n(`/api/directory`);e.ok&&(r=(await e.json()).callIn??``)}catch{}Ne=r,bt();let i=null;try{let r=await n(z.url(`/api/live/state`));r.ok&&(i=await r.json()),i?.url&&(e=i.url,ae=i.url,s.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(i){if(je=i.live,Me=i.live?i.code:``,Ne=r,s.liveControls.hidden=s.adminPanel.hidden||!i.possible,s.goLive.hidden=i.live,s.stopLive.hidden=!i.live,s.sharePhone.hidden=!1,!i.live){s.sharePhone.textContent=i.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(!r){s.sharePhone.textContent=`Listed. The code for the phone line is ${i.code}.`,s.shareSend.hidden=!1;return}s.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),Wo(r),document.createTextNode(` and key `),Wo(i.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),s.shareSend.hidden=!1}}let bo=null,xo=null,So=0,Co=e=>{bo&&clearInterval(bo),bo=null,So+=1,xo?.abort(),xo=null,j=null,Lr(),e&&(wo(),bo=setInterval(()=>{document.visibilityState===`visible`&&wo()},Rr))};async function wo(){if(d!==`remote`||xo)return;let e=new AbortController;xo=e;let t=j===null;t&&Br(e,!0);let r=So,i=z.url(`/api/streams`),a=setTimeout(()=>e.abort(),8e3);try{let t=await n(i,{signal:e.signal,cache:`no-store`});if(!t.ok)return;let a=await t.json();if(e.signal.aborted||r!==So||d!==`remote`||i!==z.url(`/api/streams`))return;_=a.server.carries!==!1,a.server.name&&a.server.name!==m&&(m=a.server.name,s.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${m}`),Jr()),j=a,zo(a),V(),To(a)}catch{}finally{clearTimeout(a),t&&Br(e,!1),xo===e&&(xo=null)}}function To(e){Lr(),O&&In()}function Eo(e){let t=ct(),n=e.restreams??[],r=[],i=e.server.playing,a=!s.adminPanel.hidden;i&&r.push(Bo({key:`live`,title:Ye(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${Ye(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&&Oo(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:Lo(`live`)}:{},direct:i?z.url(`/api/live`):``}));for(let e of n)r.push(Bo({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:()=>{At(e.at)},link:``,direct:z.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=z.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}×`),a&&t.error&&i.push(t.error),r.push(Bo({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{ko({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:Lo(`channel:${t.id}`),direct:n,onRestart:(a||Ke&&Y!==``&&t.startedBy===Y)&&t.via===`pull`?()=>{Mo(t.id,t.name)}:void 0,onStop:a||Ke&&Y!==``&&t.startedBy===Y?()=>Po(t.id,t.name):void 0,onRename:a||Ke&&Y!==``&&t.startedBy===Y?()=>{No(t.id,t.name)}:void 0}))}return r}async function Do(){if(d===`remote`)try{if((await n(z.media(B(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;T=Y===``?`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.`,Y===``&&s.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),V()}catch{}}async function Oo(e){E=-1,O=null,A={kind:`live`},Ae(e,`auto`),await k(()=>R.load({title:e||`Live`,artist:``,album:``,duration:0,url:z.url(`/api/live`),video:!0,objectUrl:!1},!0)),qn(!0),T=`Watching what this server is playing. Everyone here sees the same thing.`,V()}async function ko(e,t=!0,n){let r=j?.channels.find(t=>t.id===e.id);!e.playlist&&r?.playlist&&(e={...e,playlist:r.playlist}),E=-1,O=e,t&&(de=0),t&&(A=n??{kind:`channel`}),t&&Ae(e.name,A?.link||Qn(e.name)?`auto`:`channel`);let i=e.video&&Xe(),a=e.video&&((e.playlist?.length??0)>1||e.id.startsWith(`folder-`));await k(()=>R.load({title:e.name,artist:``,album:``,duration:0,url:z.url(i||a?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),qn(e.video),O===e&&(T=`Watching ${e.name}, live on this server.`),V()}function Ao(){let e=O;return e?Pe?!0:de>=5?(T=`${e.name} stopped, and did not come back.`,O=null,A=null,V(),!0):(de+=1,T=`${e.name} started over; rejoining…`,V(),Pe=setTimeout(()=>{Pe=null,O===e&&ko(e,!1)},2e3),!0):!1}function jo(e){s.partiesNote.hidden=!1,s.partiesNote.textContent=e,G(e)}async function Mo(e,t){jo(`Restarting ${t}…`);try{let r=await n(z.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),i=await r.json().catch(()=>({}));jo(r.ok?`${t} is dialling its source again.`:i.error??`that did not work`)}catch{jo(`could not reach the server`)}wo()}async function No(e,t){let r=globalThis.prompt(`Call ${t}…`,t);if(r===null)return;let i=r.trim();if(i!==``&&i!==t){jo(`Renaming ${t}…`);try{let r=await n(z.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:i})}),a=await r.json().catch(()=>({}));jo(r.ok?`${t} is now ${i}.`:a.error??`that did not work`)}catch{jo(`could not reach the server`)}O?.id===e&&(O={...O,name:i}),wo(),V()}}async function Po(e,t){jo(`Taking ${t} off the air…`);try{let r=await n(z.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),i=await r.json().catch(()=>({}));if(jo(r.ok?`${t} is off the air.`:i.error??`that did not work`),!r.ok)return!1}catch{return jo(`could not reach the server`),!1}return O?.id===e&&(O=null,R.stop()),!0}function Fo(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 Io(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{T=e,V();return}n===`✓`||n===`✓`?c(t,`check`):P(t,()=>p(n)),setTimeout(()=>{t.innerHTML=r},1200)}function Lo(e,t=0){let n=Ro();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 Ro(){if(ae!==``)return ae;let e=d===`remote`?z.shareLink:``;return/\/admin\//.test(e)?``:e}function zo(e){if(x===``)return;let t=x;if(t===`live`){x=``,e.server.playing?Oo(e.server.nowPlaying):(T=`Nothing is playing on this server right now.`,V());return}if(t.startsWith(`link:`)){x=``,Yn(t.slice(5));return}if(t.startsWith(`golive:`)){x=``,s.linkUrl.value=t.slice(7),Er().then(()=>dr());return}if(t.startsWith(`track:`)){x=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&At(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&&(x=``,ko({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Bo(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${y(z.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 o=document.createElement(`button`);o.type=`button`,o.className=`button`,tt(o,e.playLabel??`Join party`),o.hidden=e.key.startsWith(`channel:`)&&O?.id===e.key.slice(8),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,c(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Io(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Io(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,n=>{Fo(t,n,e.onStop,()=>void wo())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,F(o,`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=`⋯`,F(u,`aria-label`,()=>`${p(`Show more`)}: ${e.title}`),a.removeChild(o),l.append(u,a),t.append(n,o),a.childElementCount&&t.append(l),t}let Vo=``;function Ho(e,t){Vo=e;let n=e!==``&&t===e;s.loadHome.hidden=e===``,s.homeNote.hidden=e===``,e!==``&&(s.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,s.loadHome.disabled=!1)}s.loadHome.addEventListener(`click`,()=>{Vo!==``&&(s.loadHome.disabled=!0,G(`Reading this server's files…`),(async()=>{try{let e=await n(z.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Vo})}),t=await e.json();G(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{G(`could not reach the server`)}finally{s.loadHome.disabled=!1}})())});let Uo=async e=>{s.goLive.disabled=!0,s.stopLive.disabled=!0,s.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await n(z.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),r=await t.json();s.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${r.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:r.error??`that did not work`}catch{s.shareNote.textContent=`could not reach the server`}finally{s.goLive.disabled=!1,s.stopLive.disabled=!1,await yo()}};s.goLive.addEventListener(`click`,()=>void Uo(!0)),s.stopLive.addEventListener(`click`,()=>void Uo(!1));function Wo(e){let t=document.createElement(`b`);return t.textContent=e,t}s.shareCopy.addEventListener(`click`,()=>{s.shareLink.select(),navigator.clipboard?.writeText(s.shareLink.value).then(()=>{s.shareNote.textContent=`Copied. Send it to anybody.`},()=>{s.shareNote.textContent=`Copy it from the box above.`})}),s.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=s.shareTo.value.trim();t!==``&&(async()=>{s.shareNote.textContent=`Sending…`;try{let e=await n(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:Ro()})}),r=await e.json();s.shareNote.textContent=e.ok?`Sent to ${r.sent??t}.`:r.error??`that did not send`,e.ok&&(s.shareTo.value=``)}catch{s.shareNote.textContent=`could not send that`}})()}),s.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(rr,s.listenHere.checked?`1`:`0`)}catch{}d===`remote`&&(async()=>{s.listenHere.checked?(await z.send({type:`stop`}),await Vt(C.index)):(R.stop(),E=-1),V()})()}),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===s.transport)switch(e.key){case` `:e.preventDefault(),Ut();return;case`s`:qt();return;case`n`:case`ArrowRight`:Kt(1);return;case`p`:case`ArrowLeft`:Kt(-1);return;case`ArrowDown`:e.preventDefault(),At(Math.min(st()-1,B()+1));return;case`ArrowUp`:e.preventDefault(),At(Math.max(0,B()-1));return}});let Go=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Go=e,s.install.hidden=!1}),s.install.addEventListener(`click`,()=>{Go?.prompt(),Go=null,s.install.hidden=!0});try{let e=localStorage.getItem(nr);e!==null&&(s.volume.value=String(Math.round(Number(e)*100)),R.volume=Number(e));let t=localStorage.getItem(er);t&&(s.remoteUrl.value=t),localStorage.getItem(rr)===`0`&&(s.listenHere.checked=!1)}catch{}(async()=>{if(s.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await Dt(e)===null)return;let t=await wt(e);t&&t.trackCount!==0&&(s.remoteUrl.value=e,d=`remote`,T=``,z.connect(e),Co(!0),ba(),V())})(),Vr();let Ko=()=>{document.visibilityState===`visible`&&!s.partiesPanel.hasAttribute(`data-closed`)&&Vr()},qo=setInterval(Ko,Rr);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(Vr(),wo())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(qo),bo&&clearInterval(bo),Fr?.abort(),xo?.abort(),Fr=null,xo=null,So+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(qo),qo=setInterval(Ko,Rr),Ko(),d===`remote`&&Co(!0))}),(()=>{if(ar||Fe!==``)return;let e=()=>R.source!==``||R.playing||he()||O!==null,t=async()=>{try{let e=await(await n(`/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``},r=new Audio;r.volume=.7;let i=()=>{ar=!0},a=()=>{document.removeEventListener(`pointerdown`,a),document.removeEventListener(`keydown`,a),i(),setTimeout(()=>{e()||R.playJingle(r).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return r.src=t,R.playJingle(r).then(i,()=>{document.addEventListener(`pointerdown`,a,{once:!0}),document.addEventListener(`keydown`,a,{once:!0})})})})(),V(),requestAnimationFrame(Hn)}or(),Ie(),I(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{e as n,u as t};