export const PROTOCOL = 1;
const FINAL = new Set([
"bad-key",
"no-room",
"no-player",
"name-taken",
"name-invalid",
"replaced",
"kicked",
"room-closed",
"full",
"locked",
"in-progress",
"protocol",
"left",
"rate-limited",
"too-big",
]);
const FINAL_CODES = {
1009: "too-big",
4002: "protocol",
4003: "bad-key",
4004: "no-room",
4005: "no-player",
4006: "name-taken",
4007: "name-invalid",
4008: "rate-limited",
4009: "replaced",
4010: "kicked",
4011: "room-closed",
4029: "full",
4030: "in-progress",
};
const MAX_PENDING = 32;
const INPUT_INTERVAL = 100;
export class PartyActionError extends Error {
code;
constructor(code, message) {
super(message);
this.name = "PartyActionError";
this.code = code;
}
}
function isObject(v) {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
export function applyDiff(view, d) {
if (d.set)
merge(view, d.set);
for (const path of d.del ?? []) {
let o = view;
for (let i = 0; i < path.length - 1 && isObject(o); i++)
o = o[path[i]];
if (isObject(o))
delete o[path[path.length - 1]];
}
return view;
}
function merge(target, patch) {
for (const k of Object.keys(patch)) {
const pv = patch[k];
if (isObject(pv) && isObject(target[k]))
merge(target[k], pv);
else
target[k] = pv;
}
}
export function joinText(join) {
const s = join?.short;
if (typeof s !== "string" || !/^https?:\/\/[^/?#\s]+\/[A-Za-z]{1,16}$/.test(s))
return null;
return s.replace(/^https?:\/\//, "");
}
export function qrSvg(qr, opts = {}) {
if (!qr)
return "";
const quiet = opts.quiet ?? 4;
const n = qr.size + 2 * quiet;
const color = (c) => (/^[#a-zA-Z0-9(),.% ]+$/.test(c) ? c : "#000");
let d = "";
qr.rows.forEach((row, y) => {
for (let x = 0; x < row.length; x++) {
if (row[x] !== "1")
continue;
let w = 1;
while (row[x + w] === "1")
w++;
d += `M${x + quiet} ${y + quiet}h${w}v1h-${w}z`;
x += w - 1;
}
});
return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${n}" shape-rendering="crispEdges">` +
`<rect width="${n}" height="${n}" fill="${color(opts.light ?? "#fff")}"/>` +
`<path d="${d}" fill="${color(opts.dark ?? "#000")}"/></svg>`);
}
export function drawQr(ctx, qr, x, y, size, opts = {}) {
if (!qr)
return;
const quiet = opts.quiet ?? 4;
const px = size / (qr.size + 2 * quiet);
ctx.fillStyle = opts.light ?? "#fff";
ctx.fillRect(x, y, size, size);
ctx.fillStyle = opts.dark ?? "#000";
qr.rows.forEach((row, r) => {
for (let c = 0; c < row.length; c++) {
if (row[c] !== "1")
continue;
let w = 1;
while (row[c + w] === "1")
w++;
const x0 = Math.round(x + (c + quiet) * px);
const x1 = Math.round(x + (c + w + quiet) * px);
const y0 = Math.round(y + (r + quiet) * px);
const y1 = Math.round(y + (r + 1 + quiet) * px);
ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
c += w - 1;
}
});
}
export const SOCKET_PATH = "/_tvpipe/ws";
export class PartyClient {
static fromLocation(opts = {}) {
const loc = globalThis.location;
const q = new URLSearchParams(loc.search);
const h = new URLSearchParams(loc.hash.replace(/^#/, ""));
const room = opts.room ?? h.get("r") ?? q.get("r") ?? "";
const key = opts.key ?? h.get("k") ?? q.get("k") ?? undefined;
const url = opts.url ?? `${loc.protocol === "https:" ? "wss:" : "ws:"}//${loc.host}${SOCKET_PATH}`;
const r = opts.role ?? h.get("role") ?? "player";
const role = r === "screen" || r === "watch" ? r : "player";
return new PartyClient({ ...opts, url, room, key, role });
}
url;
room;
key;
role;
storage;
view = {};
you = null;
status = "idle";
byeReason = null;
#WS;
#listeners = new Map();
#ws = null;
#rev = 0;
#attempt = 0;
#retry = null;
#pinger = null;
#name;
#nextAct = 1;
#pending = new Map();
#inSeq = 0;
#inLast = 0;
#inQueued = null;
#inTimer = null;
#offset = 0;
#bestRtt = Infinity;
#samples = [];
#waiting = null;
#onVisible = () => {
if (globalThis.document?.visibilityState !== "visible")
return;
if (this.status === "reconnecting") {
this.#attempt = 0;
this.#open();
}
};
constructor(opts) {
this.url = opts.url;
this.room = opts.room.toUpperCase();
this.key = opts.key;
this.role = opts.role ?? "player";
this.storage = opts.storage !== undefined ? opts.storage : safeStorage();
this.#WS = opts.WebSocket ?? globalThis.WebSocket;
}
get #storageKey() {
let host = "";
try {
host = new URL(this.url).host;
}
catch { }
return `tvpipe-party:${host}:${this.room}:${this.role}`;
}
get saved() {
try {
const s = this.storage?.getItem(this.#storageKey);
const v = s ? JSON.parse(s) : null;
return isObject(v) ? v : null;
}
catch {
return null;
}
}
get canResume() {
return this.role !== "player" || typeof this.saved?.resume === "string";
}
on(event, fn) {
let set = this.#listeners.get(event);
if (!set)
this.#listeners.set(event, (set = new Set()));
set.add(fn);
return () => set.delete(fn);
}
off(event, fn) {
this.#listeners.get(event)?.delete(fn);
}
#emit(event, ...args) {
for (const fn of [...(this.#listeners.get(event) ?? [])]) {
try {
fn(...args);
}
catch (err) {
console.error(err);
}
}
}
join(name) {
this.#name = name;
return this.connect();
}
connect() {
if (this.#name === undefined)
this.#name = this.saved?.name;
return new Promise((resolve, reject) => {
this.#waiting = { resolve, reject };
this.byeReason = null;
this.#attempt = 0;
globalThis.document?.addEventListener?.("visibilitychange", this.#onVisible);
this.#open();
});
}
#open() {
if (this.#retry)
clearTimeout(this.#retry);
this.#retry = null;
if (this.#ws) {
const old = this.#ws;
this.#ws = null;
old.onclose = null;
try {
old.close();
}
catch { }
}
this.#setStatus(this.you ? "reconnecting" : "connecting");
let ws;
try {
ws = new this.#WS(this.url);
}
catch (err) {
return this.#fail("protocol", String(err));
}
this.#ws = ws;
ws.onopen = () => {
const saved = this.saved;
const hello = { t: "hello", v: PROTOCOL, room: this.room, role: this.role, key: this.key };
if (this.role === "player") {
if (saved?.resume)
hello["resume"] = saved.resume;
if (this.#name !== undefined)
hello["name"] = this.#name;
}
hello["agent"] = globalThis.navigator?.userAgent ?? "";
ws.send(JSON.stringify(hello));
};
ws.onmessage = (ev) => {
if (typeof ev.data !== "string")
return;
let msg;
try {
msg = JSON.parse(ev.data);
}
catch {
return;
}
if (isObject(msg))
this.#onMessage(msg);
};
ws.onerror = () => { };
ws.onclose = (ev) => {
if (this.#ws !== ws)
return;
this.#ws = null;
this.#stopPing();
const reason = this.byeReason ?? FINAL_CODES[ev.code] ?? null;
if (reason && FINAL.has(reason)) {
if (!this.byeReason) {
this.byeReason = reason;
this.#emit("bye", reason, ev.reason || undefined);
}
return this.#fail(reason, ev.reason || reason);
}
if (this.status === "closed")
return;
this.#setStatus(this.you ? "reconnecting" : "connecting");
const delay = Math.min(5000, 250 * 2 ** this.#attempt++) * (0.75 + Math.random() * 0.5);
this.#retry = setTimeout(() => this.#open(), delay);
};
}
#fail(reason, message) {
this.#setStatus("closed");
if (reason === "no-player" || reason === "kicked" || reason === "bad-key")
this.#forget();
const err = new PartyActionError(reason, message);
for (const p of this.#pending.values())
p.reject(err);
this.#pending.clear();
if (this.#waiting) {
this.#waiting.reject(err);
this.#waiting = null;
}
this.#stopInput();
globalThis.document?.removeEventListener?.("visibilitychange", this.#onVisible);
}
#forget() {
try {
this.storage?.removeItem(this.#storageKey);
}
catch { }
}
#setStatus(s) {
if (this.status === s)
return;
this.status = s;
this.#emit("status", s);
}
#onMessage(msg) {
switch (msg["t"]) {
case "welcome": {
const first = this.you === null;
this.you = msg["you"];
this.view = msg["view"] ?? {};
this.#rev = msg["rev"] ?? 0;
this.#attempt = 0;
this.#sample(0, msg["now"]);
if (this.role === "player" && msg["you"]?.resume) {
try {
this.storage?.setItem(this.#storageKey, JSON.stringify({ resume: msg["you"].resume, name: msg["you"].name }));
}
catch { }
}
this.#setStatus("open");
const last = Number(msg["you"]?.lastAct ?? 0);
if (first) {
const queued = [...this.#pending.values()];
this.#pending.clear();
this.#nextAct = last + 1;
for (const p of queued)
this.#pending.set(this.#nextAct++, p);
}
for (const [id, p] of this.#pending)
this.#send({ t: "act", id, type: p.type, data: p.data });
this.#startPing();
this.#emit("welcome", msg);
this.#emit("view", this.view, null);
if (this.#waiting) {
this.#waiting.resolve(msg);
this.#waiting = null;
}
return;
}
case "state": {
if (typeof msg["rev"] === "number" && msg["rev"] <= this.#rev)
return;
if (msg["full"]) {
this.view = msg["full"];
}
else {
if (msg["rev"] !== this.#rev + 1)
this.#send({ t: "resync" });
applyDiff(this.view, msg);
}
this.#rev = msg["rev"];
this.#emit("view", this.view, msg);
return;
}
case "ack": {
const p = this.#pending.get(msg["id"]);
if (!p)
return;
this.#pending.delete(msg["id"]);
if (msg["ok"])
p.resolve(msg["result"] ?? null);
else
p.reject(new PartyActionError(msg["error"]?.code ?? "error", msg["error"]?.message ?? "refused"));
this.#emit("ack", msg);
return;
}
case "msg":
this.#emit("msg", msg["type"], msg["data"]);
return;
case "pong":
this.#sample(msg["c"], msg["now"]);
return;
case "bye":
this.byeReason = String(msg["reason"]);
this.#emit("bye", this.byeReason, msg["message"]);
return;
}
}
#sample(c, now) {
if (typeof now !== "number")
return;
const t = Date.now();
const rtt = c > 0 ? t - c : 1000; this.#samples.push({ rtt, offset: now - (c > 0 ? (c + t) / 2 : t) });
if (this.#samples.length > 16)
this.#samples.shift();
const best = this.#samples.reduce((a, b) => (b.rtt < a.rtt ? b : a));
this.#offset = best.offset;
this.#bestRtt = best.rtt;
}
#startPing() {
this.#stopPing();
let n = 0;
const ping = () => this.#send({ t: "ping", c: Date.now() });
ping();
this.#pinger = setInterval(() => {
ping();
if (++n === 4 && this.#pinger) {
clearInterval(this.#pinger);
this.#pinger = setInterval(ping, 10_000);
}
}, 300);
}
#stopPing() {
if (this.#pinger)
clearInterval(this.#pinger);
this.#pinger = null;
}
now() {
return Date.now() + this.#offset;
}
get rtt() {
return this.#bestRtt;
}
#send(msg) {
const ws = this.#ws;
if (!ws || ws.readyState !== 1 || this.status !== "open")
return false;
ws.send(JSON.stringify(msg));
return true;
}
input(data) {
if (this.status !== "open")
return;
this.#inQueued = { data };
if (this.#inTimer)
return;
const wait = this.#inLast + INPUT_INTERVAL - Date.now();
if (wait <= 0)
return this.#flushInput();
this.#inTimer = setTimeout(() => {
this.#inTimer = null;
this.#flushInput();
}, wait);
}
#flushInput() {
const q = this.#inQueued;
this.#inQueued = null;
if (!q || this.status !== "open")
return;
this.#inLast = Date.now();
this.#send({ t: "in", s: ++this.#inSeq, data: q.data });
}
#stopInput() {
if (this.#inTimer)
clearTimeout(this.#inTimer);
this.#inTimer = null;
this.#inQueued = null;
}
act(type, data = null) {
if (this.status === "closed")
return Promise.reject(new PartyActionError("closed", "Not connected"));
if (this.#pending.size >= MAX_PENDING)
return Promise.reject(new PartyActionError("busy", "Too many actions waiting"));
const id = this.#nextAct++;
return new Promise((resolve, reject) => {
this.#pending.set(id, { type, data, resolve, reject });
this.#send({ t: "act", id, type, data });
});
}
leave() {
this.#send({ t: "leave" });
this.byeReason = "left";
this.#forget();
this.close();
}
close() {
this.#setStatus("closed");
if (this.#retry)
clearTimeout(this.#retry);
this.#stopPing();
this.#stopInput();
const ws = this.#ws;
this.#ws = null;
if (ws) {
ws.onclose = null;
try {
ws.close();
}
catch { }
}
for (const p of this.#pending.values())
p.reject(new PartyActionError("closed", "Closed"));
this.#pending.clear();
globalThis.document?.removeEventListener?.("visibilitychange", this.#onVisible);
}
drop() {
try {
this.#ws?.close(4999, "dropped");
}
catch { }
}
}
function safeStorage() {
try {
const s = globalThis.localStorage;
if (!s)
return null;
s.getItem("x");
return s;
}
catch {
return null;
}
}
export function memoryStorage() {
const m = new Map();
return {
getItem: (k) => (m.has(k) ? m.get(k) : null),
setItem: (k, v) => void m.set(k, String(v)),
removeItem: (k) => void m.delete(k),
};
}