Type Definitions
Comprehensive TypeScript type definitions for all Playcast APIs, ensuring type safety across your application
Quick Navigation
Core Types
Fundamental types used throughout the Playcast ecosystem
- PlaycastUser
- Vector2
- Serializable
- StateStore
Message Types
Types for real-time messaging and communication
- PlaycastMessage
- WebsocketMessage
- MessageTargets
- TimingEntry
Peer Types
WebRTC peer connection and media streaming types
- PeerConnection
- MediaTracks
- QualityPresets
- WebRTC Stats
Input Types
User input handling and control types
- GamepadInput
- KeyboardInput
- MouseInput
- TouchInput
Core Types
Fundamental types that form the foundation of the Playcast API.
Represents a user in the Playcast system with authentication and profile information.
interface PlaycastUser {
id: string; // Unique user identifier
authId: string; // Authentication provider ID
displayName: string; // User's display name
avatar?: string; // Avatar URL (optional)
platform: IdentityPlatform; // Authentication platform
profile?: UserProfile; // Extended profile information
}
Properties
| Property | Type | Required | Description |
|---|---|---|---|
| id | string | Required | Unique user identifier in the system |
| authId | string | Required | Authentication provider user ID |
| displayName | string | Required | User's visible display name |
| avatar | string | Optional | URL to user's avatar image |
| platform | IdentityPlatform | Required | Authentication platform used |
Two-dimensional vector for positions, movements, and coordinates.
type Vector2 = {
x: number; // X coordinate
y: number; // Y coordinate
}
Union type for values that can be safely serialized to JSON.
type Serializable =
| string
| number
| boolean
| null
| undefined
| Serializable[]
| { [key: string]: Serializable }
Generic reactive state container with subscription capabilities.
interface StateStore<T> {
get(): T; // Get current value
set(value: T): void; // Set new value
subscribe(callback: (value: T) => void): () => void; // Subscribe to changes
update(updater: (current: T) => T): void; // Update with function
}
Message Types
Types for the Playcast messaging system and real-time communication.
Core message structure for all Playcast communication.
type PlaycastMessage<T extends PlaycastMessageTarget> = {
signature: string; // Message signature
header: PlaycastMessageHeader & Pick<T, 'target' | 'action' | 'isReply'>;
body: {
message: T['message']; // Message payload
timings: PlaycastTimingEntry[]; // Performance timings
stats: PlaycastNameValuePair[]; // Statistics data
echo: boolean; // Echo flag
};
}
Header information for all Playcast messages.
interface PlaycastMessageHeader {
tag: string; // Unique message tag
source: PlaycastMessageSource; // Message source
schemaVersion: 5; // Message schema version
timestamp: number; // Unix timestamp
user: PlaycastUser; // User context
}
Performance timing information for message processing.
interface PlaycastTimingEntry {
app: PlaycastMessageSource; // Application that recorded timing
timestamp: number; // When timing was recorded
description: string; // Description of the timing point
metadata: Record<string, string>; // Additional metadata
}
Union of all possible WebSocket message types.
type WebsocketMessage =
| AuthMessage
| ConnectionMessage
| HostMessage
| InvitationMessage
| MetricsMessage
| LobbyMessage
| PeerMessage
| PresenceMessage
| SystemMessage
| OutboundMessage
| ProfileMessage
| MatchmakingMessage
| UserEventMessage
| AnalyticsMessage
| NotificationMessage
| AdminMessage
| VpnMessage;
Peer Types
Types for WebRTC peer connections and media streaming.
Base interface for all peer connection types.
interface PlaycastPeerBase {
peerId: string; // Unique peer identifier
qualityPresetStore: StateStore<PlaycastWebrtcPresetGroup>;
changeQualityProfile: (profile: PlaycastDefaultProfiles) => void;
setQualityPreset: (channel: PlaycastChannels, preset: Partial<PlaycastWebrtcPreset>) => void;
setQualityPresetGroup: (presetGroup: PlaycastWebrtcPresetGroup) => void;
handlePeerMessage: (message: PeerMessage) => void;
close: (kickReason?: string) => void;
}
WebRTC connection statistics and performance metrics.
interface PlaycastWebrtcStats {
bitrate: number; // Current bitrate (bps)
packetLoss: number; // Packet loss ratio (0-1)
roundTripTime: number; // RTT in milliseconds
jitter: number; // Jitter in milliseconds
frameRate: number; // Current frame rate
resolution: { // Current resolution
width: number;
height: number;
};
codecName: string; // Active codec name
bandwidth: number; // Available bandwidth
}
Quality preset configuration for media streams.
interface PlaycastWebrtcPreset {
maxBitrate: number; // Maximum bitrate (bps)
maxFramerate?: number; // Maximum frame rate
scaleResolutionDownBy?: number; // Resolution scaling factor
minBitrate?: number; // Minimum bitrate (bps)
startBitrate?: number; // Starting bitrate (bps)
}
Collection of media tracks indexed by name.
type PlaycastTrackSet = {
[trackName: string]: MediaStreamTrack | null;
}
User Types
Types related to user management, profiles, and authentication.
Metadata for client peer connections.
interface PlaycastPeerClientMetadata {
userId: string; // User identifier
displayName: string; // User's display name
avatar?: string; // Avatar URL
browserType: string; // Browser type
browserVersion: string; // Browser version
os: string; // Operating system
deviceType: 'mobile' | 'desktop' | 'tablet';
isAppleDevice: boolean; // Apple device flag
connectionType: string; // Connection type
networkQuality?: 'poor' | 'good' | 'excellent';
}
Metadata for host peer connections.
interface PlaycastPeerHostMetadata {
hostId: string; // Host identifier
sessionId: string; // Session identifier
gameTitle?: string; // Game being hosted
maxClients: number; // Maximum client connections
currentClients: number; // Current client count
hostCapabilities: { // Host capabilities
video: boolean;
audio: boolean;
input: boolean;
fileTransfer: boolean;
};
}
Input Types
Types for handling user input devices and events.
Gamepad input state and events.
interface PlaycastGamepadInput {
buttons: { // Button states
[button: string]: {
pressed: boolean; // Is button pressed
value: number; // Button pressure (0-1)
};
};
axes: { // Analog stick/trigger values
leftStick: Vector2; // Left stick (-1 to 1)
rightStick: Vector2; // Right stick (-1 to 1)
leftTrigger: number; // Left trigger (0-1)
rightTrigger: number; // Right trigger (0-1)
};
timestamp: number; // Input timestamp
}
Mouse input events and state.
interface PlaycastMouseInput {
position: Vector2; // Current mouse position
deltaPosition: Vector2; // Movement delta
buttons: { // Button states
left: boolean;
right: boolean;
middle: boolean;
};
wheelDelta: { // Scroll wheel
x: number;
y: number;
};
timestamp: number; // Input timestamp
}
Keyboard input events and modifier state.
interface PlaycastKeyboardInput {
key: string; // Key identifier
code: string; // Physical key code
pressed: boolean; // Key press state
repeat: boolean; // Is key repeat
modifiers: { // Modifier keys
ctrl: boolean;
alt: boolean;
shift: boolean;
meta: boolean;
};
timestamp: number; // Input timestamp
}
Enums & Constants
Enumerated values and constants used throughout the Playcast API.
Supported authentication platforms.
enum IdentityPlatform {
DISCORD = 'discord',
TWITCH = 'twitch',
CLERK = 'clerk'
}
Quality profile presets for streaming.
type PlaycastDefaultProfiles =
| 'ultra' // Highest quality
| 'high' // High quality
| 'medium' // Balanced quality
| 'low' // Lower quality for bandwidth saving
| 'potato' // Lowest quality for poor connections
Possible sources of Playcast messages.
type PlaycastMessageSource =
| 'player' // Player/client application
| 'host' // Host application
| 'playjector' // Native Playjector process
Window state for desktop applications.
type PlaycastWindowState =
| 'minimized' // Window is minimized
| 'maximized' // Window is maximized
| 'normal' // Window is in normal state
| 'closed' // Window is closed
Utility Types
Helper types and utilities for working with Playcast APIs.
State store for non-serializable values like MediaStreamTrack.
interface NonSerializableStateStore<T> {
get(): T; // Get current value
set(value: T): void; // Set new value
subscribe(callback: (value: T) => void): () => void; // Subscribe to changes
clear(): void; // Clear all values
}
Extract payload type for a given WebSocket message type.
type PayloadForMessageType<T extends WebsocketMessageType> =
T extends SystemMessageType
? Parameters<typeof generateSystemMessage>[1]
: T extends AuthMessageType
? Parameters<typeof generateAuthMessage>[1]
: T extends ConnectionMessageType
? Parameters<typeof generateConnectionMessage>[1]
// ... additional conditional types for other message types
: never;
Simple name-value pair for statistics and metadata.
interface PlaycastNameValuePair {
name: string; // Parameter or statistic name
value: string; // Parameter or statistic value
}
Type Inheritance Hierarchy
Understanding the relationships between types in the Playcast API.
Usage Examples
Practical examples of using Playcast types in your applications.
Creating Typed Message Handlers
import {
PlaycastMessage,
PlaycastGamepadMessages,
PlaycastMouseMessages
} from '@playcastdotio/Messaging';
// Type-safe message handler
function handleGamepadMessage(message: PlaycastMessage<PlaycastGamepadMessages>) {
switch (message.header.action) {
case 'buttonPressed':
console.log(`Button ${message.body.message.button} pressed`);
break;
case 'stickMoved':
console.log(`Stick moved to ${message.body.message.x}, ${message.body.message.y}`);
break;
default:
// TypeScript will warn about unhandled cases
console.log('Unknown gamepad action');
}
}
// Generic message router with type safety
type MessageHandler<T extends PlaycastMessageTarget> = (message: PlaycastMessage<T>) => void;
const messageHandlers: Record<string, MessageHandler<any>> = {
'gamepad': handleGamepadMessage,
'mouse': (message: PlaycastMessage<PlaycastMouseMessages>) => {
// Handle mouse messages
}
};
Working with Peer Types
import {
PlaycastPeerClient,
PlaycastWebrtcStats,
PlaycastDefaultProfiles
} from '@playcastdotio/Peer';
// Type-safe peer management
class PeerManager {
private peer: PlaycastPeerClient;
constructor(peer: PlaycastPeerClient) {
this.peer = peer;
this.setupStatisticsMonitoring();
}
private setupStatisticsMonitoring() {
this.peer.statistics.subscribe((stats: PlaycastWebrtcStats | null) => {
if (stats) {
this.handleStatistics(stats);
}
});
}
private handleStatistics(stats: PlaycastWebrtcStats) {
// Auto-adjust quality based on performance
if (stats.packetLoss > 0.05) {
this.adjustQuality('low');
} else if (stats.packetLoss < 0.01 && stats.bitrate > 2000000) {
this.adjustQuality('high');
}
}
private adjustQuality(profile: PlaycastDefaultProfiles) {
this.peer.changeQualityProfile(profile);
console.log(`Quality adjusted to ${profile}`);
}
}
Type-Safe Configuration
import {
MakeClientPeerConfig,
PlaycastPeerClientMetadata
} from '@playcastdotio/Peer';
// Create configuration with proper typing
const createPeerConfig = (
userId: string,
deviceInfo: Partial<PlaycastPeerClientMetadata>
): MakeClientPeerConfig => {
return {
realtimeApiManager: {
send: (message) => {
// Type-safe message sending
websocket.send(JSON.stringify(message));
}
},
iceServers: {
urls: ['stun:stun.l.google.com:19302'],
username: 'anonymous',
credential: ''
},
forceTurn: false,
additionalMetadata: {
isAppleDevice: /iPad|iPhone|iPod/.test(navigator.userAgent),
browserType: getBrowserType(),
...deviceInfo
}
};
};
// Usage with type checking
const config = createPeerConfig('user123', {
deviceType: 'desktop',
networkQuality: 'good'
});
- Compile-time error checking prevents runtime errors
- IntelliSense provides accurate autocompletion
- Refactoring is safer with guaranteed type consistency
- API changes are caught during development
- Documentation is embedded in the type definitions