codebrag
Version:
CLI tool for tracking Claude Code usage and leaderboard participation
66 lines (51 loc) • 2.5 kB
JavaScript
import chalk from 'chalk';
import { checkAuthStatus } from '../utils/config.js';
import { authenticatedFetch } from '../utils/api.js';
export async function statsCommand() {
console.log(chalk.blue('📊 Your Usage Statistics'));
console.log(chalk.gray('━'.repeat(30)));
const authStatus = await checkAuthStatus();
if (!authStatus.isAuthenticated) {
console.log(chalk.yellow('⚠️ You need to authenticate first'));
console.log(chalk.gray('Run'), chalk.cyan('codebrag auth'), chalk.gray('to get started'));
return;
}
try {
// Fetch user stats from API with automatic token refresh
const response = await authenticatedFetch(`/api/user/stats?twitter_user_id=${authStatus.twitterUserId}`);
if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
console.log(chalk.yellow(`📊 @${authStatus.twitterHandle}'s Claude Code Stats`));
console.log(chalk.gray('━'.repeat(30)));
// Calculate cost estimate
const costEstimate = (data.stats.total_tokens / 1_000_000) * 2.50;
console.log(`💰 Total Cost: ${chalk.green(`$${costEstimate.toFixed(2)}`)}`);
console.log(`📈 This Month: ${chalk.cyan(`$${((data.stats.monthly_tokens / 1_000_000) * 2.50).toFixed(2)}`)} `);
console.log(`🏆 Rank: ${chalk.yellow(`#${data.user.rank}`)} of ${data.user.total_users}`);
} catch (error) {
// Check if it's an authentication error
if (error.message.includes('401') || error.message.includes('Unauthorized')) {
console.log(chalk.yellow('🔄 Your session has expired'));
console.log(chalk.yellow('🐦 Let\'s reconnect your Twitter account...'));
console.log();
// Run re-authentication
const { authCommand } = await import('./auth.js');
await authCommand();
// Retry stats after re-auth
console.log();
console.log(chalk.blue('📊 Fetching your stats...'));
await statsCommand();
return;
}
console.error(chalk.red('❌ Error fetching stats:'), error.message);
if (error.message.includes('API error')) {
console.log(chalk.yellow('🔧 Common solutions:'));
console.log(chalk.gray('• Check if the backend server is running'));
console.log(chalk.gray('• Verify your internet connection'));
console.log(chalk.gray('• Try running the command again'));
}
throw error;
}
}