UNPKG

@flagvault/sdk

Version:

Lightweight JavaScript SDK for FlagVault with intelligent caching, graceful error handling, and built-in React hooks for seamless feature flag integration.

398 lines 11.4 kB
/** * Base exception for FlagVault SDK errors. */ export declare class FlagVaultError extends Error { constructor(message: string); } /** * Raised when authentication fails. */ export declare class FlagVaultAuthenticationError extends FlagVaultError { constructor(message: string); } /** * Raised when network requests fail. */ export declare class FlagVaultNetworkError extends FlagVaultError { constructor(message: string); } /** * Raised when the API returns an error response. */ export declare class FlagVaultAPIError extends FlagVaultError { constructor(message: string); } /** * Feature flag metadata returned from the API. * * @group Core */ export interface FeatureFlagMetadata { /** The flag key */ key: string; /** Whether the flag is enabled */ isEnabled: boolean; /** Display name of the flag */ name: string; /** Percentage of users to enable (0-100) */ rolloutPercentage?: number | null; /** Random seed for consistent rollout */ rolloutSeed?: string | null; } /** * Cache configuration options for the FlagVault SDK. * * @group Configuration */ export interface CacheConfig { /** * Enable or disable caching. * Defaults to true. */ enabled?: boolean; /** * Cache time-to-live in seconds. * Defaults to 300 seconds (5 minutes). */ ttl?: number; /** * Maximum number of flags to cache. * Defaults to 1000. */ maxSize?: number; /** * Background refresh interval in seconds. * Set to 0 to disable background refresh. * Defaults to 60 seconds. */ refreshInterval?: number; /** * Fallback behavior when cache is empty and API fails. * - 'api': Retry API call (may throw) * - 'default': Return default value * - 'throw': Throw the error * Defaults to 'default'. */ fallbackBehavior?: "api" | "default" | "throw"; } /** * Cache statistics for monitoring and debugging. * * @group Debugging */ export interface CacheStats { /** Current number of cached flags */ size: number; /** Cache hit rate as a percentage (0-1) */ hitRate: number; /** Number of expired entries */ expiredEntries: number; /** Estimated memory usage in bytes */ memoryUsage: number; } /** * Debug information for a specific flag. * * @group Debugging */ export interface FlagDebugInfo { /** The flag key */ flagKey: string; /** Whether the flag is currently cached */ cached: boolean; /** The cached value (if any) */ value?: boolean; /** When the flag was cached */ cachedAt?: number; /** When the flag expires */ expiresAt?: number; /** Time until expiry in milliseconds */ timeUntilExpiry?: number; /** Last access time */ lastAccessed?: number; } /** * Configuration options for the FlagVault SDK. * * @group Configuration */ export interface FlagVaultSDKConfig { /** * API Key for authenticating with the FlagVault service. * Can be obtained from your FlagVault dashboard. * Environment is automatically determined from the key prefix (live_ = production, test_ = test). */ apiKey: string; /** * Request timeout in milliseconds. * Defaults to 10000ms (10 seconds). */ timeout?: number; /** * @internal * Base URL for the FlagVault API. * Defaults to "https://api.flagvault.com". */ baseUrl?: string; /** * Cache configuration options. * Defaults to enabled with 5-minute TTL. */ cache?: CacheConfig; } /** * FlagVault SDK for feature flag management. * * This SDK allows you to easily integrate feature flags into your JavaScript/TypeScript applications. * Feature flags (also known as feature toggles) allow you to enable or disable features in your * application without deploying new code. * * ## Installation * * ```bash * npm install @flagvault/sdk * # or * yarn add @flagvault/sdk * ``` * * ## Basic Usage * * ```typescript * import FlagVaultSDK from '@flagvault/sdk'; * * const sdk = new FlagVaultSDK({ * apiKey: 'live_your-api-key-here' // Use 'test_' prefix for test environment * }); * * // Check if a feature flag is enabled * const isEnabled = await sdk.isEnabled('my-feature-flag'); * if (isEnabled) { * // Feature is enabled, run feature code * } else { * // Feature is disabled, run fallback code * } * ``` * * ## Graceful Error Handling * * The SDK automatically handles errors gracefully by returning default values: * * ```typescript * // No try/catch needed - errors are handled gracefully * const isEnabled = await sdk.isEnabled('my-feature-flag', false); * * // On network error, you'll see: * // FlagVault: Failed to connect to API for flag 'my-feature-flag', using default: false * * // On authentication error: * // FlagVault: Invalid API credentials for flag 'my-feature-flag', using default: false * * // On missing flag: * // FlagVault: Flag 'my-feature-flag' not found, using default: false * ``` * * ## Advanced Error Handling * * For custom error handling, you can still catch exceptions for parameter validation: * * ```typescript * try { * const isEnabled = await sdk.isEnabled('my-feature-flag', false); * // ... * } catch (error) { * // Only throws for invalid parameters (empty flagKey) * console.error('Parameter validation error:', error.message); * } * ``` * * @group Core */ declare class FlagVaultSDK { private apiKey; private baseUrl; private timeout; private cacheConfig; private cache; private refreshTimer?; private refreshInProgress; private bulkFlagsCache?; /** * Creates a new instance of the FlagVault SDK. * * @param config - Configuration options for the SDK * @throws Error if apiKey is not provided */ constructor(config: FlagVaultSDKConfig); /** * Stops background refresh and cleans up resources. * Call this when you're done with the SDK instance. */ destroy(): void; /** * Checks if a feature flag is enabled. * * @param flagKey - The key for the feature flag * @param defaultValue - Default value to return on error (defaults to false) * @param context - Optional context ID for percentage rollouts (e.g., userId, sessionId) * @returns A promise that resolves to a boolean indicating if the feature is enabled * @throws Error if flagKey is not provided */ isEnabled(flagKey: string, defaultValue?: boolean, context?: string): Promise<boolean>; /** * Fetches a flag value from the API with cache information. * @private */ private fetchFlagFromApiWithCacheInfo; /** * Fetches a flag value from the API. * @private */ private fetchFlagFromApi; /** * Gets a cached flag value if it exists and is not expired. * @private */ private getCachedValue; /** * Sets a flag value in the cache. * @private */ private setCachedValue; /** * Evicts the least recently used entry from the cache. * @private */ private evictOldestEntry; /** * Handles cache miss scenarios based on configured fallback behavior. * @private */ private handleCacheMiss; /** * Starts the background refresh timer. * @private */ private startBackgroundRefresh; /** * Refreshes flags that are about to expire. * @private */ private refreshExpiredFlags; /** * Gets cache statistics for monitoring and debugging. * * @returns Object containing cache statistics */ getCacheStats(): CacheStats; /** * Gets debug information for a specific flag. * * @param flagKey - The flag key to debug * @returns Debug information about the flag */ debugFlag(flagKey: string): FlagDebugInfo; /** * Clears the entire cache. */ clearCache(): void; /** * Estimates memory usage of the cache. * @private */ private estimateMemoryUsage; /** * Fetches all feature flags for the organization. * * @returns A promise that resolves to a map of flag keys to flag metadata * @throws Error on network or API errors */ getAllFlags(): Promise<Map<string, FeatureFlagMetadata>>; /** * Evaluates a feature flag for a specific context using local rollout logic. * @private */ private evaluateFlag; /** * Preloads all feature flags into cache. * Useful for applications that need to evaluate many flags quickly. * * @returns A promise that resolves when flags are loaded */ preloadFlags(): Promise<void>; } export default FlagVaultSDK; /** * React hook return type for feature flag hooks. * @group React Hooks */ export interface UseFeatureFlagReturn { /** Whether the feature flag is enabled */ isEnabled: boolean; /** Whether the hook is currently loading the flag status */ isLoading: boolean; /** Any error that occurred while fetching the flag status */ error: Error | null; } /** * React hook for checking feature flag status. * * @param sdk - FlagVault SDK instance * @param flagKey - The feature flag key to check * @param defaultValue - Default value to use if flag cannot be loaded * @param context - Optional context ID for percentage rollouts (e.g., userId, sessionId) * @returns Object containing isEnabled, isLoading, and error states * * @example * ```tsx * import FlagVaultSDK, { useFeatureFlag } from '@flagvault/sdk'; * * const sdk = new FlagVaultSDK({ apiKey: 'live_your-api-key' }); * * function MyComponent() { * const { isEnabled, isLoading, error } = useFeatureFlag(sdk, 'new-feature', false, 'user-123'); * * if (isLoading) return <div>Loading...</div>; * if (error) return <div>Error: {error.message}</div>; * * return isEnabled ? <NewFeature /> : <OldFeature />; * } * ``` * * @group React Hooks */ export declare function useFeatureFlag(sdk: FlagVaultSDK, flagKey: string, defaultValue?: boolean, context?: string): UseFeatureFlagReturn; /** * React hook for checking feature flag status with caching. * Reduces API calls by caching flag values for a specified TTL. * * @param sdk - FlagVault SDK instance * @param flagKey - The feature flag key to check * @param defaultValue - Default value to use if flag cannot be loaded * @param cacheTTL - Cache time-to-live in milliseconds (default: 5 minutes) * @param context - Optional context ID for percentage rollouts (e.g., userId, sessionId) * @returns Object containing isEnabled, isLoading, and error states * * @example * ```tsx * import FlagVaultSDK, { useFeatureFlagCached } from '@flagvault/sdk'; * * const sdk = new FlagVaultSDK({ apiKey: 'live_your-api-key' }); * * function MyComponent() { * const { isEnabled, isLoading } = useFeatureFlagCached( * sdk, * 'new-feature', * false, * 300000, // 5 minutes cache * 'user-123' * ); * * return isEnabled ? <NewFeature /> : <OldFeature />; * } * ``` * * @group React Hooks */ export declare function useFeatureFlagCached(sdk: FlagVaultSDK, flagKey: string, defaultValue?: boolean, cacheTTL?: number, // 5 minutes context?: string): UseFeatureFlagReturn; //# sourceMappingURL=index.d.ts.map