@evup/game-sdk
v1.0.13
Published
Official SDK for integrating EvUp game configuration service
Maintainers
Readme
@evup/game-sdk
Official TypeScript SDK for integrating with EvUp game configuration service. This SDK provides type-safe access to game configurations, custom fields, and app settings from your EvUp dashboard.
🚀 Features
- Type-safe: Full TypeScript support with complete type definitions
- Lightweight: Built with modern tooling (UnJS) for minimal bundle size
- Auto-injection: Vite plugin automatically injects config at build time
- Caching: Intelligent caching to reduce API calls
- Error handling: Comprehensive error types for better debugging
- Flexible: Support for nested configuration values and custom fields
- Framework-specific: Optimized hooks for React, Vue, and Svelte
- CLI Support: Quick project setup with @evup/game-cli
📦 Installation
npm install @evup/game-sdkyarn add @evup/game-sdkpnpm add @evup/game-sdkFramework Dependencies
For framework-specific features, install the corresponding framework:
# For React hooks
npm install react
# For Vue composables
npm install vue
# For Svelte stores
npm install svelteFramework Imports
Each framework has its own optimized entry point:
// Vanilla JavaScript/TypeScript
import { EvUpGameSDK } from '@evup/game-sdk'
// React hooks
import { useEvUpGameSDK, useGameConfig } from '@evup/game-sdk/react'
// Vue composables
import { useEvUpGameSDK, useGameConfig } from '@evup/game-sdk/vue'
// Svelte stores
import { createEvUpGameSDK, createGameConfigStore } from '@evup/game-sdk/svelte'🛠️ Quick Start
Method 1: Use CLI (Recommended)
npx @evup/game-cli create my-game
cd my-game
npm run devThe CLI automatically sets up the Vite plugin with auto-injection. Your game configuration will be available instantly:
import { useEvUpGame } from '@evup/game-sdk/react'
function Game() {
// Config is auto-injected - no manual SDK setup needed!
const { loading, error, appConfig, viewportConfig, customConfig } = useEvUpGame()
return (
<div>
<h1>{appConfig?.name}</h1>
<p>{appConfig?.description}</p>
</div>
)
}Method 2: Manual Setup with Vite Plugin
- Install the SDK:
npm install @evup/game-sdk- Configure Vite plugin:
// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import { vitePlugin as evUpPlugin } from '@evup/game-sdk/vite-plugin'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
plugins: [
evUpPlugin({
gameId: env.VITE_EVUP_GAME_ID || 'your-game-id',
apiKey: env.VITE_EVUP_API_KEY || ''
})
]
}
})- Use framework hooks:
// React, Vue, or Svelte - config is auto-injected
const { loading, error, appConfig, customConfig } = useEvUpGame()Method 3: Manual SDK Initialization
import { EvUpGameSDK } from '@evup/game-sdk'
const sdk = new EvUpGameSDK({
baseUrl: 'https://evup.vn',
apiKey: 'gep_your_api_key_here',
gameId: 'your_game_id',
version: 'latest', // optional, defaults to 'latest'
debug: false // optional, enables debug logging
})
// Get complete configuration
const config = await sdk.getConfig()
// Get only app configuration
const appConfig = await sdk.getAppConfig()
// Get custom configuration
const customConfig = await sdk.getCustomConfig()
// Get a specific custom value
const primaryColor = await sdk.getCustomValue('colors.primary', '#000000')📋 API Reference
Constructor Options
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| baseUrl | string | ✅ | - | EvUp server URL (e.g., https://evup.vn) |
| apiKey | string | ✅ | - | Game API key from EvUp dashboard |
| gameId | string | ✅ | - | Game ID from EvUp dashboard |
| version | string | ❌ | 'latest' | Config version to fetch |
| timeout | number | ❌ | 10000 | Request timeout in milliseconds |
| debug | boolean | ❌ | false | Enable debug logging |
Core Methods
| Method | Return Type | Description |
|--------|-------------|-------------|
| getConfig(force?) | Promise<GameConfig> | Get complete game configuration |
| getAppConfig(force?) | Promise<GameAppConfig> | Get application configuration |
| getCustomConfig(force?) | Promise<CustomConfig> | Get custom configuration |
| getCustomData(force?) | Promise<Record<string, any>> | Get custom field data |
| getCustomValue<T>(key, default?, force?) | Promise<T> | Get specific custom value |
| getViewportConfig(force?) | Promise<GameViewportConfig> | Get viewport configuration |
Utility Methods
| Method | Return Type | Description |
|--------|-------------|-------------|
| hasCustomField(key, force?) | Promise<boolean> | Check if custom field exists |
| getCustomFieldKeys(force?) | Promise<string[]> | Get all custom field keys |
| clearCache() | void | Clear cached configuration |
| isCached() | boolean | Check if config is cached |
| getSDKInfo() | object | Get SDK version and info |
Configuration Types
| Type | Description |
|------|-------------|
| GameConfig | Complete game configuration object |
| GameAppConfig | Application configuration (name, description, keywords) |
| GameViewportConfig | Viewport settings (width, height) |
| CustomConfig | Custom fields schema and data |
| CustomFieldSchema | Individual field schema definition |
Error Types
| Error | Code | Description |
|-------|------|-------------|
| EvUpSDKError | INVALID_OPTIONS | Invalid initialization options |
| EvUpAuthError | AUTH_ERROR | Invalid API key or unauthorized |
| EvUpNetworkError | NETWORK_ERROR | Network request failed |
| EvUpConfigNotFoundError | CONFIG_NOT_FOUND | Configuration not found |
🔌 Vite Plugin
Plugin Configuration
import { vitePlugin as evUpPlugin } from '@evup/game-sdk/vite-plugin'
export default defineConfig({
plugins: [
evUpPlugin({
gameId: 'your-game-id', // Required: Your game ID
apiKey: 'your-api-key', // Required: Your API key
baseUrl: 'https://evup.vn', // Optional: Default server URL
version: 'latest', // Optional: Config version
debug: false // Optional: Enable debug logging
})
]
})Auto-injection
The Vite plugin automatically injects configuration constants at build time:
__EVUP_GAME_ID__- Your game ID__EVUP_API_KEY__- Your API key__EVUP_BASE_URL__- Server base URL
These constants are used by framework hooks when no manual configuration is provided.
💡 Usage Examples
Basic Configuration Access
import { EvUpGameSDK } from '@evup/game-sdk'
const sdk = new EvUpGameSDK({
baseUrl: 'https://evup.vn',
apiKey: 'gep_your_api_key',
gameId: 'your_game_id'
})
// Get app information
const app = await sdk.getAppConfig()
console.log(`Game: ${app.name}`)
console.log(`Description: ${app.description}`)
// Get viewport settings
const viewport = await sdk.getViewportConfig()
console.log(`Size: ${viewport.width}x${viewport.height}`)Working with Custom Fields
// Get theme configuration
const theme = await sdk.getCustomValue('theme', 'light')
// Get nested color values
const primaryColor = await sdk.getCustomValue('colors.primary', '#007bff')
const secondaryColor = await sdk.getCustomValue('colors.secondary', '#6c757d')
// Get game settings
const maxPlayers = await sdk.getCustomValue('game.maxPlayers', 4)
const difficulty = await sdk.getCustomValue('game.difficulty', 'normal')
// Check if features are enabled
const hasMultiplayer = await sdk.getCustomValue('features.multiplayer', false)
const hasAudio = await sdk.getCustomValue('features.audio', true)Error Handling
import {
EvUpGameSDK,
EvUpAuthError,
EvUpNetworkError,
EvUpConfigNotFoundError
} from '@evup/game-sdk'
try {
const config = await sdk.getConfig()
// Use configuration...
} catch (error) {
if (error instanceof EvUpAuthError) {
console.error('Authentication failed:', error.message)
// Handle invalid API key
} else if (error instanceof EvUpNetworkError) {
console.error('Network error:', error.message)
// Handle connection issues
} else if (error instanceof EvUpConfigNotFoundError) {
console.error('Config not found:', error.message)
// Handle missing configuration
} else {
console.error('Unknown error:', error.message)
}
}Caching and Performance
// Force refresh (bypass cache)
const freshConfig = await sdk.getConfig(true)
// Check cache status
if (sdk.isCached()) {
console.log('Using cached configuration')
} else {
console.log('Will fetch from server')
}
// Clear cache manually
sdk.clearCache()
// Get SDK information
const info = sdk.getSDKInfo()
console.log('SDK Version:', info.version)
console.log('Last fetch:', info.lastFetchTime)Framework Integration
The SDK includes built-in integrations for React, Vue, and Svelte with optimized hooks, composables, and stores.
React Hooks
import {
useEvUpGameSDK,
useGameConfig,
useCustomValue,
useEvUpGame
} from '@evup/game-sdk/react'
function GameComponent() {
// Initialize SDK
const sdk = useEvUpGameSDK({
baseUrl: 'https://evup.vn',
apiKey: 'gep_your_api_key',
gameId: 'your_game_id'
})
// Get game configuration
const { config, loading, error, refetch } = useGameConfig(sdk)
// Get custom values with type safety
const { value: theme } = useCustomValue<string>(sdk, 'theme', 'light')
const { value: maxPlayers } = useCustomValue<number>(sdk, 'game.maxPlayers', 4)
// Combined hook for all game data (auto-injection recommended)
const { appConfig, viewportConfig, customConfig } = useEvUpGame()
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
return (
<div>
<h1>{appConfig?.name}</h1>
<p>Theme: {theme}</p>
<p>Max Players: {maxPlayers}</p>
</div>
)
}Vue Composables
<script setup lang="ts">
import {
useEvUpGameSDK,
useGameConfig,
useCustomValue,
useEvUpGame
} from '@evup/game-sdk/vue'
// Initialize SDK
const { sdk } = useEvUpGameSDK({
baseUrl: 'https://evup.vn',
apiKey: 'gep_your_api_key',
gameId: 'your_game_id'
})
// Get game configuration
const { config, loading, error, refetch } = useGameConfig(sdk)
// Get custom values
const { value: theme } = useCustomValue<string>(sdk, 'theme', 'light')
const { value: maxPlayers } = useCustomValue<number>(sdk, 'game.maxPlayers', 4)
// Combined composable (auto-injection recommended)
const gameData = useEvUpGame()
</script>
<template>
<div v-if="loading">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<div v-else>
<h1>{{ gameData.appConfig?.name }}</h1>
<p>Theme: {{ theme }}</p>
<p>Max Players: {{ maxPlayers }}</p>
<button @click="refetch()">Refresh</button>
</div>
</template>Svelte Stores
<script lang="ts">
import {
createEvUpGameSDK,
createGameConfigStore,
createCustomValueStore,
createEvUpGameStore
} from '@evup/game-sdk/svelte'
// Create SDK store
const sdkStore = createEvUpGameSDK({
baseUrl: 'https://evup.vn',
apiKey: 'gep_your_api_key',
gameId: 'your_game_id'
})
// Create individual stores
const configStore = createGameConfigStore(sdkStore)
const themeStore = createCustomValueStore(sdkStore, 'theme', 'light')
// Or use combined store (auto-injection recommended)
const gameStore = createEvUpGameStore()
// Access reactive values
$: config = $gameStore.config
$: loading = $gameStore.loading
$: error = $gameStore.error
</script>
{#if $loading}
<div>Loading...</div>
{:else if $error}
<div>Error: {$error.message}</div>
{:else}
<div>
<h1>{$gameStore.appConfig?.name}</h1>
<p>Theme: {$themeStore.value}</p>
<button on:click={() => gameStore.refetchAll()}>Refresh All</button>
</div>
{/if}🔧 Advanced Configuration
Custom Validation
import { validateCustomConfig } from '@evup/game-sdk'
const config = await sdk.getConfig()
const validation = validateCustomConfig(config)
if (!validation.valid) {
console.error('Configuration validation failed:')
validation.errors.forEach(({ field, error }) => {
console.error(`- ${field}: ${error}`)
})
}Configuration Merging
import { mergeConfigs } from '@evup/game-sdk'
const defaultSettings = {
theme: 'light',
colors: { primary: '#007bff', secondary: '#6c757d' },
features: { audio: true, multiplayer: false }
}
const customData = await sdk.getCustomData()
const finalSettings = mergeConfigs(defaultSettings, customData)🛡️ Best Practices
1. Use Auto-injection (Recommended)
// Configure once in vite.config.ts
export default defineConfig({
plugins: [
evUpPlugin({
gameId: env.VITE_EVUP_GAME_ID,
apiKey: env.VITE_EVUP_API_KEY
})
]
})
// Use anywhere in your app without setup
const { appConfig, customConfig } = useEvUpGame()2. Manual Configuration (Advanced)
// Only when you need custom SDK instances
const sdk = new EvUpGameSDK({
baseUrl: process.env.VITE_EVUP_BASE_URL || 'https://evup.vn',
apiKey: process.env.VITE_EVUP_API_KEY!,
gameId: process.env.VITE_EVUP_GAME_ID!,
debug: process.env.NODE_ENV === 'development'
})3. Error Boundaries
// Always wrap SDK calls in try-catch blocks
async function getGameTheme() {
try {
return await sdk.getCustomValue('theme', 'light')
} catch (error) {
console.error('Failed to get theme:', error)
return 'light' // fallback
}
}4. Type Safety
// Use generic types for better type safety
interface GameSettings {
maxPlayers: number
difficulty: 'easy' | 'normal' | 'hard'
enablePowerUps: boolean
}
const settings = await sdk.getCustomValue<GameSettings>('gameSettings', {
maxPlayers: 4,
difficulty: 'normal',
enablePowerUps: true
})🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
MIT License - see LICENSE for details.
🆘 Support
- 📧 Email: [email protected]
- 🌐 Website: https://evup.vn
- 📖 Documentation: https://docs.evup.vn
- 🐛 Issues: GitHub Issues
Made with ❤️ by the EvUp Team
