Initial Commit
This commit is contained in:
@@ -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 }); },
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user