Enhanced Game Developer SDK for browser-based projects - integrate games with campaigns, leaderboards, and anti-cheat protection
npm install playe-developer-sdkbash
npm install playe-developer-sdk
or
yarn add playe-developer-sdk
or
pnpm add playe-developer-sdk
`
$3
`html
`
$3
`json
{
"dependencies": {
"@workspace/playe-developer-sdk": "workspace:*"
}
}
`
๐ Quick Start
$3
`typescript
import { createPlayeSDK } from "playe-developer-sdk";
// Initialize SDK
const sdk = createPlayeSDK({
apiBaseUrl: "https://api.playe.com",
apiKey: "your-api-key",
enableDebugMode: true,
});
// Initialize game session (gets sessionId from URL)
const session = await sdk.initializeGameSession();
// Start game
await sdk.startGameSession({
difficulty: "normal",
mode: "classic",
});
// Update progress
await sdk.updateGameProgress({
currentScore: 1500,
elapsedTime: 120,
gameState: {
level: 3,
lives: 2,
powerUps: ["speed", "shield"],
},
achievements: [
{
id: "level-3",
name: "Level 3 Complete",
unlockedAt: new Date().toISOString(),
},
],
});
// Complete game
const result = await sdk.completeGame({
finalScore: 2500,
validationChecksum: "client-checksum",
gameMetrics: {
totalPlayTime: 300,
actionsPerformed: 150,
powerUpsUsed: 5,
levelsCompleted: 5,
},
finalGameState: {
level: 5,
finalLives: 1,
},
});
`
$3
`html
`
๐ Table of Contents
- ๐ฎ Playe Developer SDK
- โจ Features
- ๐ Installation
- ๐ Quick Start
- ๐ Table of Contents
- ๐ง API Reference
- ๐ Security & Integrity
- ๐งช Testing & Development
- ๐จ Error Handling
- ๐ Examples
- ๐ Migration Guide
- ๐ง Troubleshooting
- ๐ค Contributing
- ๐ License
๐ง API Reference
$3
`typescript
interface SDKConfig {
apiBaseUrl: string; // Required: API base URL
apiKey?: string; // Optional: API key for authentication
enableDebugMode?: boolean; // Optional: Enable debug logging
retryAttempts?: number; // Optional: Number of retry attempts (default: 3)
timeoutMs?: number; // Optional: Request timeout in ms (default: 30000)
enableOfflineMode?: boolean; // Optional: Enable offline mode (default: false)
}
`
$3
#### Game Session Management
`typescript
// Initialize game session (gets sessionId from URL query parameter)
const session = await sdk.initializeGameSession(): Promise;
// Returns: { sessionId, campaignId, gameId, status, campaign, player, createdAt, expiresAt }
// Start game session
await sdk.startGameSession(config?: Record): Promise;
// Returns: { sessionId, status, startTime }
// Update game progress with integrity verification
await sdk.updateGameProgress({
currentScore: number;
gameState?: Record; // Automatically hashed for integrity
elapsedTime: number;
achievements?: Achievement[];
clientTimestamp?: string;
}): Promise;
// Returns: { isValid, validationMessage, currentRank, isLeading, campaignStatus, warnings }
// Complete game with integrity verification
await sdk.completeGame({
finalScore: number;
validationChecksum: string;
gameMetrics?: GameMetrics;
finalGameState?: Record; // Automatically hashed for integrity
}): Promise;
// Returns: { isWinner, prizeAmount, prizeType, finalRank, totalParticipants, winnerDetails, reward, campaignResult }
// Abandon game
await sdk.abandonGame(reason?: string, lastKnownScore?: number): Promise;
// Returns: { success, message, gamepassRefunded, abandonedAt }
`
#### Campaign Information
`typescript
// Get campaign status
await sdk.getCampaignStatus(campaignId: string, playerId?: string): Promise;
// Returns: { campaignId, status, campaignStyle, remainingGamepasses, totalParticipants,
// totalPrizePool, endDate, playerStatus, topPlayers, prizeBreakdown }
// Get leaderboard
await sdk.getLeaderboard(campaignId: string, limit?: number, playerId?: string): Promise;
// Returns: { campaignId, entries, playerRank, lastUpdated, isLive }
// entries: [{ rank, playerId, displayName, score, achievedAt, isCurrentPlayer, prizeAmount }]
// Get player attempts
await sdk.getPlayerAttempts(campaignId: string, playerId: string): Promise;
// Returns: { playerId, campaignId, totalAttempts, remainingAttempts, attempts, stats }
// attempts: [{ sessionId, score, playedAt, duration, status, wasWinner }]
// stats: { bestScore, averageScore, totalPlayTime, firstAttempt, lastAttempt }
`
#### Validation & Anti-Cheat
`typescript
// Validate game session with integrity verification
await sdk.validateGameSession({
clientChecksum: string;
stateSnapshot?: Record; // Automatically hashed
timingData?: unknown;
behaviorMetrics?: unknown;
}): Promise;
// Returns: { isValid, confidenceScore, validationIssues, warnings, requiresRevalidation, validatedAt }
// Send heartbeat (usually handled automatically)
await sdk.sendHeartbeat(currentScore?: number): Promise;
// Returns: { acknowledged, serverTimestamp, nextHeartbeatIn, campaignStillActive, message }
`
#### Developer Tools
`typescript
// Create test game session for development
await sdk.createTestGameSession(testConfig?: Record): Promise;
// Returns: { testSessionId, testScenario, mockCampaign, testData, expiresAt }
`
$3
`typescript
// Test SDK functionality
sdk.test('Custom test message'): void;
// Check if running in demo mode
const isDemoMode = sdk.isDemo(): boolean;
// Game lifecycle events
sdk.gameLoadingStart(): void; // Emit loading start event
sdk.gameLoadingFinished(): void; // Emit loading finished event
sdk.gamePlayStop(): void; // Stop heartbeat and emit stop event
// Clean up resources
sdk.destroy(): void; // Clean up session artifacts and stop heartbeat
`
$3
`typescript
// Game Session Response
interface GameSessionResponse {
sessionId: string;
campaignId: string;
gameId: string;
status: string;
campaign: CampaignInfo;
player: PlayerInfo;
createdAt: string;
expiresAt?: string;
}
// Progress Update Response
interface ProgressUpdateResponse {
isValid: boolean;
validationMessage?: string;
currentRank: number;
isLeading: boolean;
campaignStatus?: CampaignStatusInfo;
warnings?: string[];
}
// Game Completion Response
interface GameCompletionResponse {
isWinner: boolean;
prizeAmount?: number;
prizeType?: string;
finalRank: number;
totalParticipants: number;
winnerDetails?: WinnerInfo;
reward?: RewardInfo;
campaignResult?: CampaignResultInfo;
}
// Campaign Status Response
interface CampaignStatusResponse {
campaignId: string;
status: string;
campaignStyle: string;
remainingGamepasses: number;
totalParticipants: number;
totalPrizePool: number;
endDate?: string;
playerStatus?: PlayerStatusInfo;
topPlayers?: TopPlayer[];
prizeBreakdown?: PrizeBreakdown;
}
// Leaderboard Response
interface LeaderboardResponse {
campaignId: string;
entries: LeaderboardEntry[];
playerRank?: PlayerRankInfo;
lastUpdated: string;
isLive: boolean;
}
// Validation Response
interface ValidationResponse {
isValid: boolean;
confidenceScore: number;
validationIssues: string[];
warnings: string[];
requiresRevalidation: boolean;
validatedAt: string;
}
`
$3
`typescript
import { canonicalStringify, sha256Hex } from "playe-developer-sdk";
// Canonical JSON stringification (deterministic)
const canonical = canonicalStringify({ b: 1, a: 2 }); // '{"a":2,"b":1}'
// SHA-256 hashing
const hash = await sha256Hex("data to hash");
`
$3
`typescript
import { DeviceUtils } from "@workspace/playe-developer-sdk";
// Get device information
const deviceInfo = DeviceUtils.getDeviceInfo();
// Get geolocation
const location = await DeviceUtils.getGeolocationData();
// Generate fingerprint
const fingerprint = DeviceUtils.generateFingerprint();
// Check browser support
const isSupported = DeviceUtils.isBrowser();
const features = DeviceUtils.getFeatureSupport();
`
$3
`typescript
import {
PlayeSDKError,
ValidationError,
NetworkError,
AuthenticationError,
GameSessionError,
} from "@workspace/playe-developer-sdk";
try {
await sdk.initializeGameSession(params);
} catch (error) {
if (error instanceof ValidationError) {
console.error("Validation failed:", error.message);
} else if (error instanceof NetworkError) {
console.error("Network error:", error.message);
} else if (error instanceof AuthenticationError) {
console.error("Authentication failed:", error.message);
} else if (error instanceof PlayeSDKError) {
console.error("SDK error:", error.toJSON());
}
}
`
๐ Security & Integrity
The SDK includes built-in integrity verification to prevent cheating and ensure fair play:
$3
- Session Integrity: Each game session includes a unique session token and salt
- Game State Hashing: Game states are automatically hashed using SHA-256 with session salt
- Integrity Headers: All authenticated requests include cryptographic integrity headers
- Retry Logic: Failed requests due to integrity issues are automatically retried with fresh headers
$3
1. Session Initialization: SDK receives session token and salt from server
2. State Hashing: Game states are canonicalized and hashed with session salt
3. Request Signing: Integrity headers are built with timestamp, nonce, and session token
4. Server Validation: Server verifies hashes and headers to detect tampering
$3
`typescript
// Manually validate game session
const validation = await sdk.validateGameSession({
clientChecksum: "calculated-checksum",
stateSnapshot: currentGameState,
timingData: { avgResponseTime: 250 },
behaviorMetrics: { clicksPerSecond: 5.2 },
});
if (!validation.isValid) {
console.log("Validation issues:", validation.validationIssues);
}
`
๐งช Testing & Development
$3
`typescript
// Create a test game session for development
const testSession = await sdk.createTestGameSession({
testConfig: {
mockCampaign: true,
mockPlayers: 10,
testScenario: "leaderboard",
},
});
console.log("Test session created:", testSession.testSessionId);
`
$3
Enable debug mode to see detailed logging:
`typescript
const sdk = createPlayeSDK({
apiBaseUrl: "https://api.playe.com",
enableDebugMode: true, // This will log all API calls, integrity operations, and responses
});
`
$3
For initializeGameSession() to work, page URL must include a sessionId query parameter:
`
https://yourgame.com/play?sessionId=abc123-def456-ghi789
`
The SDK will automatically extract this sessionId and initialize session.
๐ Examples
$3
The examples/browser-example.html provides a complete integration example with:
- SDK initialization and configuration
- Session management (initialize, start, update, complete)
- Progress tracking with integrity verification
- Leaderboard fetching and display
- Error handling and recovery
- Debug mode logging
- Device fingerprinting
$3
The examples/flappy-bird.html provides a complete game integration example with:
- Player eligibility validation (attempts remaining, campaign status)
- Game session initialization with SDK
- Real-time progress tracking
- Score submission with completion data
- Graceful fallback to demo mode if SDK unavailable
- Responsive game canvas with mobile support
๐ Migration Guide
$3
#### Breaking Changes
1. SDK Initialization
`typescript
// v0.x
import { PlayeDeveloperSDK } from 'playe-developer-sdk';
const sdk = new PlayeDeveloperSDK(config);
// v1.x
import { createPlayeSDK } from 'playe-developer-sdk';
const sdk = createPlayeSDK(config);
`
2. Method Signatures
`typescript
// v0.x - Callback-based
sdk.initializeGameSession((error, session) => {
if (error) handleError(error);
else handleSuccess(session);
});
// v1.x - Promise-based
try {
const session = await sdk.initializeGameSession();
handleSuccess(session);
} catch (error) {
handleError(error);
}
`
๐จ Error Handling
$3
`typescript
// Base SDK error
PlayeSDKError {
name: string;
message: string;
originalError?: Error;
context?: string;
timestamp: string;
}
// Specific error types
ValidationError extends PlayeSDKError; // Validation failures
NetworkError extends PlayeSDKError; // Network issues
AuthenticationError extends PlayeSDKError; // Authentication failures
GameSessionError extends PlayeSDKError; // Session-specific errors
`
$3
`typescript
// Enable debug mode for detailed error information
const sdk = createPlayeSDK({
apiBaseUrl: 'https://api.playe.com',
enableDebugMode: true,
retryAttempts: 3, // Configure retry behavior
timeoutMs: 30000, // Configure timeout
});
`
๐ง Troubleshooting
$3
#### "No sessionId found in URL" Error
Problem: Getting an error when calling initializeGameSession().
Solution: Ensure your game URL includes a sessionId query parameter:
`
https://yourgame.com/play?sessionId=abc123-def456-ghi789
`
#### Network/Timeout Errors
Problem: API calls failing with network errors.
Solutions:
1. Check API endpoint configuration
2. Verify API key is correct
3. Check network connectivity
4. Increase timeout for slow networks
#### Integrity Validation Failures
Problem: Game completion failing with integrity validation errors.
Solutions:
1. Ensure game state is valid and serializable
2. Check timing data is reasonable
3. Use debug mode to inspect requests
๐ค Contributing
We welcome contributions to the Playe Developer SDK!
$3
`bash
Clone repository
git clone https://github.com/playe/playe.git
cd playe
Install dependencies
pnpm install
Build SDK
pnpm --filter playe-developer-sdk build
Run tests
pnpm --filter playe-developer-sdk test
``