UNPKG

theater-client

Version:

TypeScript client library for Theater actor system TCP protocol

92 lines (78 loc) 2.32 kB
/** * Serialization utilities for Theater protocol */ import type { FrameMessage } from '../types/protocol.js'; /** * Convert Uint8Array to number array for protocol compatibility */ export function uint8ArrayToNumbers(data: Uint8Array): number[] { return Array.from(data); } /** * Convert number array from protocol to Uint8Array */ export function numbersToUint8Array(data: number[]): Uint8Array { return new Uint8Array(data); } /** * Encode string to Uint8Array */ export function encodeString(text: string): Uint8Array { return new TextEncoder().encode(text); } /** * Decode Uint8Array to string */ export function decodeString(data: Uint8Array): string { return new TextDecoder().decode(data); } /** * Encode object to JSON bytes */ export function encodeJson(obj: any): Uint8Array { return encodeString(JSON.stringify(obj)); } /** * Decode JSON bytes to object */ export function decodeJson<T = any>(data: Uint8Array): T { return JSON.parse(decodeString(data)); } /** * Create a FragmentingCodec frame for sending data * Always creates Complete frames for outgoing messages (server handles fragmentation) */ export function createFrame(data: Uint8Array): FrameMessage { return { Complete: uint8ArrayToNumbers(data) }; } /** * Parse a FragmentingCodec frame * Note: Fragment handling is now done in TheaterConnection.handleFragment() */ export function parseFrame(frame: FrameMessage): Uint8Array { if (frame.Complete) { return numbersToUint8Array(frame.Complete); } else if (frame.Fragment) { // Fragment messages are handled at the connection level throw new Error('Fragment parsing should be handled by TheaterConnection'); } else { throw new Error('Unknown frame type'); } } /** * Serialize a message for sending over TCP * Includes length prefix as required by Theater protocol */ export function serializeMessage(data: any): Buffer { // Convert to JSON string const jsonString = JSON.stringify(data); // Convert to bytes const messageBytes = Buffer.from(jsonString, 'utf8'); // Create length prefix (4 bytes, big-endian) const lengthPrefix = Buffer.allocUnsafe(4); lengthPrefix.writeUInt32BE(messageBytes.length, 0); // Combine length prefix and message return Buffer.concat([lengthPrefix, messageBytes]); }