/** * Base64 carriage for real `@colyseus/schema` binary state on the JSON * `Envelope` wire. * * The replication seam encodes host state with the REAL `@colyseus/schema` * `Encoder`, which emits a `Uint8Array`. Every P2P transport (browser-hosted * WebRTC, universal WebSocket, forced/​fallback Cloudflare relay, in-process * loopback) carries an `Envelope` that is `JSON.stringify`'d, so the binary * patch/snapshot bytes ride as a base64 STRING field inside that envelope — * universal, and unchanged by `JSON.stringify`. There is deliberately no * native binary frame kind: a raw binary frame during join is the live signal * `client.ts`'s H4 guard uses to detect a real Colyseus server, and a separate * binary-frame optimization is out of scope here. * * `btoa`/`atob` exist in browsers and in Node ≥16 (`globalThis`), so these work * in the deployed static bundle and in headless unit tests without a Buffer * dependency. */ const CHUNK = 0x8000; export function bytesToBase64(bytes: Uint8Array): string { let binary = ''; for (let i = 0; i < bytes.length; i += CHUNK) { binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK)); } return btoa(binary); } export function base64ToBytes(base64: string): Uint8Array { const binary = atob(base64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return bytes; }