Initial Commit
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Host-side table connection (contract 41 client rules TP-4xx/5xx), used by the table page (M19).
|
||||
* Owns both sockets and all credentials (CS-12); the game iframe only sees ordered `state` messages.
|
||||
*/
|
||||
import { io, type Socket } from "socket.io-client";
|
||||
|
||||
export interface HostCallbacks {
|
||||
onState(env: any): void;
|
||||
onViewChanged(view: string | null): void;
|
||||
onAck(ack: { cid: number; status: string; code?: string }): void;
|
||||
onStatus(status: string): void;
|
||||
onConnection(state: "connecting" | "online" | "offline"): void;
|
||||
onHello?(h: { server_time_ms: number; view: string | null; ep: number }): void;
|
||||
}
|
||||
|
||||
const rand = () => Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
function ss(): Storage | null { try { return window.sessionStorage; } catch { return null; } }
|
||||
|
||||
export class TableConnection {
|
||||
readonly ci: string;
|
||||
private cid: number;
|
||||
private ing!: Socket;
|
||||
private egr!: Socket;
|
||||
private view: string | null = null;
|
||||
private vseq = 0;
|
||||
private ep = 0;
|
||||
private buffer = new Map<number, any>();
|
||||
private resyncAt = 0;
|
||||
private pending = new Map<number, { type: string; payload: unknown; known?: unknown }>();
|
||||
private closed = false;
|
||||
|
||||
constructor(private tid: string, private origin: string, private getTicket: (ci: string) => Promise<string>, private cb: HostCallbacks) {
|
||||
const s = ss();
|
||||
const key = `m3.ci.${tid}`;
|
||||
this.ci = s?.getItem(key) ?? rand(); // TP-004: fresh ci per tab per table
|
||||
s?.setItem(key, this.ci);
|
||||
this.cid = Number(s?.getItem(`m3.cid.${tid}.${this.ci}`) ?? 0);
|
||||
}
|
||||
|
||||
connect() {
|
||||
const auth = (extra: () => object) => (cb: (d: object) => void) => {
|
||||
this.getTicket(this.ci).then((ticket) => cb({ ticket, ...extra() })).catch(() => cb({ ticket: "" }));
|
||||
};
|
||||
const common = { transports: ["websocket"], reconnectionDelay: 500, reconnectionDelayMax: 4000 };
|
||||
this.cb.onConnection("connecting");
|
||||
this.ing = io(this.origin, { ...common, path: "/t/in", auth: auth(() => ({})) });
|
||||
this.egr = io(this.origin, { ...common, path: "/t/out", auth: auth(() => (this.view ? { resume: { view: this.view, after_vseq: this.vseq } } : {})) });
|
||||
|
||||
this.ing.on("connect", () => {
|
||||
// TP-501: re-send pending commands with their original cid
|
||||
for (const [cid, p] of [...this.pending.entries()].sort((a, b) => a[0] - b[0])) this.emitCmd(cid, p.type, p.payload, p.known);
|
||||
this.updateConn();
|
||||
});
|
||||
this.ing.on("disconnect", () => this.updateConn());
|
||||
this.egr.on("connect", () => this.updateConn());
|
||||
this.egr.on("disconnect", () => this.updateConn());
|
||||
this.egr.on("hello", (h: any) => {
|
||||
if (h.view !== this.view) this.setView(h.view);
|
||||
this.cb.onHello?.(h);
|
||||
});
|
||||
this.egr.on("sys", (s: any) => {
|
||||
if (s.kind === "view_changed") this.setView(s.view);
|
||||
if (s.kind === "status") this.cb.onStatus(s.status);
|
||||
});
|
||||
this.egr.on("m", (env: any) => this.onMessage(env));
|
||||
this.egr.on("ack", (a: any) => {
|
||||
if (!this.pending.has(a.cid)) return; // TP-504
|
||||
this.pending.delete(a.cid);
|
||||
this.cb.onAck(a);
|
||||
});
|
||||
}
|
||||
|
||||
private updateConn() {
|
||||
if (this.closed) return;
|
||||
this.cb.onConnection(this.ing?.connected && this.egr?.connected ? "online" : "offline");
|
||||
}
|
||||
|
||||
private setView(view: string | null) { // TP-405
|
||||
this.view = view; this.vseq = 0; this.buffer.clear();
|
||||
this.cb.onViewChanged(view);
|
||||
}
|
||||
|
||||
private onMessage(env: any) {
|
||||
if (env.view !== this.view) return; // TP-401
|
||||
if (env.vseq <= this.vseq) return; // TP-402
|
||||
this.ep = Math.max(this.ep, env.ep);
|
||||
if (env.t === "snap") { // TP-403
|
||||
this.vseq = env.vseq;
|
||||
this.cb.onState(env);
|
||||
this.drain();
|
||||
return;
|
||||
}
|
||||
if (this.vseq > 0 && env.vseq === this.vseq + 1) { // TP-404
|
||||
this.vseq = env.vseq;
|
||||
this.cb.onState(env);
|
||||
this.drain();
|
||||
return;
|
||||
}
|
||||
this.buffer.set(env.vseq, env);
|
||||
if (this.buffer.size > 256) this.buffer.clear();
|
||||
const now = Date.now();
|
||||
if (now - this.resyncAt > 3000) { this.resyncAt = now; this.egr.emit("resync", { view: this.view, after_vseq: this.vseq }); }
|
||||
}
|
||||
|
||||
private drain() {
|
||||
for (const k of [...this.buffer.keys()]) if (k <= this.vseq) this.buffer.delete(k);
|
||||
while (this.buffer.has(this.vseq + 1)) {
|
||||
const env = this.buffer.get(this.vseq + 1);
|
||||
this.buffer.delete(this.vseq + 1);
|
||||
this.vseq = env.vseq;
|
||||
this.cb.onState(env);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the assigned cid; result arrives via onAck. */
|
||||
send(type: string, payload: unknown): number {
|
||||
const cid = ++this.cid;
|
||||
ss()?.setItem(`m3.cid.${this.tid}.${this.ci}`, String(cid));
|
||||
const known = this.view ? { ep: this.ep, view: this.view, vseq: this.vseq } : undefined;
|
||||
this.pending.set(cid, { type, payload, known });
|
||||
if (this.ing.connected) this.emitCmd(cid, type, payload, known);
|
||||
return cid;
|
||||
}
|
||||
|
||||
private emitCmd(cid: number, type: string, payload: unknown, known?: unknown) {
|
||||
this.ing.emit("cmd", { tid: this.tid, cid, type, payload, known }, (r: any) => {
|
||||
if (r && !r.ok) { this.pending.delete(cid); this.cb.onAck({ cid, status: "failed", code: r.code }); }
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.ing?.close();
|
||||
this.egr?.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Game-bundle side of the postMessage protocol (contract 43 §2). Messages are `{ m3: 1, type, ... }`.
|
||||
* The host origin is passed as `?host=<origin>` in the iframe URL and checked on every message (CS-20).
|
||||
*/
|
||||
export interface InitMsg {
|
||||
table_id: string; game_version: string; replay: boolean;
|
||||
me: { user_id: string; seat?: number; role: string; view: string | null };
|
||||
participants: { user_id: string; seat?: number; display: string; is_bot: boolean }[];
|
||||
options: Record<string, unknown>; locale: "fa" | "en"; dir: "rtl" | "ltr"; theme: Record<string, string>; server_offset_ms?: number;
|
||||
}
|
||||
export interface GameHandlers {
|
||||
onInit(init: InitMsg): void;
|
||||
onState(env: any): void;
|
||||
onAck?(a: { cid: number; status: string; code?: string; req_id?: number }): void;
|
||||
onViewChanged?(view: string | null): void;
|
||||
onCmdFailed?(reqId: number, code: string): void;
|
||||
}
|
||||
|
||||
export function connectHost(h: GameHandlers) {
|
||||
const hostOrigin = new URLSearchParams(location.search).get("host") ?? "*";
|
||||
const post = (msg: object) => window.parent.postMessage({ m3: 1, ...msg }, hostOrigin);
|
||||
let reqId = 0;
|
||||
window.addEventListener("message", (e) => {
|
||||
if (e.source !== window.parent || (hostOrigin !== "*" && e.origin !== hostOrigin)) return;
|
||||
const m = e.data;
|
||||
if (!m || m.m3 !== 1) return;
|
||||
switch (m.type) {
|
||||
case "init": h.onInit(m); post({ type: "ready" }); break;
|
||||
case "state": h.onState(m.env); break;
|
||||
case "ack": h.onAck?.(m); break;
|
||||
case "view_changed": h.onViewChanged?.(m.view); break;
|
||||
case "cmd_failed": h.onCmdFailed?.(m.req_id, m.code); break;
|
||||
}
|
||||
});
|
||||
post({ type: "loaded" });
|
||||
return {
|
||||
cmd(type: string, payload: unknown = {}) { const id = ++reqId; post({ type: "cmd", cmd_type: type, payload, req_id: id }); return id; },
|
||||
toast(text_fa: string, text_en: string, kind: "info" | "warn" | "error" = "info") { post({ type: "toast", text_fa, text_en, kind }); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./host.ts";
|
||||
export * from "./iframe.ts";
|
||||
Reference in New Issue
Block a user