
Security News
Node.js Homepage Adds Paid Support Link, Prompting Contributor Pushback
A new Node.js homepage button linking to paid support for EOL versions has sparked a heated discussion among contributors and the wider community.
@playcademy/sdk
Advanced tools
Official TypeScript SDK for the Playcademy platform
The Playcademy SDK provides a comprehensive, type-safe interface for building games on the Playcademy platform. It handles authentication, game sessions, user data, inventory management, and all platform APIs through a unified client interface.
The SDK serves as the primary interface between your game and the Playcademy platform, providing:
Install the SDK using your preferred package manager:
# Using Bun (recommended)
bun add @playcademy/sdk
# Using npm
npm install @playcademy/sdk
# Using yarn
yarn add @playcademy/sdk
# Using pnpm
pnpm add @playcademy/sdk
For most game development scenarios, use automatic initialization:
import { PlaycademyClient } from '@playcademy/sdk'
async function initializeGame() {
try {
// Automatic initialization - detects environment and configures appropriately
const client = await PlaycademyClient.init()
// Get current user
const user = await client.users.me()
console.log('Welcome,', user.name)
// The client is ready for all platform operations
return client
} catch (error) {
console.error('Failed to initialize Playcademy SDK:', error)
throw error
}
}
The SDK automatically detects and configures for different environments:
@playcademy/vite-plugin
)// Automatic session management when gameId is available
const client = await PlaycademyClient.init()
// Save transient game state (position, health, temporary data)
await client.games.saveState({
currentLevel: 'forest_glade',
playerPosition: { x: 100, y: 200 },
health: 85,
activePowerUps: ['speed_boost'],
})
// Load previously saved state
const gameState = await client.games.loadState()
console.log('Loaded state:', gameState)
// Exit game (automatically ends session if managed)
await client.runtime.exit()
// Get user information
const user = await client.users.me()
// Inventory operations (accepts UUIDs or slugs)
const inventory = await client.users.inventory.get()
await client.users.inventory.add('magic-sword', 1)
await client.users.inventory.remove('health-potion', 1)
// Check item quantities and ownership
const goldCount = await client.users.inventory.quantity('gold-coin')
const hasKey = await client.users.inventory.has('dungeon-key')
const hasEnoughGold = await client.users.inventory.has('gold-coin', 100)
// Platform currency management
const balance = await client.credits.balance()
await client.credits.add(100)
await client.credits.spend(50)
// Check affordability
if ((await client.credits.balance()) >= 100) {
await client.credits.spend(100)
console.log('Purchase successful!')
}
// Level management
const userLevel = await client.levels.get()
const progress = await client.levels.progress()
console.log(`Level ${userLevel.currentLevel}, ${progress.xpToNextLevel} XP to next level`)
// Add experience points
const result = await client.levels.addXP(100)
if (result.leveledUp) {
console.log(`Level up! ${result.oldLevel} → ${result.newLevel}`)
console.log('Credits awarded:', result.creditsAwarded)
}
client.auth
)logout()
: Logs out user and clears authentication tokenclient.users
)me()
: Get current user informationclient.users.inventory
):
get()
: Get user's inventoryadd(identifier, quantity)
: Add items to inventoryremove(identifier, quantity)
: Remove items from inventoryquantity(identifier)
: Get item quantityhas(identifier, minQuantity?)
: Check item ownershipclient.games
)list()
: Get all available gamesfetch(gameIdOrSlug)
: Get specific game detailssaveState(state)
: Save transient game stateloadState()
: Load saved game statestartSession(gameId?)
: Start game sessionendSession(sessionId, gameId?)
: End game sessionclient.credits
)balance()
: Get current credits balanceadd(amount)
: Add credits to userspend(amount)
: Spend user creditsclient.levels
)get()
: Get current user level informationprogress()
: Get level progress and XP to next leveladdXP(amount)
: Add experience pointsclient.levels.config
):
list()
: Get all level configurationsget(level)
: Get specific level configurationclient.maps
)elements(mapId)
: Get map elements and points of interestclient.runtime
)getGameToken(gameId, options?)
: Get game-specific authentication tokenexit()
: Signal platform to exit game viewclient.leaderboard
) - Game-specificfetch(options?)
: Get leaderboard for a specific game
options.timeframe
: Filter by time period ('all_time'
, 'monthly'
, 'weekly'
, 'daily'
)options.gameId
: Game ID to fetch leaderboard for (required)options.limit
: Number of entries to return (default: 10)options.offset
: Pagination offset (default: 0)client.scores
) - Platform-widesubmit(gameId, score, metadata?)
: Submit a score for any gamegetUserScores(userId, options?)
: Get all scores for a user
options.gameId
: Filter by specific game (optional)options.limit
: Number of scores to return (default: 50)client.dev.auth
)applyForDeveloper()
: Apply for developer statusgetDeveloperStatus()
: Check current developer statusclient.dev.games
)upsert(slug, metadata, gameFile)
: Create or update gameupdate(gameId, updates)
: Update game propertiesdelete(gameId)
: Delete gameclient.dev.keys
)createKey(gameId, name)
: Create API key for server authenticationlistKeys()
: List all API keysrevokeKey(keyId)
: Revoke API keyclient.dev.items
)list(gameId)
: List all items for a gameget(gameId, slug)
: Get specific itemcreate(gameId, slug, data)
: Create new game itemupdate(gameId, itemId, updates)
: Update existing itemdelete(gameId, itemId)
: Delete itemThe SDK provides real-time event notifications for important platform changes:
// Authentication changes
client.on('authChange', payload => {
console.log('Authentication changed:', payload.token)
})
// Inventory changes
client.on('inventoryChange', payload => {
console.log(`Item ${payload.itemId}: ${payload.delta} (total: ${payload.newTotal})`)
})
// Experience gained
client.on('xpGained', payload => {
console.log(`Gained ${payload.amount} XP (total: ${payload.totalXP})`)
})
// Level up notifications
client.on('levelUp', payload => {
console.log(`Level up! ${payload.oldLevel} → ${payload.newLevel}`)
console.log('Credits awarded:', payload.creditsAwarded)
})
// Update UI in response to platform events
client.on('inventoryChange', payload => {
updateInventoryDisplay(payload.itemId, payload.newTotal)
})
client.on('levelUp', payload => {
showLevelUpAnimation(payload.newLevel)
showCreditsAwarded(payload.creditsAwarded)
})
client.on('xpGained', payload => {
updateXPBar(payload.totalXP, payload.leveledUp)
})
For server-side applications or custom environments:
import { PlaycademyClient } from '@playcademy/sdk'
import type { LoginResponse } from '@playcademy/sdk'
// Step 1: Authenticate
const loginData: LoginResponse = await PlaycademyClient.login(
'https://api.playcademy.com',
'user@example.com',
'password',
)
// Step 2: Initialize client
const client = new PlaycademyClient({
baseUrl: 'https://api.playcademy.com',
token: loginData.token,
gameId: 'your-game-id', // Optional: enables automatic session management
})
const client = new PlaycademyClient({
baseUrl: 'https://api.playcademy.com',
token: 'your-auth-token',
gameId: 'your-game-id',
// Additional options
timeout: 10000, // Request timeout in milliseconds
retries: 3, // Number of retry attempts
})
import { PlaycademyError } from '@playcademy/sdk'
try {
const user = await client.users.me()
// Handle success
} catch (error) {
if (error instanceof PlaycademyError) {
console.error('Playcademy API Error:', error.message)
console.error('Status Code:', error.statusCode)
console.error('Error Code:', error.code)
} else {
console.error('Unexpected error:', error)
}
}
When using the official Playcademy Vite templates, the development environment is automatically configured:
// In your game's main file
import { PlaycademyClient } from '@playcademy/sdk'
// The vite plugin automatically starts the sandbox
const client = await PlaycademyClient.init()
// SDK automatically connects to local sandbox at http://localhost:4321
If not using the Vite plugin, start the sandbox manually:
# Start sandbox server
bunx @playcademy/sandbox --port 4321 --verbose
# In your application
const client = new PlaycademyClient({
baseUrl: 'http://localhost:4321/api',
token: 'dev-token' // Sandbox provides mock authentication
})
PlaycademyClient.init()
games.saveState()
for transient data (current level, position, temporary status)users.inventory
for persistent items and resources that carry between sessions// Mock the SDK for unit tests
import { jest } from '@jest/globals'
// Mock the entire SDK module
jest.mock('@playcademy/sdk', () => ({
PlaycademyClient: {
init: jest.fn().mockResolvedValue({
users: {
me: jest.fn().mockResolvedValue({ id: 'test-user', name: 'Test User' }),
inventory: {
get: jest.fn().mockResolvedValue([]),
add: jest.fn().mockResolvedValue(undefined),
},
},
}),
},
}))
// Test with real sandbox
import { PlaycademyClient } from '@playcademy/sdk'
describe('Playcademy Integration', () => {
let client: PlaycademyClient
beforeAll(async () => {
// Initialize with sandbox
client = new PlaycademyClient({
baseUrl: 'http://localhost:4321/api',
token: 'test-token',
})
})
test('should fetch user data', async () => {
const user = await client.users.me()
expect(user).toBeDefined()
expect(user.name).toEqual(expect.any(String))
})
})
SDK Initialization Timeout
Error: PLAYCADEMY_INIT not received within 5000ms
Authentication Errors
Error: Unauthorized (401)
PlaycademyClient.login()
Network Connection Issues
Error: Failed to fetch
Use these debugging techniques for troubleshooting SDK issues:
// Check initialization process
try {
const client = await PlaycademyClient.init()
console.log('SDK initialized successfully')
} catch (error) {
console.error('SDK initialization failed:', error)
}
// Monitor network requests in browser dev tools (Network tab)
// Check console for SDK error messages
// Verify API responses and error details
The SDK is a critical component of the Playcademy platform ecosystem. When contributing:
For general contribution guidelines, see the monorepo CONTRIBUTING.md.
@playcademy/api-core
: API handlers used by the SDK@playcademy/data
: Database schema and type definitions@playcademy/vite-plugin
: Development environment integration@playcademy/sandbox
: Local development server/templates
for example integrationsFAQs
Unknown package
The npm package @playcademy/sdk receives a total of 145 weekly downloads. As such, @playcademy/sdk popularity was classified as not popular.
We found that @playcademy/sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A new Node.js homepage button linking to paid support for EOL versions has sparked a heated discussion among contributors and the wider community.
Research
North Korean threat actors linked to the Contagious Interview campaign return with 35 new malicious npm packages using a stealthy multi-stage malware loader.
Research
Security News
The Socket Research Team investigates a malicious Python typosquat of a popular password library that forces Windows shutdowns when input is incorrect.