/* party.js — watch-together hooks (docs/api.md "Party"). Inert ('solo') until a transport attaches and the server says who is host; the public site never attaches one. import { party } from './party.js' also window.bugtvParty, plus a 'bugtv:party-ready' window event party.mode 'solo' | 'host' | 'viewer' party.me / host user ids (from welcome / host messages) party.members [{id, username, avatar}] party.attach(transport) transport = { send(type, data) } → detach() party sends: 'route' {path}, 'play' {snapshot}, 'ping' {at} (the transport puts them on the wire as {t: type, ...data}) party.receive(msg) server messages {t: 'welcome'|'host'|'members'|'route'|'play'|'pong'|'error', …} party.now() server-synced ms (Date.now() until a pong/welcome arrives) party.publish(type, data) host only; no-op otherwise ('play' {snapshot: null} = left the watch page) party.resend() host only: re-publish current route + snapshot (after a reconnect) party.on(type, fn) → off 'mode' | 'members' | 'route' | 'play' | 'error' | 'resend' party.lastRoute / lastPlay last relayed route path / snapshot (for late subscribers) party.hostName() host's username ('' if unknown) Pings: on attach party sends a few pings (1s apart), then one every 15s, and takes the median of the last 5 offsets. */ const listeners = new Map(); const offsets = []; let offset = 0; let pingTimer = null; let pingCount = 0; function emit(type, data) { const set = listeners.get(type); if (!set) return; for (const fn of [...set]) { try { fn(data); } catch (e) { console.error('[party]', type, e); } } } function setClasses(mode) { if (typeof document === 'undefined') return; const c = document.documentElement.classList; c.toggle('party-host', mode === 'host'); c.toggle('party-viewer', mode === 'viewer'); } function median(list) { const s = list.slice().sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; } export const party = { mode: 'solo', me: null, host: null, members: [], transport: null, lastRoute: null, lastPlay: null, attach(transport) { this.transport = transport || null; clearInterval(pingTimer); pingCount = 0; if (this.transport) { const ping = () => { pingCount++; this._send('ping', { at: Date.now() }); if (pingCount === 5) { clearInterval(pingTimer); pingTimer = setInterval(ping, 15000); } }; ping(); pingTimer = setInterval(ping, 1000); } return () => { if (this.transport !== transport) return; clearInterval(pingTimer); this.transport = null; this._setMode('solo'); }; }, receive(msg) { if (!msg || typeof msg !== 'object') return; const t = msg.t || msg.type; switch (t) { case 'welcome': { this.me = msg.you ? String(msg.you.id) : this.me; this.host = msg.host != null ? String(msg.host) : null; this.members = Array.isArray(msg.members) ? msg.members : []; if (typeof msg.now === 'number' && !offsets.length) offset = msg.now - Date.now(); this.lastRoute = msg.route || null; // a stale snapshot (host already left the watch page) must not drag viewers back this.lastPlay = msg.play && (!msg.route || msg.play.path === msg.route) ? msg.play : null; this._setMode(this._derive()); emit('members', this.members); if (this.mode === 'viewer') { if (this.lastRoute) emit('route', { path: this.lastRoute }); if (this.lastPlay) emit('play', this.lastPlay); } break; } case 'host': this.host = msg.host != null ? String(msg.host) : null; this._setMode(this._derive()); break; case 'members': this.members = Array.isArray(msg.members) ? msg.members : []; emit('members', this.members); break; case 'route': if (!msg.path) return; this.lastRoute = msg.path; if (this.mode === 'viewer') emit('route', { path: msg.path }); break; case 'play': // snapshot null: the host left the watch page this.lastPlay = msg.snapshot || null; if (this.mode === 'viewer' && msg.snapshot) emit('play', msg.snapshot); break; case 'pong': { if (typeof msg.at !== 'number' || typeof msg.now !== 'number') return; const rtt = Date.now() - msg.at; if (rtt < 0 || rtt > 30000) return; offsets.push(msg.now - (msg.at + rtt / 2)); if (offsets.length > 5) offsets.shift(); offset = median(offsets); break; } case 'error': emit('error', msg); break; default: break; } }, now() { return Date.now() + offset; }, publish(type, data) { if (this.mode !== 'host') return; this._send(type, data || {}); }, // host: re-publish the current route + snapshot (the overlay calls this after a reconnect) resend() { if (this.mode === 'host') emit('resend', {}); }, on(type, fn) { if (!listeners.has(type)) listeners.set(type, new Set()); listeners.get(type).add(fn); return () => listeners.get(type).delete(fn); }, hostName() { const m = this.members.find((x) => x && String(x.id) === this.host); return (m && (m.global_name || m.username)) || ''; }, _send(type, data) { if (!this.transport || typeof this.transport.send !== 'function') return; try { this.transport.send(type, data); } catch (e) { console.warn('[party] send failed', e); } }, _derive() { if (!this.transport || !this.me || !this.host) return 'solo'; return this.me === this.host ? 'host' : 'viewer'; }, _setMode(mode) { if (mode === this.mode) return; const prev = this.mode; this.mode = mode; setClasses(mode); emit('mode', { mode, prev }); }, }; if (typeof window !== 'undefined') { window.bugtvParty = party; try { window.dispatchEvent(new CustomEvent('bugtv:party-ready', { detail: party })); } catch (e) { /* very old browsers */ } } export default party;