@adopture/next
Version:
Next.js SDK for Adopture feature adoption tracking with SSR support
267 lines (258 loc) • 9.02 kB
TypeScript
import { AdoptionEventData, UserProperties, FeatureTrackerConfig } from '@adopture/sdk-core';
export { AdoptionEventData, AdoptionEventType, ExposureEventData, FeatureTrackerConfig, UserProperties, VisibilityTrackingOptions } from '@adopture/sdk-core';
/**
* Activation state tracker for automatic activation/usage event detection
* Manages per-user, per-feature activation state with configurable persistence
*/
interface ActivationTrackerConfig {
enabled: boolean;
persistAcrossSessions: boolean;
autoUpgrade: boolean;
resetOnNewSession: boolean;
storageKey: string;
maxCacheSize: number;
sessionTTL: number;
debug: boolean;
}
interface NextAdoptureConfig extends Omit<FeatureTrackerConfig, 'apiUrl' | 'apiKey'> {
apiUrl?: string;
apiKey?: string;
projectId?: string;
environment?: 'live' | 'test';
enableAutoPageTracking?: boolean;
enableWebVitals?: boolean;
enableRouteTracking?: boolean;
routeChangeTimeout?: number;
enableServerSideTracking?: boolean;
bootstrapFromServer?: boolean;
disableInDevelopment?: boolean;
debugMode?: 'client' | 'server' | 'both' | false;
activationTracking?: Partial<ActivationTrackerConfig>;
}
interface ServerAdoptureConfig extends Omit<FeatureTrackerConfig, 'apiUrl' | 'apiKey'> {
apiUrl?: string;
apiKey?: string;
projectId?: string;
environment?: 'live' | 'test';
enableEdgeRuntime?: boolean;
requestTimeout?: number;
activationTracking?: Partial<ActivationTrackerConfig>;
}
interface ServerAdoptureTracker {
track(featureId: string, userId: string, metadata?: Record<string, unknown>): Promise<void>;
trackAdoption(data: AdoptionEventData): Promise<void>;
expose(featureId: string, userId: string, exposureChannel?: string, metadata?: Record<string, unknown>): Promise<void>;
identify(userId: string, properties?: UserProperties): Promise<void>;
flush(): Promise<void>;
isReady(): boolean;
getConfig(): ServerAdoptureConfig | null;
}
interface MiddlewareConfig {
apiKey: string;
apiUrl?: string;
enableRouteTracking?: boolean;
enablePerformanceTracking?: boolean;
excludeRoutes?: string[];
includeRoutes?: string[];
userIdExtractor?: (request: any) => string | null;
metadataExtractor?: (request: any) => Record<string, unknown>;
}
interface BootstrapData {
config: NextAdoptureConfig;
initialUserId?: string;
initialUserProperties?: UserProperties;
sessionId: string;
timestamp: number;
}
/**
* Server-side Adopture tracker for Next.js applications
* Designed for server components, API routes, and middleware
*/
declare class NextServerTracker implements ServerAdoptureTracker {
private config;
private isInitialized;
private events;
private sessionId;
constructor();
/**
* Initialize the server tracker
*/
init(manualConfig?: Partial<ServerAdoptureConfig>): Promise<void>;
/**
* Track feature usage
*/
track(featureId: string, userId: string, metadata?: Record<string, unknown>): Promise<void>;
/**
* Track feature adoption
*/
trackAdoption(data: AdoptionEventData): Promise<void>;
/**
* Track feature exposure
*/
expose(featureId: string, userId: string, exposureChannel?: string, metadata?: Record<string, unknown>): Promise<void>;
/**
* Identify user with properties
*/
identify(userId: string, properties?: UserProperties): Promise<void>;
/**
* Flush all queued events (not applicable for server-side, events are sent immediately)
*/
flush(): Promise<void>;
/**
* Check if tracker is ready
*/
isReady(): boolean;
/**
* Get current configuration
*/
getConfig(): ServerAdoptureConfig | null;
/**
* Generate bootstrap data for client-side hydration
*/
generateBootstrapData(userId?: string, userProperties?: UserProperties): BootstrapData | null;
/**
* Send event to API
*/
private sendEvent;
}
/**
* Create a new server tracker instance
*/
declare function createServerTracker(config?: Partial<ServerAdoptureConfig>): NextServerTracker;
/**
* Get or create global server tracker instance
*/
declare function getServerTracker(config?: Partial<ServerAdoptureConfig>): NextServerTracker;
/**
* Initialize global server tracker
*/
declare function initServerTracker(config?: Partial<ServerAdoptureConfig>): Promise<NextServerTracker>;
/**
* Next.js Server Actions integration for Adopture
* Provides server actions that can be called from client components
*/
/**
* Server action to track feature usage
*/
declare function trackFeature(featureId: string, userId?: string, metadata?: Record<string, unknown>): Promise<{
success: boolean;
error?: string;
}>;
/**
* Server action to track feature adoption
*/
declare function trackAdoption(data: Omit<AdoptionEventData, 'userId'> & {
userId?: string;
}): Promise<{
success: boolean;
error?: string;
}>;
/**
* Server action to track feature exposure
*/
declare function exposeFeature(featureId: string, exposureChannel?: string, userId?: string, metadata?: Record<string, unknown>): Promise<{
success: boolean;
error?: string;
}>;
/**
* Server action to identify user
*/
declare function identifyUser(userId: string, properties?: UserProperties): Promise<{
success: boolean;
error?: string;
}>;
/**
* Server action to initialize tracker (should be called from layout or page)
*/
declare function initializeTracker(config?: Partial<ServerAdoptureConfig>): Promise<{
success: boolean;
error?: string;
bootstrapData?: any;
}>;
/**
* Server action to get current tracker status
*/
declare function getTrackerStatus(): Promise<{
isReady: boolean;
config?: ServerAdoptureConfig | null;
error?: string;
}>;
/**
* Higher-order function to wrap server actions with automatic tracking
*/
declare function withTracking<T extends any[], R>(action: (...args: T) => Promise<R>, options: {
featureId: string;
extractUserId?: (...args: T) => string | undefined;
extractMetadata?: (...args: T) => Record<string, unknown>;
trackOnSuccess?: boolean;
trackOnError?: boolean;
}): (...args: T) => Promise<R>;
/**
* Decorator for server actions to add automatic tracking
*/
declare function track(options: {
featureId: string;
extractUserId?: (...args: any[]) => string | undefined;
extractMetadata?: (...args: any[]) => Record<string, unknown>;
trackOnSuccess?: boolean;
trackOnError?: boolean;
}): <T extends any[], R>(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<(...args: T) => Promise<R>>) => TypedPropertyDescriptor<(...args: T) => Promise<R>>;
/**
* Load server-side configuration from environment variables and manual config
* Can also load from .adopture.config.json file if available
*/
declare function loadServerConfig(manualConfig?: Partial<ServerAdoptureConfig>): Promise<ServerAdoptureConfig>;
/**
* Validate that required configuration is present
*/
declare function validateConfig(config: NextAdoptureConfig | ServerAdoptureConfig): {
isValid: boolean;
errors: string[];
};
/**
* Extract project ID from API key
*/
declare function extractProjectIdFromApiKey(apiKey: string): string | null;
/**
* Determine environment from API key
*/
declare function extractEnvironmentFromApiKey(apiKey: string): 'live' | 'test' | null;
/**
* Check if we're in development mode
*/
declare function isDevelopment(): boolean;
/**
* Check if we're in production mode
*/
declare function isProduction(): boolean;
/**
* Extract route from Next.js pathname
*/
declare function extractRoute(pathname: string): string;
/**
* Check if route should be excluded from tracking
*/
declare function shouldExcludeRoute(pathname: string, excludeRoutes?: string[], includeRoutes?: string[]): boolean;
/**
* Extract user ID from various sources
*/
declare function extractUserId(headers: Headers, cookies?: {
[key: string]: string;
}, customExtractor?: (headers: Headers) => string | null): string | null;
/**
* Create a cache with TTL
*/
declare class TTLCache<K, V> {
private cache;
private defaultTTL;
constructor(defaultTTL?: number);
set(key: K, value: V, ttl?: number): void;
get(key: K): V | undefined;
has(key: K): boolean;
delete(key: K): boolean;
clear(): void;
cleanup(): void;
size(): number;
forEach(callback: (value: V, key: K) => void): void;
}
export { type BootstrapData, type MiddlewareConfig, NextServerTracker, type ServerAdoptureConfig, type ServerAdoptureTracker, TTLCache, createServerTracker, exposeFeature, extractEnvironmentFromApiKey, extractProjectIdFromApiKey, extractRoute, extractUserId, getServerTracker, getTrackerStatus, identifyUser, initServerTracker, initializeTracker, isDevelopment, isProduction, loadServerConfig, shouldExcludeRoute, track, trackAdoption, trackFeature, validateConfig, withTracking };