Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrcsite.js

1.4.2Released Nov 21, 2026

site.js

990 lines41.2 KBJavaScript
// Runs in the site's webview before juicewrld.io's own scripts, on every page load. Five parts, each on its own://// 1. What's playing, for the Discord status. It reads it the way the system's media controls do://    navigator.mediaSession (the player sets its metadata and playbackState, src/components/player/store.ts) plus the//    playing <audio> element's clock, and reports changes to the app's `presence` command (capabilities/site.json).//    While this page plays nothing, what the member's other browsers play (GET /api/me/now-playing), for the same.// 2. window.juicewrldDesktop.plugins: the user's own plugins for the studio, when this copy of the app can run them//    (desktop/README.md, "Plugins in the studio", has the API).// 3. window.juicewrldLikeShortcut: the keyboard shortcut that likes what's playing.// 4. window.juicewrldNotifications: Windows notifications for the site's messages, notes and alerts.// 5. The title bar's room: whether this page lies under the see-through bar, and the room it leaves it.// Nothing else is exposed.(() => {  "use strict";  if (location.origin !== "https://juicewrld.io" || window.top !== window) return;  // The player's audio elements are never attached to the page (new Audio()), so they're found as they  // start: play() is wrapped, unchanged otherwise. Each is held weakly, newest play last.  const decks = [];  const heard = new WeakSet();  const play = HTMLMediaElement.prototype.play;  HTMLMediaElement.prototype.play = function (...args) {    // Audio only: a snippet's <video> playing on a page isn't the song (its clock comes from the player's    // position reports below if the player ever plays through a video).    try {      if (this instanceof HTMLAudioElement) watch(this);    } catch {}    return play.apply(this, args);  };  function watch(el) {    for (let i = decks.length - 1; i >= 0; i--) {      const d = decks[i].el.deref();      if (!d || d === el) decks.splice(i, 1);    }    decks.push({ el: new WeakRef(el), at: performance.now() });    if (decks.length > 8) decks.shift();    if (!heard.has(el)) {      heard.add(el);      for (const type of ["play", "pause", "ended", "seeked", "durationchange", "emptied", "ratechange"]) {        el.addEventListener(type, soon);      }    }    soon();  }  /** The element that is playing (the newest one, if two overlap in a crossfade), else the newest at all. */  function current() {    let fallback = null;    for (let i = decks.length - 1; i >= 0; i--) {      const el = decks[i].el.deref();      if (!el) continue;      if (!el.paused && !el.ended) return el;      fallback = fallback || el;    }    return fallback;  }  // The player's own position reports, for when no element can be read.  let position = null;  const ms = navigator.mediaSession;  if (ms && MediaSession.prototype.setPositionState) {    const setPositionState = MediaSession.prototype.setPositionState;    MediaSession.prototype.setPositionState = function (state) {      position = state && Number.isFinite(state.duration) ? { ...state, at: performance.now() } : null;      soon();      return setPositionState.call(this, state);    };  }  // The player flips playbackState and swaps metadata on every change: check right away instead of  // waiting for the poll (which a hidden, paused window runs only now and then).  for (const key of ["playbackState", "metadata"]) {    const d = ms && Object.getOwnPropertyDescriptor(MediaSession.prototype, key);    if (!d || !d.set) continue;    Object.defineProperty(MediaSession.prototype, key, {      ...d,      set(v) {        d.set.call(this, v);        soon();      },    });  }  function absolute(src) {    try {      return new URL(src, location.href).href;    } catch {      return "";    }  }  /** The biggest artwork the player offered. */  function artwork(list) {    let best = "";    let size = -1;    for (const a of list || []) {      const s = Math.max(0, ...String(a.sizes || "").split(/\s+/).map((x) => parseInt(x, 10) || 0));      if (s > size) {        size = s;        best = a.src;      }    }    return best ? absolute(best) : "";  }  // The member's own picture as a song's cover (components/covers/picks.ts) is private to them, at an address only their  // session opens, which Discord can't fetch. For the status it goes as a link of the site's that Discord can  // (GET /api/desktop/cover?upload=<id>, good for a day: src/app/api/desktop/cover), asked for once per picture and used  // until an hour before it lapses. Until the link is here the status goes without the picture (the 999 icon); a  // picture the site won't link (not theirs, gone) stays that way, asked about again in ten minutes.  const UPLOAD = /^https:\/\/juicewrld\.io\/api\/me\/covers\/uploads\/([a-f0-9]{24})$/;  const links = new Map(); // upload id -> { url, until } (url "" while it's asked for, or when there's none)  function discordArt(src) {    const m = UPLOAD.exec(src);    if (!m) return src;    const id = m[1];    const held = links.get(id);    if (held && held.until > Date.now()) return held.url;    links.set(id, { url: "", until: Date.now() + 60000 });    fetch(`/api/desktop/cover?upload=${id}`, { credentials: "same-origin", cache: "no-store", headers: { accept: "application/json" } })      .then((r) => (r.ok ? r.json() : null))      .then((j) => {        const ok = j && typeof j.url === "string" && j.url.startsWith("https://juicewrld.io/") && Number.isFinite(j.expires);        links.set(id, ok ? { url: j.url, until: j.expires - 3600000 } : { url: "", until: Date.now() + 600000 });        soon();      })      .catch(() => {});    return "";  }  /** The song's page: the player bar's title links there. */  function songUrl() {    const a = document.querySelector("a.pl-bar__title[href]");    return a ? a.href : `${location.origin}/`;  }  function snapshot() {    const md = ms && ms.metadata;    const ps = ms ? ms.playbackState : "none";    if (!md || !md.title || ps === "none") return { state: "none" };    const s = {      state: ps === "playing" ? "playing" : "paused",      title: md.title,      artist: md.artist || "",      album: md.album || "",      artwork: discordArt(artwork(md.artwork)),      position: 0,      duration: 0,      url: songUrl(),    };    const el = current();    if (el && Number.isFinite(el.duration) && el.duration > 0) {      s.position = el.currentTime;      s.duration = el.duration;    } else if (position) {      const rate = s.state === "playing" ? position.playbackRate || 1 : 0;      s.duration = position.duration;      s.position = Math.min(position.duration, (position.position || 0) + ((performance.now() - position.at) / 1000) * rate);    }    return s;  }  // Sent only when something Discord shows changes: the song, play or pause, the length becoming known,  // or the clock jumping (a seek) by more than two seconds against where it should be. Until the length  // is known the clock isn't either, so it can't jump.  let sentKey = "";  let sentStart = 0;  function tell(s) {    const known = s.duration > 0;    const key = [s.state, s.title, s.artist, s.album, s.artwork, s.url, known ? Math.round(s.duration) : 0].join("\n");    const start = Date.now() - (s.position || 0) * 1000;    const el = current();    const scanning = el && el.playbackRate > 2;    if (key === sentKey && (s.state !== "playing" || !known || scanning || Math.abs(start - sentStart) < 2000)) return;    sentKey = key;    sentStart = start;    try {      window.__TAURI_INTERNALS__.invoke("presence", { update: s }).catch(() => {});    } catch {}  }  // ---- what the member's other browsers play ----  // While this page plays nothing, the member may be playing elsewhere (a tab in another browser, their phone): the site  // keeps what each of the account's browsers plays (src/app/api/me/now-playing) and the app shows it on Discord while  // this page is quiet; this page's own playback always wins (presence.rs). Asked every WEB_EVERY while this page plays  // nothing and never while it plays; a page that isn't signed in hears 401 and asks every WEB_SIGNED_OUT.  const WEB_EVERY = 15000;  const WEB_SIGNED_OUT = 300000;  /** The other browser's song as last heard: its clock as of `at` (performance.now()), good until `until`. */  let web = null;  let webTimer = 0;  let webAsking = false;  let webSentKey = "";  let webSentStart = 0;  function webFrom(n) {    if (!n || n.state !== "playing" || typeof n.title !== "string" || !n.title) return null;    const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);    const at = performance.now();    return {      title: n.title,      artist: typeof n.artist === "string" ? n.artist : "",      album: typeof n.album === "string" ? n.album : "",      artwork: typeof n.cover === "string" ? n.cover : "",      url: typeof n.url === "string" ? n.url : "",      duration: num(n.duration),      position: num(n.position),      rate: num(n.rate) || 1,      at,      until: at + Math.min(Math.max(num(n.freshFor), 0), 600000),    };  }  function webSnapshot() {    const t = performance.now();    const position = web ? web.position + ((t - web.at) / 1000) * web.rate : 0;    // Not said again in time, or its song long over (that browser moved on and the word hasn't reached the site).    if (web && (t > web.until || (web.duration > 0 && position > web.duration + 15))) web = null;    if (!web) return { state: "none" };    return { state: "playing", title: web.title, artist: web.artist, album: web.album, artwork: web.artwork, position, duration: web.duration, url: web.url };  }  /** Tells the app what the other browser plays: when it changes, and after every answer (`fresh`) so it stays fresh. */  function tellWeb(fresh) {    const s = webSnapshot();    const key = [s.state, s.title, s.artist, s.album, s.artwork, s.url, Math.round(s.duration || 0)].join("\n");    const start = Date.now() - (s.position || 0) * 1000;    const same = key === webSentKey && (s.state !== "playing" || Math.abs(start - webSentStart) < 2000);    if (same && !(fresh && s.state === "playing")) return;    webSentKey = key;    webSentStart = start;    try {      window.__TAURI_INTERNALS__.invoke("presence", { update: s, source: "web" }).catch(() => {});    } catch {}  }  function askWeb() {    webTimer = 0;    if (webAsking) return;    webAsking = true;    fetch("/api/me/now-playing", { credentials: "same-origin", cache: "no-store", headers: { accept: "application/json" } })      .then((r) => (r.status === 401 ? { signedOut: true } : r.ok ? r.json() : null))      .then(        (j) => {          if (j && !j.signedOut) web = webFrom(j.now);          else if (j) web = null;          return j && j.signedOut ? WEB_SIGNED_OUT : WEB_EVERY;        },        () => WEB_EVERY,      )      .then((next) => {        webAsking = false;        // This page started playing meanwhile: its own song is the one, and nothing more is asked.        if (snapshot().state === "playing") return;        tellWeb(true);        if (!webTimer) webTimer = setTimeout(askWeb, next);      })      .catch(() => {        webAsking = false;      });  }  /** While this page plays, the other browsers' song stands down and isn't asked for; once it doesn't, it's asked. */  function others(s) {    if (s.state === "playing") {      clearTimeout(webTimer);      webTimer = 0;      if (web) {        web = null;        tellWeb(false);      }      return;    }    if (!webTimer && !webAsking) webTimer = setTimeout(askWeb, 500);    // The song running out of freshness, or its clock: the 2-second rule as for this page's own.    tellWeb(false);  }  function check() {    const s = snapshot();    tell(s);    others(s);  }  let timer = 0;  function soon() {    if (!timer) timer = setTimeout(() => ((timer = 0), check()), 150);  }  setInterval(check, 1000);})();// window.juicewrldDesktop.plugins, version 1: the VST3 plugins installed on this PC, for the studio's mixer slots. The// app runs them in a process of its own; this wraps its commands (plugins_*, src-tauri/src/plugins/mod.rs) and the// audio path: an AudioWorklet (plugins/worklet.js) that trades blocks with the plugin through a ring in a WebView2// shared buffer, so the page's main thread never carries audio. Only on https://juicewrld.io (and the debug build's// test page), and only when this copy of the app can run plugins: the app writes those two facts in below. status().api// says which calls an app has: 2 adds manage() (the app's plugin manager) and the `favourite` mark in list().(() => {  "use strict";  const SUPPORTED = /*JW_PLUGINS*/ false;  const TEST_ORIGIN = /*JW_TEST_ORIGIN*/ "";  if (!SUPPORTED || window.top !== window || !window.chrome || !window.chrome.webview) return;  if (location.origin !== "https://juicewrld.io" && !(TEST_ORIGIN && location.origin === TEST_ORIGIN)) return;  const VERSION = 1;  const WORKLET = "/__juicewrld-desktop/plugins-worklet-1.js";  const AT = { IN_WRITE: 16, OUT_READ: 17, CAPACITY: 3, LATENCY: 4, STATE: 35, OUT_WRITE: 33, PLUGIN_LATENCY: 38 };  const STATE_LOST = 3;  const call = (cmd, args, options) =>    window.__TAURI_INTERNALS__.invoke(cmd, args, options).catch((e) => {      throw new Error(typeof e === "string" ? e : (e && e.message) || "the app refused");    });  /** Bytes from a raw answer: an ArrayBuffer, or numbers where the page's CSP sends IPC through postMessage. */  const bytes = (x) =>    x instanceof ArrayBuffer ? new Uint8Array(x) : ArrayBuffer.isView(x) ? new Uint8Array(x.buffer, x.byteOffset, x.byteLength) : Uint8Array.from(x || []);  // ---- events ----  const handlers = new Map();  function on(map, type, fn) {    if (typeof fn !== "function") throw new TypeError("not a function");    if (!map.has(type)) map.set(type, new Set());    map.get(type).add(fn);    return () => map.get(type)?.delete(fn);  }  function emit(map, type, detail) {    for (const fn of map.get(type) || []) {      try {        fn(detail);      } catch (err) {        setTimeout(() => {          throw err;        });      }    }  }  const live = new Map(); // instance id -> Instance  let listening = null;  /** The app's events for this page, through a Tauri channel (in order: they carry an index). */  function listen() {    if (listening) return listening;    let next = 0;    const early = new Map();    const id = window.__TAURI_INTERNALS__.transformCallback((m) => {      if (!m || typeof m.index !== "number") return;      early.set(m.index, m);      while (early.has(next)) {        const msg = early.get(next).message;        early.delete(next);        next++;        if (msg) dispatch(msg);      }    });    listening = call("plugins_subscribe", { events: `__CHANNEL__:${id}` }).catch((err) => {      listening = null;      throw err;    });    return listening;  }  function dispatch(ev) {    if (ev.type === "status") return emit(handlers, "status", ev.status);    if (ev.type === "lost") {      for (const l of ev.instances || []) {        const inst = live.get(l.instance);        if (!inst) continue;        inst._lose({ reason: ev.reason, code: ev.code || null, culprit: !!l.culprit });      }      return emit(handlers, "lost", { reason: ev.reason, code: ev.code || null, instances: (ev.instances || []).map((l) => ({ ...l })) });    }    const inst = live.get(ev.instance);    if (!inst) return;    if (ev.type === "latency") inst._latency(ev.latency);    else if (ev.type === "param") emit(inst._handlers, "param", { id: ev.id, value: ev.value, phase: ["begin", "change", "end"][ev.phase] || "change" });    else if (ev.type === "editor") {      inst._editor = false;      emit(inst._handlers, "editor", { open: false });    } else if (ev.type === "changed") emit(inst._handlers, "changed", { flags: ev.flags });    else if (ev.type === "editor-requested") emit(inst._handlers, "editor-requested", {});  }  // ---- shared buffers: the rings, as the app posts them ----  const rings = new Map(); // stream id -> ArrayBuffer, or a resolver waiting for it  window.chrome.webview.addEventListener("sharedbufferreceived", (e) => {    const data = e.additionalData || {};    if (data.kind !== "juicewrld-plugins-ring") return;    const buffer = e.getBuffer();    const waiting = rings.get(data.stream);    if (typeof waiting === "function") waiting(buffer);    else rings.set(data.stream, buffer);  });  function ringFor(stream) {    const have = rings.get(stream);    if (have instanceof ArrayBuffer) {      rings.delete(stream);      return Promise.resolve(have);    }    return new Promise((resolve, reject) => {      const t = setTimeout(() => {        rings.delete(stream);        reject(new Error("the audio stream didn't arrive"));      }, 10000);      rings.set(stream, (b) => {        clearTimeout(t);        rings.delete(stream);        resolve(b);      });    });  }  /** A ring kept on the main thread, for render(). */  function view(buffer) {    const h = new Int32Array(buffer, 0, 64);    const cap = h[AT.CAPACITY];    const d = new Float32Array(buffer, 256, cap * 4);    return { buffer, h, cap, mask: cap - 1, planes: [0, 1, 2, 3].map((i) => d.subarray(i * cap, (i + 1) * cap)) };  }  function put(r, plane, pos, src) {    const at = pos & r.mask;    const first = Math.min(src.length, r.cap - at);    plane.set(src.subarray(0, first), at);    if (first < src.length) plane.set(src.subarray(first), 0);  }  function take(r, plane, pos, dst) {    const at = pos & r.mask;    const first = Math.min(dst.length, r.cap - at);    dst.set(plane.subarray(at, at + first), 0);    if (first < dst.length) dst.set(plane.subarray(0, dst.length - first), first);  }  /** Yields to the event loop for a moment (a message, not a 4 ms timer). */  const tick = () =>    new Promise((resolve) => {      const c = new MessageChannel();      c.port1.onmessage = () => resolve();      c.port2.postMessage(0);    });  const worklets = new WeakMap(); // context -> Promise  function loadWorklet(context) {    let p = worklets.get(context);    if (!p) {      p = context.audioWorklet.addModule(new URL(WORKLET, location.origin).href);      worklets.set(context, p);      p.catch(() => worklets.delete(context));    }    return p;  }  /**   * The real-time ring's latency for a context: one render burst and 6 ms to spare, in whole quanta. Chromium renders   * an AudioContext in bursts of quanta back to back (4 quanta, 512 frames, every 10.7 ms at 48 kHz for "interactive";   * 8 for "playback"), so the output due in a burst has to come from input written in an earlier one: a ring shorter   * than a burst underruns all the time (384 frames: about 74 underruns a second, measured), one burst exactly never   * did in 20 s with the main thread busy, and the 6 ms margin covers a slow plugin block or a late host thread. At   * "interactive" that's 896 frames, 18.7 ms, plus the plugin's own latency.   */  function ringLatency(context) {    const rate = context.sampleRate;    const burst = Math.max(128, Math.ceil(((context.baseLatency || 0.01) * rate) / 128) * 128);    return Math.ceil((burst + 0.006 * rate) / 128) * 128;  }  // ---- instances ----  class PluginNode {    constructor(instance, context, node, info) {      this.instance = instance;      this.context = context;      this.node = node;      this.mode = info.mode;      this.ringLatency = info.latency;      this.stream = info.stream;      this.closed = false;      this._stats = null;      this._handlers = new Map();      node.port.onmessage = (e) => {        const m = e.data || {};        if (m.type === "stats") {          const before = this._stats ? this._stats.underruns : 0;          this._stats = m;          emit(this._handlers, "stats", m);          if (m.underruns > before) emit(this._handlers, "underrun", { underruns: m.underruns });        } else if (m.type === "lost") emit(this._handlers, "lost", {});        else if (m.type === "error") emit(this._handlers, "error", { message: m.message });      };    }    /** Frames from a sample going in to it coming out: the ring's share and the plugin's own. */    get latency() {      return this.ringLatency + this.instance.latency;    }    get latencySeconds() {      return this.latency / this.context.sampleRate;    }    stats() {      return this._stats ? { ...this._stats } : null;    }    /** The studio's transport, for plugins that follow tempo: tempo in BPM, playing, position in samples. */    setTransport(t) {      this.node.port.postMessage({ type: "transport", tempo: t.tempo, playing: t.playing, position: t.position });    }    on(type, fn) {      return on(this._handlers, type, fn);    }    async close() {      if (this.closed) return;      this.closed = true;      this.node.port.postMessage({ type: "close" });      try {        this.node.disconnect();      } catch {}      if (this.instance._node === this) {        this.instance._node = null;        if (!this.instance.closed) await call("plugins_stream_close", { instance: this.instance.id }).catch(() => {});      }    }  }  class Instance {    constructor(info) {      this.id = info.instance;      this.plugin = Object.freeze({ ...info.plugin });      this.name = info.name;      this.sampleRate = info.sampleRate;      this.blockSize = info.blockSize;      this.offline = info.offline;      this.latency = info.latency;      this.tail = info.tail;      this.inputs = info.inputs;      this.outputs = info.outputs;      this.layout = info.layout;      this.inBuses = info.inBuses;      this.outBuses = info.outBuses;      this.hasEditor = info.hasEditor;      this.parameterCount = info.params;      this.bypassParameter = info.bypassParam;      this.closed = false;      this.lost = null;      this._editor = false;      this._node = null;      this._ring = null;      this._handlers = new Map();    }    get editorOpen() {      return this._editor;    }    on(type, fn) {      return on(this._handlers, type, fn);    }    _check() {      if (this.lost) throw new Error(`the plugin was lost (${this.lost.reason})`);      if (this.closed) throw new Error("the plugin is closed");    }    _latency(samples) {      this.latency = samples;      emit(this._handlers, "latency", { latency: samples });    }    _lose(lost) {      this.lost = lost;      this.closed = true;      this._editor = false;      live.delete(this.id);      if (this._node) this._node.close();      emit(this._handlers, "lost", { ...lost });    }    async close() {      if (this.closed) return;      this.closed = true;      live.delete(this.id);      if (this._node) await this._node.close();      await call("plugins_close", { instance: this.id }).catch(() => {});    }    /** The plugin's own editor in its window, titled "<plugin> (<label>)"; it floats above the app's window. */    async showEditor(label) {      this._check();      const r = await call("plugins_editor", { instance: this.id, show: true, label: label === undefined ? null : String(label) });      this._editor = !!r.open;      return this._editor;    }    async hideEditor() {      this._check();      const r = await call("plugins_editor", { instance: this.id, show: false, label: null });      this._editor = !!r.open;      return this._editor;    }    /** The component's and the controller's state together, as bytes to keep with the mix. */    async getState() {      this._check();      return bytes(await call("plugins_get_state", { instance: this.id }));    }    async setState(state) {      this._check();      await call("plugins_set_state", bytes(state), { headers: { "Plugin-Instance": String(this.id) } });    }    /** [{id, title, shortTitle, units, steps, default, value, display, automatable, readOnly, hidden, list, bypass}] */    async parameters() {      this._check();      return call("plugins_params", { instance: this.id });    }    /** A normalized value, 0 to 1. */    async setParameter(id, value) {      this._check();      await call("plugins_set_param", { instance: this.id, id: Number(id) >>> 0, value: Number(value) });    }    /** Clears tails and delay lines; resolves with the latency. */    async reset() {      this._check();      const r = await call("plugins_reset", { instance: this.id });      if (typeof r.latency === "number" && r.latency !== this.latency) this._latency(r.latency);      return this.latency;    }    async setBypass(on) {      this._check();      await call("plugins_bypass", { instance: this.id, on: !!on });    }    /**     * The plugin as an AudioNode for `context` (stereo in, stereo out): an AudioWorkletNode trading blocks with the     * plugin through shared memory. In an AudioContext it plays `latency` frames behind (ring latency, default one     * render burst and 6 ms, plus the plugin's own); in an OfflineAudioContext it waits for each block instead. One     * node per instance at a time: a new one replaces the last.     */    async createNode(context, options = {}) {      this._check();      if (context.sampleRate !== this.sampleRate) throw new Error(`the context runs at ${context.sampleRate} Hz, the plugin at ${this.sampleRate} Hz`);      const offline = typeof OfflineAudioContext === "function" && context instanceof OfflineAudioContext;      await loadWorklet(context);      const node = new AudioWorkletNode(context, "juicewrld-plugin", {        numberOfInputs: 1,        numberOfOutputs: 1,        outputChannelCount: [2],        channelCount: 2,        channelCountMode: "explicit",        channelInterpretation: "speakers",      });      const latency = offline ? 0 : Number.isFinite(options.latency) ? options.latency : ringLatency(context);      if (this._node) await this._node.close();      this._ring = null;      const info = await call("plugins_stream", { instance: this.id, mode: offline ? "offline" : "realtime", latency });      const buffer = await ringFor(info.stream);      node.port.postMessage({ type: "ring", buffer }, [buffer]);      const pn = new PluginNode(this, context, node, info);      this._node = pn;      return pn;    }    /**     * Offline, no deadline: runs [left, right] (Float32Arrays of one length; one array is used for both) through the     * plugin and resolves with the processed pair, as long as it went in. For an instance without a node: open one for     * an export. `via: "ipc"` sends the audio through the app's IPC instead of shared memory (slower; for comparison).     */    async render(channels, options = {}) {      this._check();      const [left, right] = Array.isArray(channels) ? [channels[0], channels[1] || channels[0]] : [channels, channels];      if (!(left instanceof Float32Array) || !(right instanceof Float32Array) || left.length !== right.length) throw new TypeError("two Float32Arrays of one length");      if (this._node) throw new Error("this instance is playing through a node; open another for offline rendering");      if (options.via === "ipc") {        const body = new Uint8Array(left.length * 8);        new Float32Array(body.buffer, 0, left.length).set(left);        new Float32Array(body.buffer, left.length * 4, left.length).set(right);        const out = bytes(await call("plugins_render", body, { headers: { "Plugin-Instance": String(this.id), "Plugin-Frames": String(left.length) } }));        const f = new Float32Array(out.buffer, out.byteOffset, out.byteLength / 4);        return [f.slice(0, left.length), f.slice(left.length)];      }      if (!this._ring) {        const info = await call("plugins_stream", { instance: this.id, mode: "offline", latency: 0 });        this._ring = view(await ringFor(info.stream));      }      const r = this._ring;      const outL = new Float32Array(left.length);      const outR = new Float32Array(left.length);      const chunk = r.cap >> 1;      for (let done = 0; done < left.length; ) {        const n = Math.min(chunk, left.length - done);        const w = Atomics.load(r.h, AT.IN_WRITE);        put(r, r.planes[0], w, left.subarray(done, done + n));        put(r, r.planes[1], w, right.subarray(done, done + n));        Atomics.store(r.h, AT.IN_WRITE, (w + n) | 0);        const t0 = Date.now();        while (((Atomics.load(r.h, AT.OUT_WRITE) - w) | 0) < n) {          if (Atomics.load(r.h, AT.STATE) === STATE_LOST || this.lost) throw new Error("the plugin was lost");          if (Date.now() - t0 > 30000) throw new Error("the plugin stopped rendering");          await tick();        }        take(r, r.planes[2], w, outL.subarray(done, done + n));        take(r, r.planes[3], w, outR.subarray(done, done + n));        Atomics.store(r.h, AT.OUT_READ, (w + n) | 0);        done += n;      }      return [outL, outR];    }  }  const plugins = Object.freeze({    version: VERSION,    /**     * {api, supported, enabled, scanned, scanning, progress: {done, total, module} | null, plugins (listed), hidden,     * unread (modules that need activation or didn't load), unsupported (plugins that can't run here), scan: {modules,     * plugins, effects, instruments, read, loaded, failed, unsupported, stopped, millis, at} | null}. While plugins are     * off, only {api, supported, enabled}: nothing about what's installed.     */    async status() {      listen().catch(() => {});      return call("plugins_status");    },    /** Asks the user in the app's title bar to turn plugins on (which starts the first scan); true once on. */    async requestEnable() {      listen().catch(() => {});      return call("plugins_request_enable");    },    /**     * Asks the user in the app's title bar to scan for plugins now (the page can't start a full scan: only the user's     * press does; list() runs the quick check, which reads only new or changed files). Resolves true once a scan they     * started has finished, false if they said Not now.     */    async requestScan() {      listen().catch(() => {});      return call("plugins_request_scan");    },    /**     * The plugins found, less what the user hid: [{id, name, vendor, version, kind: "effect" | "instrument" | "other",     * categories, surround, module, sdkVersion, favourite (only there, true, for the ones the user starred)}], answered     * at once. The app also runs its quick check in the background (only new or changed plugin files are read); a     * "status" event follows when that adds plugins.     */    async list() {      listen().catch(() => {});      return call("plugins_list");    },    /**     * Opens the app's plugin manager (or brings it forward): the user's own window for their plugins, favourites,     * folders and scans. Resolves true when it opened; nothing in it reaches the page. A "status" event follows when the     * user changes something there.     */    async manage() {      listen().catch(() => {});      return (await call("plugins_manage")) === true;    },    /**     * Plugins in the folders that can't run here, to show greyed: [{name, file, format: "vst2" | "vst3", arch,     * reason: "vst2" | "32-bit" | "arm", replacement (its VST 3 version is installed), why (in words)}].     */    async unsupported() {      listen().catch(() => {});      return call("plugins_unsupported");    },    /** Opens an instance: {id, sampleRate, blockSize = 128, label = "", offline = false}. */    async open(options) {      await listen();      const o = options || {};      const info = await call("plugins_open", {        id: String(o.id || ""),        sampleRate: Number(o.sampleRate),        blockSize: o.blockSize === undefined ? null : Number(o.blockSize),        label: o.label === undefined ? null : String(o.label),        offline: !!o.offline,      });      const inst = new Instance(info);      live.set(inst.id, inst);      return inst;    },    /** The instances this page has open. */    instances() {      return [...live.values()];    },    /** "status" ({enabled, scanning, plugins, ...}) or "lost" ({reason, code, instances}); returns an unsubscribe. */    on(type, fn) {      listen().catch(() => {});      return on(handlers, type, fn);    },  });  Object.defineProperty(window, "juicewrldDesktop", {    value: Object.freeze({ version: VERSION, plugins }),    enumerable: false,    configurable: false,    writable: false,  });})();// window.juicewrldLikeShortcut, version 1: the keyboard shortcut that likes or unlikes what's playing from anywhere,// even while a game has the keyboard (src-tauri/src/like_shortcut.rs). The site's Settings reads and sets it; pressed,// the app sends the page a `juicewrld:like` event, and the page answers with notice() so Windows can say what changed.// Only on https://juicewrld.io.(() => {  "use strict";  if (location.origin !== "https://juicewrld.io" || window.top !== window || !window.__TAURI_INTERNALS__) return;  const call = (cmd, args) =>    window.__TAURI_INTERNALS__.invoke(cmd, args).catch((e) => {      throw new Error(typeof e === "string" ? e : (e && e.message) || "the app refused");    });  Object.defineProperty(window, "juicewrldLikeShortcut", {    value: Object.freeze({      version: 1,      /** The shortcut in force ("Ctrl+Alt+L"), or null. */      get: () => call("like_shortcut_get"),      /** Sets it (null turns it off); resolves the shortcut in force, or rejects with why it can't be used. */      set: (accelerator) => call("like_shortcut_set", { accelerator: accelerator == null ? null : String(accelerator) }),      /** After the shortcut liked or unliked a song: a Windows notification, while the app isn't in front. */      notice: (title, liked, grail) => call("like_notice", { title: String(title || ""), liked: !!liked, grail: !!grail }),    }),    enumerable: false,    configurable: false,    writable: false,  });})();// window.juicewrldNotifications, version 1: Windows notifications from the app (src-tauri/src/notices.rs) for what the site// would push to a browser, which the app's window can't show itself: new messages and message requests, replies and// the bell's other notes, and the site's alerts (src/components/desktop-alerts.tsx). A click, on the screen or later in// the Action Center, opens `url` in this window and brings it forward. Only on https://juicewrld.io.(() => {  "use strict";  if (location.origin !== "https://juicewrld.io" || window.top !== window || !window.__TAURI_INTERNALS__) return;  const call = (cmd, args) =>    window.__TAURI_INTERNALS__.invoke(cmd, args).catch((e) => {      throw new Error(typeof e === "string" ? e : (e && e.message) || "the app refused");    });  Object.defineProperty(window, "juicewrldNotifications", {    value: Object.freeze({      version: 1,      /**       * { title, body, url, tag?, quietIfFocused? } -> { shown, why? }. `url` is a page on the site ("/messages/12"); a       * newer notification with the same `tag` takes the older one's place; `quietIfFocused` shows nothing while the       * app's window is in front. `why`: "focused", "off" (Windows has the app's notifications off) or "busy" (too many       * this minute). Rejects with why it can't (not a page on the site, no title).       */      show: (n) =>        call("notify", {          title: String((n && n.title) || ""),          body: String((n && n.body) || ""),          url: String((n && n.url) || "/"),          tag: n && n.tag != null ? String(n.tag) : null,          quietIfFocused: !!(n && n.quietIfFocused),        }),    }),    enumerable: false,    configurable: false,    writable: false,  });})();// The title bar's room. A page with the site's own top chrome ([data-site-header], its top bar) fills the window and the// app's title bar lies over its top, see-through, so the page's colour (the moving cover, the mesh) runs up behind it;// the page leaves it the room: --app-bar-h on <html>, which the site's CSS adds to its top safe area (--safe-top,// src/app/globals.css), so its top chrome and everything that keeps clear of the top (Now Playing, the chat, dialogs)// keeps clear of the bar too. Any other page (the studio, the admin) starts below the bar, solid then. The app lays the// two out (`site_under_bar`, main.rs) and answers the bar's height in physical pixels; the room is that over// devicePixelRatio, so Ctrl+wheel zoom keeps it exact. A page's first guess comes from its address alone (the studio's// and the admin's are below the bar, every other page of the site under it), so a reload's first paint already has its// room; the page itself then says.//// 1.4.1 (the owner, 2026-11-21: "the window bar is overlappin on some pages still like the studio page ... the window bar// needs to blend better in with the actual site so its unnoticable"): a page left behind stays in the document, hidden// (React keeps the last routes' state), header and all, so only a header that shows counts; and below the bar, the bar// takes the colour along the page's top edge (`tint`), so the bar and the page's own top bar read as one.(() => {  "use strict";  if (location.origin !== "https://juicewrld.io" || window.top !== window || !window.__TAURI_INTERNALS__) return;  /** The bar's height in CSS pixels at 100% (main.rs BAR), until the app answers its physical height. */  const BAR_CSS = 36;  let barPx = 0;  let dpr = window.devicePixelRatio || 1;  /** Whether this page lies under the bar, as last asked; null before the first ask. */  let under = null;  /** The room is on <html> as `under` says (false while the document has no root yet: the observer paints then). */  let painted = false;  function paint() {    const root = document.documentElement;    if (!root) return;    painted = true;    if (!under) {      root.style.removeProperty("--app-bar-h");      root.removeAttribute("data-app-bar");      return;    }    const px = barPx ? barPx / (window.devicePixelRatio || 1) : BAR_CSS;    root.style.setProperty("--app-bar-h", `${Math.round(px * 1000) / 1000}px`);    root.setAttribute("data-app-bar", "");  }  /** The colour the solid bar takes: the page's top edge, as "rgb(r g b)"; null while under the bar. */  let tint = null;  /**   * The colour along the page's top edge: the backgrounds under the middle of its top row, from the page's own colour   * up to the topmost, laid one over another on a pixel (so translucent ones and color-mix() come out as drawn).   */  function topColour() {    try {      const layers = [];      for (let n = document.elementFromPoint(Math.round(innerWidth / 2), 1); n && layers.length < 24; n = n.parentElement) {        const c = getComputedStyle(n).backgroundColor;        if (c && c !== "transparent" && c !== "rgba(0, 0, 0, 0)") layers.push(c);      }      const canvas = document.createElement("canvas");      canvas.width = 1;      canvas.height = 1;      const g = canvas.getContext("2d", { willReadFrequently: true });      if (!g) return null;      g.fillStyle = "#0b0b0e";      g.fillRect(0, 0, 1, 1);      for (const c of layers.reverse()) {        g.fillStyle = c;        g.fillRect(0, 0, 1, 1);      }      const [r, gr, b] = g.getImageData(0, 0, 1, 1).data;      return `rgb(${r} ${gr} ${b})`;    } catch {      return null;    }  }  function ask() {    window.__TAURI_INTERNALS__.invoke("site_under_bar", { under: !!under, tint: under ? null : tint }).then(      (px) => {        if (typeof px === "number" && px > 0 && px !== barPx) {          barPx = px;          paint();        }      },      () => {},    );  }  function set(next) {    const colour = next ? null : topColour();    if (next === under && colour === tint) return;    under = next;    tint = colour;    paint();    ask();  }  /**   * Whether this page has the site's own top chrome, which leaves the bar its room: a header that shows. A page left   * behind keeps its hidden one in the document (the site also takes its marker off while it's hidden: nav.tsx).   */  const fits = () =>    [...document.querySelectorAll("[data-site-header]")].some((el) => (el.checkVisibility ? el.checkVisibility() : el.getClientRects().length > 0));  // The first guess, before the page is parsed: below for the studio's and the admin's addresses, which have no chrome of  // the site's, under for every other.  set(!/^\/(studio|admin)(\/|$)/.test(location.pathname));  // Then the page says. While it's parsed only a top bar arriving counts (the rest of it may be on its way); once it's in,  // whatever it has. After every move in the app (Next's router pushes or replaces history, Back and Forward pop it) the  // next frame has the new page; and every second, for anything else.  let parsed = document.readyState !== "loading";  const look = () => {    const has = fits();    if (has || parsed) set(has);  };  if (!parsed) {    const mo = new MutationObserver(() => {      if (!painted) paint();      if (fits()) set(true);    });    mo.observe(document, { childList: true, subtree: true });    document.addEventListener(      "DOMContentLoaded",      () => {        mo.disconnect();        parsed = true;        look();      },      { once: true },    );  }  const later = () => requestAnimationFrame(look);  for (const name of ["pushState", "replaceState"]) {    const original = History.prototype[name];    History.prototype[name] = function (...args) {      const r = original.apply(this, args);      later();      return r;    };  }  addEventListener("popstate", later);  setInterval(look, 1000);  // Zoomed (Ctrl+wheel) or on a screen of another scale: the room again, and the bar's height asked for anew.  addEventListener("resize", () => {    const now = window.devicePixelRatio || 1;    if (now === dpr) return;    dpr = now;    paint();    if (under) ask();  });})();