### Create Report Command Example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md This example illustrates the behavior of the `cursor-stats.createReport` command. When executed, it shows progress, prompts the user to open a dialog, and automatically copies the report path to the clipboard. ```typescript // User runs command via command palette // Report is created in extension directory // Report path copied to clipboard automatically ``` -------------------------------- ### Log Entry Example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/errors-and-status.md Illustrates the format of log entries, including timestamp, level, category, and message. This format is used for all logged events. ```log [2024-01-15T10:30:45.123Z] [INFO] [Stats] Updated premium requests [2024-01-15T10:30:46.456Z] [ERROR] [API] Error fetching monthly data: 403 Forbidden [2024-01-15T10:30:47.789Z] [INFO] [Notifications] Spending threshold $50 met ``` -------------------------------- ### Check Token Log Entry Format Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/README.md When debugging, look for log entries indicating the start of the database token. This helps verify token handling. ```log [Database] Token starts with: {first 20 chars}... ``` -------------------------------- ### Create and Show Status Bar Item Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Creates a status bar item, sets its text to display usage statistics, and makes it visible. This is the initial setup for the usage display. ```typescript const statusBarItem = createStatusBarItem(); statusBarItem.text = '$(pulse) 125/500 (25%)'; statusBarItem.show(); ``` -------------------------------- ### activate Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Initializes the Cursor Stats extension when VS Code activates it. This function sets up logging, event listeners, command registration, and starts automatic statistics updates. ```APIDOC ## activate ### Description Initializes the extension when VS Code activates it. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method N/A (VS Code internal activation) ### Endpoint N/A ### Request Example ```typescript // Extension activation is automatic when VS Code loads the extension // Registered in package.json activationEvents: ["onStartupFinished"] ``` ### Response #### Success Response N/A (void return type) #### Response Example None ``` -------------------------------- ### Get Progress Bar Settings Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the current progress bar configuration, including bar length and threshold values. ```typescript const settings = getProgressBarSettings(); console.log(`Bar length: ${settings.barLength} characters`); ``` -------------------------------- ### startRefreshInterval Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Starts the automatic stats refresh interval, respecting configuration and avoiding updates during cooldown or when the window is not focused. It calls `updateStats()` periodically. ```APIDOC ## startRefreshInterval(): void ### Description Starts the automatic stats refresh interval. ### Behavior - Respects configured refresh interval (`cursorStats.refreshInterval`). - Skips updates if the system is in cooldown or the window is not focused. - Calls `updateStats()` at regular intervals. ### Configuration - Setting: `cursorStats.refreshInterval` (default: 60 seconds, minimum: 10 seconds) ### Example ```typescript startRefreshInterval(); // Stats will update every 60 seconds ``` ``` -------------------------------- ### TimingInfo Interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Defines the internal structure for timing information within Cursor, including keys, timestamps, and client-side start times. ```typescript interface TimingInfo { key: string; // Timing entry key timestamp: number; // Timestamp in milliseconds timingInfo: { clientStartTime: number; // Client-side start time [key: string]: any; }; } ``` -------------------------------- ### Getters and Setters Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Provides access to and methods for modifying the state of the cooldown utility, including start times, error counts, and refresh intervals. ```APIDOC ## Getters and Setters ### Getters - **getCooldownStartTime()**: Returns the cooldown start timestamp or null if not in cooldown. - **getConsecutiveErrorCount()**: Returns the number of consecutive API errors. - **getRefreshInterval()**: Returns the currently active refresh interval or null. ### Setters - **setCooldownStartTime(time)**: Sets the cooldown start timestamp. - **setConsecutiveErrorCount(count)**: Sets the number of consecutive API errors. - **incrementConsecutiveErrorCount()**: Increments the consecutive error count by one. - **resetConsecutiveErrorCount()**: Resets the consecutive error count to zero. ### Example ```typescript if (getCooldownStartTime()) { console.log('Currently in cooldown'); } resetConsecutiveErrorCount(); ``` ``` -------------------------------- ### Start Cooldown Countdown Display Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Begins a countdown timer in the status bar when the API is rate-limited. The timer updates every second for a duration of 10 minutes. Once the countdown finishes, normal refresh is resumed. Call `setCooldownStartTime` before this function. ```typescript setCooldownStartTime(Date.now()); startCountdownDisplay(); // Status bar shows: "$(warning) API Unavailable 9:59" ``` -------------------------------- ### Initialize Logging Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Sets up the logging system for the extension. Call this early in your extension's activation. ```typescript initializeLogging(context); log('[Initialization] Extension ready'); ``` -------------------------------- ### initializeLogging Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Sets up the logging system for the Cursor Stats extension. It creates a VS Code output channel named 'Cursor Stats' and prepares the logging infrastructure. ```APIDOC ## initializeLogging ### Description Sets up the logging system, creating a VS Code output channel named "Cursor Stats". ### Method `initializeLogging(context: ExtensionContext): void` ### Parameters #### Path Parameters - **context** (`vscode.ExtensionContext`) - Required - Extension context for subscription management ### Request Example ```typescript initializeLogging(context); ``` ``` -------------------------------- ### getStripeSessionUrl Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Gets the Stripe checkout session URL for billing purposes. ```APIDOC ## GET https://cursor.com/api/stripeSession ### Description Gets the Stripe checkout session URL for billing. ### Method GET ### Endpoint https://cursor.com/api/stripeSession ### Parameters #### Query Parameters - **token** (string) - Required - Cursor session token ### Response #### Success Response (200) - **string** - Stripe session URL ``` -------------------------------- ### Get Currency Symbol Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the currency symbol corresponding to a given currency code. ```typescript getCurrencySymbol('EUR'); // Returns "€" getCurrencySymbol('USD'); // Returns "$" getCurrencySymbol('GBP'); // Returns "Β£" ``` -------------------------------- ### Get Current Currency Code Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the user's selected currency code from settings. Defaults to 'USD'. ```typescript const currency = getCurrentCurrency(); console.log(`Display currency: ${currency}`); ``` -------------------------------- ### Minimal Cursor Stats Configuration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md A basic configuration enabling logging and setting the currency. ```json { "cursorStats.enableLogging": false, "cursorStats.currency": "USD" } ``` -------------------------------- ### Get Log History Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves all stored log entries. The logs are returned in an array with the most recent entries first. ```typescript const logs = getLogHistory(); logs.forEach(entry => console.log(entry)); ``` -------------------------------- ### Minimal Overhead Configuration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md A configuration designed to minimize extension overhead by disabling logging, alerts, and status bar colors, and setting a long refresh interval. ```json { "cursorStats.enableLogging": false, "cursorStats.enableAlerts": false, "cursorStats.showProgressBars": false, "cursorStats.refreshInterval": 300, "cursorStats.enableStatusBarColors": false } ``` -------------------------------- ### Complete Cursor Stats Configuration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md A comprehensive configuration including all available settings for detailed control over the extension's behavior, alerts, and appearance. ```json { "cursorStats.enableLogging": true, "cursorStats.enableStatusBarColors": true, "cursorStats.statusBarColorThresholds": [ { "percentage": 95, "color": "#CC0000" }, { "percentage": 0, "color": "#FFFFFF" } ], "cursorStats.enableAlerts": true, "cursorStats.usageAlertThresholds": [25, 50, 75, 100], "cursorStats.spendingAlertThreshold": 5, "cursorStats.refreshInterval": 60, "cursorStats.showTotalRequests": false, "cursorStats.currency": "EUR", "cursorStats.showProgressBars": true, "cursorStats.progressBarLength": 15, "cursorStats.progressBarWarningThreshold": 60, "cursorStats.progressBarCriticalThreshold": 80, "cursorStats.customDatabasePath": "", "cursorStats.excludeWeekends": false, "cursorStats.showDailyRemaining": true, "cursorStats.language": "en", "cursorStats.showChangelogOnUpdate": true } ``` -------------------------------- ### initializeI18n Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Initializes the internationalization system. It loads all language packs, sets the default language from settings, and listens for language changes. ```APIDOC ## initializeI18n() ### Description Initializes the internationalization system. ### Behavior - Loads all language packs from files - Sets language from `cursorStats.language` setting (default: en) - Listens for language changes in settings ### Example ```typescript initializeI18n(); ``` ``` -------------------------------- ### createMarkdownTooltip Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Creates a formatted markdown tooltip with sections for premium requests and usage-based pricing. It supports features like centered headers, progress bars, and period/daily calculations. ```APIDOC ## createMarkdownTooltip ### Description Creates a formatted markdown tooltip with sections for premium requests and usage-based pricing. ### Parameters #### Parameters - **lines** (`string[]`) - Required - Array of tooltip lines to display - **isError** (`boolean`) - Optional - Whether this is an error tooltip (defaults to `false`) - **allLines** (`string[]`) - Optional - All available lines for reference (defaults to `[]`) ### Returns `Promise` - Formatted markdown tooltip ### Features - Centered headers with emojis - Organized sections for different usage types - Progress bars (if enabled in settings) - Period and daily remaining calculations - HTML-based layout for better formatting ### Example ```typescript const tooltipLines = [ 'πŸš€ Premium Fast Requests', 'Requests Used: 125/500', 'Utilized: 25%', 'Period: 15 April - 15 May', 'πŸ’³ Usage-Based Pricing: $25.50' ]; const tooltip = await createMarkdownTooltip(tooltipLines); statusBarItem.tooltip = tooltip; ``` ``` -------------------------------- ### Get Extension Context Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the stored extension context, which provides access to global storage and other extension-related utilities. Throws an error if the context has not been initialized. ```typescript const context = getExtensionContext(); const storageUri = context.globalStorageUri; ``` -------------------------------- ### createStatusBarItem Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Creates and configures the status bar item for displaying usage stats. It is positioned on the right side of the status bar with a priority of 100 and is responsive to click events. ```APIDOC ## createStatusBarItem ### Description Creates and configures the status bar item for displaying usage stats. ### Returns `vscode.StatusBarItem` - Configured status bar item positioned on the right. ### Details - Alignment: Right - Priority: 100 - Responsive to click events ### Example ```typescript const statusBarItem = createStatusBarItem(); statusBarItem.text = '$(pulse) 125/500 (25%)'; statusBarItem.show(); ``` ``` -------------------------------- ### Get Refresh Interval Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the configured refresh interval for statistics updates in milliseconds. The minimum interval is 5 seconds, with a default of 30 seconds from configuration. ```typescript const intervalMs = getRefreshIntervalMs(); console.log(`Stats will update every ${intervalMs / 1000} seconds`); ``` -------------------------------- ### Extension Module Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/INDEX.md Functions for initializing and cleaning up the extension, and managing its refresh interval and context. ```APIDOC ## Extension Module (src/extension.ts) ### Description Provides core functions for the extension's lifecycle management. ### Functions - **activate()**: Initializes the extension. - **deactivate()**: Cleans up the extension resources. - **getRefreshIntervalMs()**: Retrieves the current refresh interval in milliseconds. - **getExtensionContext()**: Returns the extension's context object. ``` -------------------------------- ### Cursor Stats: Usage-Based Pricing Flow Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md Illustrates the user interaction flow for enabling, setting, or disabling usage-based pricing. This includes prompts for limits and confirmation messages. ```typescript // User sees quick pick // "Enable Usage-Based" β†’ prompts for amount β†’ "Enter monthly limit: 50" // Updates with "Usage-based pricing enabled with limit $50" // Or for existing limit // "Set Monthly Limit" β†’ prompts for new amount β†’ "Enter new monthly limit: 100" // Updates with "Limit updated to $100" // Or to disable // "Disable Usage-Based" β†’ "Usage-based pricing disabled" ``` -------------------------------- ### Get Stripe Checkout Session URL Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Obtains the Stripe checkout session URL for initiating the billing process. This URL can be used to redirect users to Stripe for payment. ```typescript const stripeUrl = await getStripeSessionUrl(token); vscode.env.openExternal(vscode.Uri.parse(stripeUrl)); ``` -------------------------------- ### Get Current Usage Limit Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the current monthly spending limit and per-user limit for usage-based pricing. Use this to check the hard limit set for your account or team. ```typescript const limit = await getCurrentUsageLimit(token); console.log(`Monthly limit: $${limit.hardLimit}`); ``` -------------------------------- ### Register Command to Open Cursor Stats Settings Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md This snippet demonstrates registering the 'cursor-stats.openSettings' command. It uses VS Code's API to open the settings UI, filtered to the Cursor Stats extension. ```typescript vscode.commands.registerCommand('cursor-stats.openSettings', async () => { await vscode.commands.executeCommand( 'workbench.action.openSettings', '@ext:Dwtexe.cursor-stats' ); }); ``` -------------------------------- ### startCountdownDisplay Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Initiates a countdown timer displayed in the status bar when the API is rate-limited. The countdown lasts for 10 minutes and resumes normal refresh upon completion. ```APIDOC ## startCountdownDisplay(): void ### Description Starts a countdown timer when the API is rate-limited. ### Behavior - Updates the status bar with the countdown every second. - Duration: 10 minutes (600 seconds). - Resumes normal refresh when the countdown ends. ### Example ```typescript setCooldownStartTime(Date.now()); startCountdownDisplay(); // Status bar shows: "$(warning) API Unavailable 9:59" ``` ``` -------------------------------- ### Get Windows Username for WSL Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Extracts the Windows username, primarily used to support WSL environments. Call this function if your application needs to resolve Windows user context within WSL. ```typescript const username = getWindowsUsername(); if (username) { console.log(`Windows user: ${username}`); } ``` -------------------------------- ### European Configuration for Cursor Stats Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md A configuration tailored for European users, setting currency to EUR, language to German, and enabling weekend exclusion. ```json { "cursorStats.currency": "EUR", "cursorStats.language": "de", "cursorStats.spendingAlertThreshold": 3, "cursorStats.refreshInterval": 45, "cursorStats.showProgressBars": true, "cursorStats.excludeWeekends": true } ``` -------------------------------- ### Accessing and Updating VS Code Configuration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md Demonstrates how to retrieve individual settings, array settings, and update a setting globally using the VS Code workspace configuration API. Includes default values for settings. ```typescript import * as vscode from 'vscode'; // Get a single setting const config = vscode.workspace.getConfiguration('cursorStats'); const refreshInterval = config.get('refreshInterval', 60); const currency = config.get('currency', 'USD'); const enableAlerts = config.get('enableAlerts', true); // Get array settings const thresholds = config.get('usageAlertThresholds', [10, 30, 50]); // Update a setting globally await config.update('currency', 'EUR', vscode.ConfigurationTarget.Global); // Listen for configuration changes vscode.workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration('cursorStats.currency')) { console.log('Currency setting changed'); } }); ``` -------------------------------- ### Start Automatic Stats Refresh Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Initiates the automatic refresh of statistics. Respects the configured refresh interval and avoids refreshing if the API is in cooldown or the window is not focused. Ensure `cursorStats.refreshInterval` is set appropriately. ```typescript startRefreshInterval(); // Stats will update every 60 seconds ``` -------------------------------- ### Get Status Bar Color Based on Percentage Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Determines the appropriate color for the status bar text based on the provided usage percentage. It respects custom color thresholds and falls back to a default gradient. ```typescript const color = getStatusBarColor(75); statusBarItem.color = color; ``` -------------------------------- ### formatTooltipLine Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Wraps text to a maximum width for tooltip formatting, ensuring readability by adding newlines and indentation. ```APIDOC ## formatTooltipLine ### Description Wraps text to a maximum width for tooltip formatting. ### Parameters #### Parameters - **text** (`string`) - Required - Text to format - **maxWidth** (`number`) - Optional - Maximum characters per line (defaults to `50`) ### Returns `string` - Text wrapped with newlines and indentation ### Example ```typescript const longText = 'This is a very long text that needs to be wrapped'; const formatted = formatTooltipLine(longText, 30); // Output: "This is a very long text that\n needs to be wrapped" ``` ``` -------------------------------- ### Currency Utility Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/INDEX.md Functions for currency conversion, formatting, and fetching exchange rates. ```APIDOC ## Currency Utility (src/utils/currency.ts) ### Description Handles currency conversions, formatting, and fetching of exchange rates. ### Functions - **getCurrentCurrency()**: Gets the currently selected currency. - **convertAndFormatCurrency()**: Converts a USD amount to the selected currency and formats it. - **convertAmount()**: Converts a given amount based on fetched exchange rates. - **formatCurrency()**: Formats a numerical amount with the appropriate currency symbol and formatting. - **getCurrencySymbol()**: Retrieves the symbol for a given currency. - **fetchExchangeRates()**: Fetches the latest exchange rates. - Caching functions: Manages caching of exchange rates. ``` -------------------------------- ### Cursor Stats Project Structure Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/README.md This snippet shows the directory and file structure of the cursor-stats project. It includes the main entry point, handlers, services, utilities, interfaces, and locale files. ```tree cursor-stats/ β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ extension.ts # Main extension entry point β”‚ β”œβ”€β”€ handlers/ β”‚ β”‚ β”œβ”€β”€ statusBar.ts # Status bar UI and formatting β”‚ β”‚ └── notifications.ts # User notifications β”‚ β”œβ”€β”€ services/ β”‚ β”‚ β”œβ”€β”€ api.ts # Cursor API endpoints β”‚ β”‚ β”œβ”€β”€ database.ts # SQLite database access β”‚ β”‚ β”œβ”€β”€ team.ts # Team membership and spending β”‚ β”‚ └── github.ts # GitHub release checking β”‚ β”œβ”€β”€ utils/ β”‚ β”‚ β”œβ”€β”€ logger.ts # Logging system β”‚ β”‚ β”œβ”€β”€ currency.ts # Currency conversion β”‚ β”‚ β”œβ”€β”€ cooldown.ts # Rate limiting and cooldown β”‚ β”‚ β”œβ”€β”€ progressBars.ts # Progress bar generation β”‚ β”‚ β”œβ”€β”€ updateStats.ts # Main stats update orchestration β”‚ β”‚ β”œβ”€β”€ i18n.ts # Internationalization β”‚ β”‚ └── report.ts # Diagnostic reporting β”‚ β”œβ”€β”€ interfaces/ β”‚ β”‚ β”œβ”€β”€ types.ts # Type definitions β”‚ β”‚ └── i18n.ts # Language pack interface β”‚ └── locales/ # Language pack files β”‚ β”œβ”€β”€ en.json β”‚ β”œβ”€β”€ de.json β”‚ β”œβ”€β”€ ru.json β”‚ β”œβ”€β”€ zh.json β”‚ β”œβ”€β”€ ko.json β”‚ β”œβ”€β”€ ja.json β”‚ └── kk.json β”œβ”€β”€ package.json # Extension manifest β”œβ”€β”€ tsconfig.json # TypeScript configuration └── README.md # Project README ``` -------------------------------- ### Strict Spending Control Configuration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md Configuration focused on strict spending control with a low alert threshold and critical progress bar limit. ```json { "cursorStats.spendingAlertThreshold": 0.5, "cursorStats.usageAlertThresholds": [50, 75, 100], "cursorStats.enableAlerts": true, "cursorStats.progressBarCriticalThreshold": 50, "cursorStats.currency": "USD" } ``` -------------------------------- ### UsageBasedPricing Interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Contains usage-based pricing data for a single month. Includes an array of billable items and information about mid-month payments and invoices. ```typescript interface UsageBasedPricing { items: UsageItem[]; // Array of billable items hasUnpaidMidMonthInvoice: boolean; // Whether there's an unpaid invoice midMonthPayment: number; // Amount paid mid-month in dollars } ``` -------------------------------- ### createProgressBar Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Creates a visual progress bar based on a percentage, with customizable length and thresholds for warning and critical states. ```APIDOC ## createProgressBar(percentage: number, length?: number, warningThreshold?: number, criticalThreshold?: number): string ### Description Creates a visual progress bar using emoji characters. The bar's color changes based on the provided percentage and thresholds. ### Parameters #### Path Parameters - `percentage` (number) - Required - Usage percentage (0-100) - `length` (number) - Optional - Number of characters in bar (default: 10) - `warningThreshold` (number) - Optional - Percentage for yellow (warning) (default: 75) - `criticalThreshold` (number) - Optional - Percentage for red (critical) (default: 90) ### Returns `string` - Progress bar using emoji characters (🟩, 🟨, πŸŸ₯, ⬜) ### Example ```typescript createProgressBar(75, 10, 75, 90); // Returns "🟨🟨🟨🟨🟨⬜⬜⬜⬜⬜" createProgressBar(25, 10, 75, 90); // Returns "🟩🟩⬜⬜⬜⬜⬜⬜⬜⬜" ``` ``` -------------------------------- ### ProgressBarSettings Interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Configuration for progress bar display. Defines the bar length and the percentage thresholds for warning and critical states. ```typescript interface ProgressBarSettings { barLength: number; // Number of characters in progress bar (5-20) warningThreshold: number; // Percentage for yellow state (0-100) criticalThreshold: number; // Percentage for red state (0-100) } ``` -------------------------------- ### VS Code Command Implementation Pattern Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md This snippet shows the standard pattern for implementing a VS Code command, including command logic and error handling. The command registration is typically added to the extension's subscriptions. ```typescript vscode.commands.registerCommand('cursor-stats.commandName', async () => { try { // Command logic log('[Command] Executing commandName'); } catch (error) { // Error handling vscode.window.showErrorMessage( t('commands.failedToExecute', { error: error.message }) ); } }); // Register in subscriptions context.subscriptions.push(commandRegistration); ``` -------------------------------- ### Extension Activation Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Extension activation is handled automatically by VS Code when the extension is loaded. This is typically configured in the package.json file. ```typescript // Extension activation is automatic when VS Code loads the extension // Registered in package.json activationEvents: ["onStartupFinished"] ``` -------------------------------- ### Custom Keyboard Shortcuts for Cursor Stats Commands Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md Users can define custom keyboard shortcuts in their `keybindings.json` file to quickly access specific Cursor Stats commands. This allows for personalized workflow optimization. ```json { "key": "ctrl+shift+u", "command": "cursor-stats.refreshStats" }, { "key": "ctrl+shift+l", "command": "cursor-stats.setLimit" }, { "key": "ctrl+shift+c", "command": "cursor-stats.selectCurrency" } ``` -------------------------------- ### Set Custom Usage Alert Thresholds Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md Configure specific percentage thresholds for triggering usage alerts. This allows for customized notification points based on usage levels. ```json "cursorStats.usageAlertThresholds": [25, 50, 75, 100] ``` -------------------------------- ### getProgressBarSettings Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the current configuration settings for progress bars, including bar length and threshold values. ```APIDOC ## getProgressBarSettings(): ProgressBarSettings ### Description Fetches the progress bar configuration, such as bar length and warning/critical thresholds, from the application settings. ### Returns `ProgressBarSettings` - An object containing progress bar settings: ```typescript { barLength: number; // 5-20 (default: 10) warningThreshold: number; // 0-100 (default: 50) criticalThreshold: number; // 0-100 (default: 75) } ``` ### Example ```typescript const settings = getProgressBarSettings(); console.log(`Bar length: ${settings.barLength} characters`); ``` ``` -------------------------------- ### UsageInfo Interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Represents the current usage status for notification purposes. Includes usage percentage, type, and optional limits or spending details. ```typescript interface UsageInfo { percentage: number; // Usage percentage (0-100) type: 'premium' | 'usage-based'; // Type of usage being tracked limit?: number; // Optional spending/request limit totalSpent?: number; // Optional total amount spent premiumPercentage?: number; // Optional premium request percentage } ``` -------------------------------- ### UsageItem Interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Represents a single billable item from the monthly invoice. Includes formatted calculation and cost strings, original description, and pricing details. ```typescript interface UsageItem { calculation: string; // Formatted calculation string (e.g., "05 req @ $0.003") totalDollars: string; // Total cost string (e.g., "$1.50") description?: string; // Original API description modelNameForTooltip?: string; // Extracted model name for display isDiscounted?: boolean; // Whether this item had discounted pricing } ``` -------------------------------- ### createUsageProgressBar Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Generates a progress bar that visualizes current usage against a specified limit, optionally including a label. ```APIDOC ## createUsageProgressBar(current: number, limit: number, label?: string): string ### Description Creates a progress bar to represent current usage relative to a maximum limit. Includes an optional label for context. ### Parameters #### Path Parameters - `current` (number) - Required - Current usage - `limit` (number) - Required - Maximum limit - `label` (string) - Optional - Progress bar label (default: "Usage") ### Returns `string` - Formatted progress bar with label ### Example ```typescript createUsageProgressBar(125, 500, 'Premium Requests'); // Returns "Premium Requests: 🟩🟩⬜⬜⬜⬜⬜⬜⬜⬜" ``` ``` -------------------------------- ### Convert and Format Currency Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Converts a USD amount to the user's selected currency and formats it. Fetches exchange rates if necessary and handles fallback to USD if conversion fails. Special formatting is applied for currencies like JPY and KRW that do not use decimals. ```typescript const formatted = await convertAndFormatCurrency(25.50); // If EUR selected and rate is 0.92: returns "€23.46" ``` -------------------------------- ### Create Usage Progress Bar Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Generates a progress bar to visualize current usage against a specified limit, with an optional label. ```typescript createUsageProgressBar(125, 500, 'Premium Requests'); // Returns "Premium Requests: 🟩🟩⬜⬜⬜⬜⬜⬜⬜⬜" ``` -------------------------------- ### generateReport Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Creates a comprehensive diagnostic report containing various usage and system details. ```APIDOC ## generateReport() ### Description Creates a comprehensive diagnostic report that includes extension version, VS Code version, OS information, cursor statistics, usage-based pricing details, team membership, spending data, invoice history, log history, and API error details. ### Method `generateReport` ### Returns `Promise<{ reportPath: string, success: boolean }> ` - `reportPath` (string) - Path to the generated JSON report. - `success` (boolean) - Indicates whether the report was successfully created. ### Example ```typescript const { reportPath, success } = await generateReport(); if (success) { await vscode.env.clipboard.writeText(reportPath); } ``` ``` -------------------------------- ### Create Formatted Markdown Tooltip Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Generates a detailed markdown tooltip for the status bar item, including usage statistics, pricing, and period information. It supports advanced formatting and features like progress bars. ```typescript const tooltipLines = [ 'πŸš€ Premium Fast Requests', 'Requests Used: 125/500', 'Utilized: 25%', 'Period: 15 April - 15 May', 'πŸ’³ Usage-Based Pricing: $25.50' ]; const tooltip = await createMarkdownTooltip(tooltipLines); statusBarItem.tooltip = tooltip; ``` -------------------------------- ### CursorStats Interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Complete usage statistics combining premium requests and usage-based pricing for the current and last month. Includes team spending data if applicable. ```typescript interface CursorStats { currentMonth: { month: number; // Month number (1-12) year: number; // Year usageBasedPricing: UsageBasedPricing; // Monthly pricing data }; lastMonth: { month: number; year: number; usageBasedPricing: UsageBasedPricing; }; premiumRequests: { current: number; // Current premium requests used limit: number; // Monthly limit on premium requests startOfMonth: string; // Billing period start date }; isTeamSpendData?: boolean; // Whether using team spending data teamId?: number; // Team ID if team member teamSpendCents?: number; // Team spend in cents } ``` -------------------------------- ### checkAndNotifySpending Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Monitors the total amount spent and displays notifications when spending reaches configured thresholds. It converts amounts to the user's currency and can be configured or disabled. ```APIDOC ## checkAndNotifySpending(totalSpent: number): Promise ### Description Monitors spending and shows notifications at spending thresholds. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters: - **totalSpent** (`number`) - Required - Total amount spent (in USD) ### Behavior: - Tracks spending multiples of the configured threshold - Converts amounts to user's selected currency - Primes tracked thresholds on initial run - Continues checking for each threshold crossed ### Configuration: - Setting: `cursorStats.spendingAlertThreshold` (default: $1) - Set to 0 or less to disable spending alerts ### Request Example: ```typescript await checkAndNotifySpending(25.50); // Shows notification at $1, $2, $3... multiples (if threshold is $1) ``` ### Response #### Success Response (200) - **void** - This function does not return a value. ``` -------------------------------- ### Database Service Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/INDEX.md Functions for interacting with the local database to retrieve authentication tokens and database paths. ```APIDOC ## Database Service (src/services/database.ts) ### Description Handles interactions with the local database for storing and retrieving authentication tokens and configuration. ### Functions - **getCursorTokenFromDB()**: Extracts the authentication token from the database. - **getCursorDBPath()**: Finds the location of the database file. - **getWindowsUsername()**: Retrieves the Windows username, used for WSL support. ``` -------------------------------- ### fetchCursorStats Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves comprehensive usage statistics including premium requests and usage-based pricing. ```APIDOC ## POST https://cursor.com/api/usage ### Description Retrieves comprehensive usage statistics including premium requests and usage-based pricing. ### Method POST ### Endpoint https://cursor.com/api/usage ### Parameters #### Query Parameters - **token** (string) - Required - Cursor session token ### Response #### Success Response (200) - **currentMonth** (object) - Description - **month** (number) - Description - **year** (number) - Description - **usageBasedPricing** (object) - Description - **lastMonth** (object) - Description - **month** (number) - Description - **year** (number) - Description - **usageBasedPricing** (object) - Description - **premiumRequests** (object) - Description - **current** (number) - Description - **limit** (number) - Description - **startOfMonth** (string) - Description - **isTeamSpendData** (boolean) - Optional - Description - **teamId** (number) - Optional - Description - **teamSpendCents** (number) - Optional - Description ``` -------------------------------- ### fetchExchangeRates Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Fetches the latest exchange rates from an external API, with rates based on USD. The fetched rates are cached for 24 hours to improve performance. ```APIDOC ## fetchExchangeRates ### Description Fetches current exchange rates from API. ### Returns `Promise` - Rates object with USD base ### Source `https://latest.currency-api.pages.dev/v1/currencies/usd.json` ### Caching - Caches for 24 hours in extension directory - Returns cached rates if available and fresh ### Example ```typescript const rates = await fetchExchangeRates(); const eurRate = rates.usd['eur']; // Gets EUR rate ``` ``` -------------------------------- ### shouldShowProgressBars Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Checks the system's configuration to determine if progress bars should be displayed to the user. ```APIDOC ## shouldShowProgressBars(): boolean ### Description Determines whether progress bars are enabled based on the `cursorStats.showProgressBars` setting. ### Returns `boolean` - `true` if progress bars should be shown, `false` otherwise. ### Example ```typescript if (shouldShowProgressBars()) { tooltip.appendMarkdown(progressBar); } ``` ``` -------------------------------- ### Initialize i18n and Translate Message Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Initializes the internationalization system and then translates a message using a given key. Ensure i18n is initialized before calling t(). ```typescript initializeI18n(); const message = t('statusBar.premiumFastRequests'); ``` -------------------------------- ### Select Display Currency Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md Use this command to change the currency displayed for monetary amounts. It presents a quick pick list of supported currencies and updates the global setting. ```typescript // User selects "EUR (Euro)" // All monetary displays update to Euro // $25.50 β†’ €23.46 (with current exchange rate) // Settings updated with: "cursorStats.currency": "EUR" ``` -------------------------------- ### setOnLanguageChangeCallback Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Sets a callback function that will be executed whenever the application's language changes. ```APIDOC ## setOnLanguageChangeCallback(callback: (newLanguage: string, languageLabel: string) => void): void ### Description Sets a callback for language changes. ### Parameters #### Parameters - **callback** (`function`) - Required - Function called when language changes. It receives the new language code and its label as arguments. ### Example ```typescript setOnLanguageChangeCallback((lang, label) => { vscode.window.showInformationMessage(`Language changed to ${label}`); }); ``` ``` -------------------------------- ### getExtensionContext Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Retrieves the stored extension context, which provides access to VS Code's extension APIs like global storage. ```APIDOC ## getExtensionContext ### Description Retrieves the stored extension context. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method N/A (Utility function) ### Endpoint N/A ### Request Example ```typescript const context = getExtensionContext(); const storageUri = context.globalStorageUri; ``` ### Response #### Success Response (`vscode.ExtensionContext`) - **Return Value** (`vscode.ExtensionContext`) - The extension context #### Response Example None ``` -------------------------------- ### Select Interface Language Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md Use this command to change the language of the extension's interface and messages. It updates the global setting and immediately reflects changes in UI elements. ```typescript // User selects "Deutsch" // All UI immediately updates to German // Confirmation: "Die Sprache wurde geΓ€ndert zu Deutsch" // Settings: "cursorStats.language": "de" ``` -------------------------------- ### cursor-stats.createReport Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md A registered command that generates a diagnostic report and prompts the user to open it. ```APIDOC ## cursor-stats.createReport ### Description This command generates a diagnostic report, displays progress during data gathering, opens a folder/file dialog upon completion, and automatically copies the report data to the clipboard. ### Behavior - Shows progress while gathering data. - Opens folder/file dialog on completion. - Copies report data to clipboard. ### Example ```typescript // User runs command via command palette // Report is created in extension directory // Report path copied to clipboard automatically ``` ``` -------------------------------- ### Logger Utility Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/INDEX.md Utility functions for initializing, logging messages, and managing log history. ```APIDOC ## Logger Utility (src/utils/logger.ts) ### Description Provides utilities for logging messages and managing the log history. ### Functions - **initializeLogging()**: Sets up the logging system. - **log()**: Logs a message. - **getLogHistory()**: Retrieves the history of log entries. - **clearLogHistory()**: Clears all entries from the log history. ``` -------------------------------- ### calculateDailyRemaining Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Calculates and returns a message about the remaining daily requests based on current usage, total limit, and the billing period's end date. ```APIDOC ## calculateDailyRemaining(currentRequests: number, limitRequests: number, periodEndDate: Date): string ### Description Calculates the estimated remaining requests per day for a billing period and provides a summary message. ### Parameters #### Path Parameters - `currentRequests` (number) - Required - Current request usage - `limitRequests` (number) - Required - Total request limit - `periodEndDate` (Date) - Required - End date of billing period ### Returns `string` - Daily remaining message or empty string ### Example ```typescript const endDate = new Date('2024-05-17'); const message = calculateDailyRemaining(125, 500, endDate); // Returns "~75 requests per day over 14 days (1050 remaining)" ``` ``` -------------------------------- ### Check for Latest GitHub Release Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Fetches the latest release information from the GitHub API for the dwtexe/cursor-stats repository. Returns null if an error occurs. ```typescript const result = await checkGitHubRelease(); if (result?.hasUpdate) { console.log(`Update available: ${result.latestVersion}`); } ``` -------------------------------- ### getMaxLineWidth Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Calculates the maximum line width from an array of strings, which is useful for determining layout constraints in tooltips. ```APIDOC ## getMaxLineWidth ### Description Calculates the maximum line width from an array of strings. ### Parameters #### Parameters - **lines** (`string[]`) - Required - Array of text lines ### Returns `number` - Width of the longest line ### Example ```typescript const lines = ['Short', 'This is a longer line', 'Medium']; const width = getMaxLineWidth(lines); // Returns 21 ``` ``` -------------------------------- ### Language Change Callback Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/commands.md This snippet shows how to register a callback function that is executed whenever the extension's language is changed. It demonstrates displaying a confirmation message in the newly selected language. ```typescript setOnLanguageChangeCallback((_newLanguage: string, languageLabel: string) => { const message = t('commands.languageChanged', { language: languageLabel }); vscode.window.showInformationMessage(message); }); ``` -------------------------------- ### Format Tooltip Line with Wrapping Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Wraps a given text string to a specified maximum width, inserting newlines and indentation as needed for better tooltip readability. Defaults to a maximum width of 50 characters. ```typescript const longText = 'This is a very long text that needs to be wrapped'; const formatted = formatTooltipLine(longText, 30); // Output: "This is a very long text that\n needs to be wrapped" ``` -------------------------------- ### checkGitHubRelease Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference.md Checks GitHub for the latest release of the cursor-stats extension. It returns information about the current and latest versions, release notes, and download URLs if an update is available. ```APIDOC ## GET https://api.github.com/repos/dwtexe/cursor-stats/releases ### Description Checks GitHub for the latest release of the cursor-stats extension. It returns information about the current and latest versions, release notes, and download URLs if an update is available. ### Method GET ### Endpoint https://api.github.com/repos/dwtexe/cursor-stats/releases ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```typescript const result = await checkGitHubRelease(); if (result?.hasUpdate) { console.log(`Update available: ${result.latestVersion}`); } ``` ### Response #### Success Response (200) - **hasUpdate** (boolean) - Indicates if a new release is available. - **currentVersion** (string) - The currently installed version. - **latestVersion** (string) - The latest available version. - **isPrerelease** (boolean) - Whether the latest release is a pre-release. - **releaseUrl** (string) - URL to the latest release on GitHub. - **releaseNotes** (string) - Markdown content of the release notes. - **releaseName** (string) - The name of the latest release. - **zipballUrl** (string) - URL to download the release as a zip archive. - **tarballUrl** (string) - URL to download the release as a tarball. - **assets** (Array) - List of release assets, each with `name` (string) and `downloadUrl` (string). #### Response Example ```json { "hasUpdate": true, "currentVersion": "1.0.0", "latestVersion": "1.1.0", "isPrerelease": false, "releaseUrl": "https://github.com/dwtexe/cursor-stats/releases/tag/v1.1.0", "releaseNotes": "### Added\n- New feature X\n### Fixed\n- Bug Y", "releaseName": "v1.1.0", "zipballUrl": "https://api.github.com/repos/dwtexe/cursor-stats/zipball/v1.1.0", "tarballUrl": "https://api.github.com/repos/dwtexe/cursor-stats/tarball/v1.1.0", "assets": [ { "name": "cursor-stats-1.1.0.vsix", "downloadUrl": "https://github.com/dwtexe/cursor-stats/releases/download/v1.1.0/cursor-stats-1.1.0.vsix" } ] } ``` ``` -------------------------------- ### Cursor APIs Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/INDEX.md Endpoints for managing spending limits, checking premium request status, retrieving invoice details, and managing team information. ```APIDOC ## POST /api/dashboard/get-hard-limit ### Description Retrieves the current spending limit. ### Method POST ### Endpoint /api/dashboard/get-hard-limit ### Parameters #### Request Body None explicitly mentioned. ### Response #### Success Response (200) Details about the spending limit. ### Response Example { "example": "{\"limit\": 1000}" } ## POST /api/dashboard/set-hard-limit ### Description Sets a new spending limit. ### Method POST ### Endpoint /api/dashboard/set-hard-limit ### Parameters #### Request Body - **limit** (integer) - Required - The new spending limit value. ### Response #### Success Response (200) Confirmation of the limit being set. ### Response Example { "example": "{\"message\": \"Limit set successfully\"}" } ## POST /api/dashboard/get-usage-based-premium-requests ### Description Checks if usage-based premium requests are enabled. ### Method POST ### Endpoint /api/dashboard/get-usage-based-premium-requests ### Parameters #### Request Body None explicitly mentioned. ### Response #### Success Response (200) Indicates whether premium requests are enabled. ### Response Example { "example": "{\"enabled\": true}" } ## POST /api/dashboard/get-monthly-invoice ### Description Retrieves details about monthly costs and invoices. ### Method POST ### Endpoint /api/dashboard/get-monthly-invoice ### Parameters #### Request Body None explicitly mentioned. ### Response #### Success Response (200) Information regarding monthly invoices and costs. ### Response Example { "example": "{\"invoice_id\": \"inv_123\", \"amount\": 50.00}" } ## POST /api/dashboard/teams ### Description Lists all teams associated with the account. ### Method POST ### Endpoint /api/dashboard/teams ### Parameters #### Request Body None explicitly mentioned. ### Response #### Success Response (200) A list of teams. ### Response Example { "example": "{\"teams\": [\"Team A\", \"Team B\"]}" } ## POST /api/dashboard/team ### Description Retrieves details for a specific team. ### Method POST ### Endpoint /api/dashboard/team ### Parameters #### Request Body - **team_id** (string) - Required - The ID of the team to retrieve details for. ### Response #### Success Response (200) Details of the specified team. ### Response Example { "example": "{\"team_name\": \"Team A\", \"members\": 5}" } ## POST /api/dashboard/get-team-spend ### Description Retrieves the spending details for a specific team. ### Method POST ### Endpoint /api/dashboard/get-team-spend ### Parameters #### Request Body - **team_id** (string) - Required - The ID of the team to get spending details for. ### Response #### Success Response (200) Spending information for the team. ### Response Example { "example": "{\"team_id\": \"Team A\", \"spent\": 25.50}" } ## GET /api/usage ### Description Provides information about premium request usage. ### Method GET ### Endpoint /api/usage ### Parameters None explicitly mentioned. ### Response #### Success Response (200) Details on premium request usage. ### Response Example { "example": "{\"requests_used\": 150, \"limit\": 200}" } ## GET /api/stripeSession ### Description Generates a billing URL for Stripe payment sessions. ### Method GET ### Endpoint /api/stripeSession ### Parameters None explicitly mentioned. ### Response #### Success Response (200) A URL to initiate a Stripe billing session. ### Response Example { "example": "{\"url\": \"https://stripe.com/billing/session/xyz123\"}" } ```