A comprehensive TypeScript wrapper for the PUBG API with full type safety, rate limiting, error handling, and caching.
- 🔒 Full TypeScript support with comprehensive type definitions
- 🚦 Built-in rate limiting (10 requests per minute by default)
- 🛡️ Comprehensive error handling with custom error types
- 🔄 Automatic retries for failed requests
- 💾 Client-local response caching with TTL and size limits
- 📡 All PUBG API endpoints supported
- 🎯 Easy-to-use service-based architecture
- 🐛 Debug logging with multiple namespaces
- ⚡ Performance monitoring with timing utilities
- ❤️ Synchronous Client Health derived from real request outcomes
- 📦 Local-only Asset Catalog with generated image URLs
npm install @j03fr0st/pubg-tsUpgrading from v1? See MIGRATION.md for the breaking interface changes.
import { PubgClient } from '@j03fr0st/pubg-ts';
const client = new PubgClient({
apiKey: 'your-api-key',
shard: 'pc-na'
});
// Get player by name
const player = await client.players.getPlayerByName('playerName');
// Get match details
const match = await client.matches.getMatch('match-id');
// Get current season
const season = await client.seasons.getCurrentSeason();// Get players by name
const players = await client.players.getPlayers({
playerNames: ['player1', 'player2']
});
// Get player by ID
const player = await client.players.getPlayerById('player-id');
// Get player season stats
const stats = await client.players.getPlayerSeasonStats({
playerId: 'player-id',
seasonId: 'season-id'
});// Get match details
const match = await client.matches.getMatch('match-id');
// Get matches with filters
const matches = await client.matches.getMatches({
filter: {
createdAt: {
start: '2023-01-01T00:00:00Z',
end: '2023-01-31T23:59:59Z'
}
}
});// Get all seasons
const seasons = await client.seasons.getSeasons();
// Get current season
const currentSeason = await client.seasons.getCurrentSeason();// Get leaderboard
const leaderboard = await client.leaderboards.getLeaderboard({
seasonId: 'season-id',
gameMode: 'squad'
});// Get telemetry data from a match
const telemetry = await client.matches.getTelemetry(matchId);AssetCatalog always reads bundled local data synchronously. assetBaseUrl only controls the
image URLs generated by the catalog.
import { AssetCatalog, ItemId, VehicleId } from '@j03fr0st/pubg-ts';
// Every client owns a local catalog.
const itemId: ItemId = 'Item_Weapon_AK47_C';
const itemName = client.assets.getItemName(itemId); // "AKM"
const itemInfo = client.assets.getItemInfo(itemId);
// Enhanced search and filtering
const weapons = client.assets.getItemsByCategory('weapon');
const searchResults = client.assets.searchItems('AK');
// Vehicle information with type safety
const vehicleId: VehicleId = 'BP_Motorbike_04_C';
const vehicleName = client.assets.getVehicleName(vehicleId);
const vehicleInfo = client.assets.getVehicleInfo(vehicleId);
// Map data with comprehensive coverage
const allMaps = client.assets.getAllMaps();
const mapName = client.assets.getMapName('Baltic_Main');
// Season data by platform; Season Activity is read from the bundled dates at call time
const pcSeasons = client.assets.getSeasonsByPlatform('PC');
const activeSeason = client.assets.getActiveSeason('PC');
// Survival titles with rating ranges
const title = client.assets.getSurvivalTitle(1500);
// Asset statistics and insights
const stats = client.assets.getAssetStats();
console.log(`Total items: ${stats.totalItems}`);
// Standalone catalogs use the same local data and can customize generated image URLs.
const assets = new AssetCatalog({ assetBaseUrl: 'https://cdn.example.com/pubg' });
const weaponIconUrl = assets.getWeaponAssetUrl('Item_Weapon_AK47_C', 'icon');Each client caches eligible API responses locally:
const health = client.getHealth();
console.log(
`Cache: ${health.responseCache.size}/${health.responseCache.maxSize} entries`
);
// Clear cache manually
client.clearResponseCache();Enable debug logging by setting the DEBUG environment variable:
# Enable all debug logs
DEBUG=pubg-ts:* node your-app.js
# Enable specific component logs
DEBUG=pubg-ts:http,pubg-ts:cache node your-app.jsAvailable debug namespaces:
pubg-ts:http- HTTP requests, timing, and retriespubg-ts:cache- Cache hits, misses, and operationspubg-ts:client- Client initialization and configuration
Inspect the last-known rate-limit state through Client Health:
const health = client.getHealth();
console.log(`Remaining requests: ${health.rateLimit.remaining}`);
console.log(`Reset time: ${health.rateLimit.resetAt ?? 'not observed'}`);import {
PubgApiError,
PubgRateLimitError,
PubgAuthenticationError
} from '@j03fr0st/pubg-ts';
try {
const player = await client.players.getPlayerByName('nonexistent');
} catch (error) {
if (error instanceof PubgRateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof PubgAuthenticationError) {
console.log('Invalid API key');
}
}const client = new PubgClient({
apiKey: 'your-api-key',
shard: 'pc-na',
baseUrl: 'https://api.pubg.com', // optional
assetBaseUrl: 'https://cdn.example.com/pubg', // optional, generated asset URLs only
timeout: 10000, // optional, default 10s
retryAttempts: 3, // optional, default 0 (no retries); only transient 5xx responses are retried
retryDelay: 1000 // optional, default 1s, doubled on each retry
});Check out the examples directory for comprehensive usage examples:
basic-usage.ts- Simple API usageadvanced-usage.ts- Advanced features and error handlingasset-usage.ts- Local Asset Catalog: typed IDs, search, seasons, image URLsdamage-info-usage.ts- Working with Match Telemetry damage data
This project uses Biome for fast, reliable linting and formatting:
# Format all files
npm run format
# Lint code
npm run lint
# Fix linting issues
npm run lint:fix
# Check and fix both formatting and linting
npm run check:fixThe checked-in JSON under src/assets/ is the Asset Catalog's only source of truth; building does
not fetch or synchronize remote asset data. The identifier types under src/types/assets/ are
generated from that JSON — after editing any bundled JSON, run:
npm run generate:asset-types
npm run check:asset-types # verify generated types without writing files (also runs in CI)# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchThis project uses Lefthook for pre-commit validation:
- Automatic code formatting with Biome
- Linting and type checking
- Running tests for changed files
The hooks run automatically on git commit. To bypass (not recommended):
git commit --no-verifyThe project includes:
- EditorConfig (.editorconfig) for consistent formatting across editors
- VS Code settings (.vscode/) with recommended extensions and settings
- Biome integration for automatic formatting on save
Recommended VS Code extensions:
- EditorConfig for VS Code
- Biome
- Indentation: 2 spaces
- Quotes: Single quotes for strings
- Line endings: LF (Unix)
- Line length: 100 characters
- Trailing commas: ES5 style
- Import organization: Automatic sorting and grouping
Please read CONTRIBUTING.md for details on our development process and how to submit pull requests.
Please see SECURITY.md for information about reporting security vulnerabilities.
This project is licensed under the MIT License - see the LICENSE file for details.
This is an open source project and anyone is free to:
- Use this software for any purpose
- Modify and distribute the software
- Include it in other projects (commercial or non-commercial)
- Contribute improvements back to the project
The MIT License is one of the most permissive open source licenses, placing minimal restrictions on reuse.