UNPKG

@adopture/next

Version:

Next.js SDK for Adopture feature adoption tracking with SSR support

490 lines (479 loc) 17.3 kB
import { AdoptionEventData, VisibilityTrackingOptions, UserProperties, FeatureTrackerConfig } from '@adopture/sdk-core'; export { AdoptionEventData, AdoptionEventType, ExposureEventData, FeatureTrackerConfig, UserProperties, VisibilityTrackingOptions, generateAnonymousId, generateEventId, generateSessionId, generateShortId, generateUUID, getUUIDGenerationInfo, isCryptoAvailable, isValidEventId, isValidUUID } from '@adopture/sdk-core'; import * as react_jsx_runtime from 'react/jsx-runtime'; import * as React$1 from 'react'; /** * 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 NextAdoptureProviderProps { config?: NextAdoptureConfig; children: React.ReactNode; fallback?: React.ReactNode; loadingComponent?: React.ReactNode; } interface NextAdoptureContext { tracker: NextAdoptureTracker | null; isInitialized: boolean; isLoading: boolean; error: Error | null; config: NextAdoptureConfig | null; } interface NextAdoptureTracker { track(featureId: string, metadata?: Record<string, unknown>): Promise<void>; trackAdoption(data: AdoptionEventData): Promise<void>; expose(featureId: string, exposureChannel?: string, metadata?: Record<string, unknown>, options?: VisibilityTrackingOptions): Promise<void>; identify(userId: string, properties?: UserProperties): Promise<void>; trackPageView(route: string, metadata?: Record<string, unknown>): Promise<void>; trackRouteChange(from: string, to: string, metadata?: Record<string, unknown>): Promise<void>; trackWebVital(name: string, value: number, metadata?: Record<string, unknown>): Promise<void>; flush(): Promise<void>; destroy(): Promise<void>; isReady(): boolean; getConfig(): NextAdoptureConfig | null; getCurrentUserId(): string | null; getSessionId(): string; } interface ServerAdoptureConfig extends Omit<FeatureTrackerConfig, 'apiUrl' | 'apiKey'> { apiUrl?: string; apiKey?: string; projectId?: string; environment?: 'live' | 'test'; enableEdgeRuntime?: boolean; requestTimeout?: number; activationTracking?: Partial<ActivationTrackerConfig>; } interface BootstrapData { config: NextAdoptureConfig; initialUserId?: string; initialUserProperties?: UserProperties; sessionId: string; timestamp: number; } interface UseAdoptureReturn { tracker: NextAdoptureTracker | null; track: (featureId: string, metadata?: Record<string, unknown>) => Promise<void>; expose: (featureId: string, exposureChannel?: string, metadata?: Record<string, unknown>, options?: VisibilityTrackingOptions) => Promise<void>; identify: (userId: string, properties?: UserProperties) => Promise<void>; isInitialized: boolean; isLoading: boolean; error: Error | null; } interface UseTrackReturn { track: (featureId: string, metadata?: Record<string, unknown>) => Promise<void>; isReady: boolean; } interface UseExposeReturn { expose: (featureId: string, exposureChannel?: string, metadata?: Record<string, unknown>, options?: VisibilityTrackingOptions) => Promise<void>; isReady: boolean; } /** * Client-side Next.js tracker extending React tracker with Next.js specific features */ /** * Client-side Next.js tracker with browser-specific features */ declare class NextClientTracker implements NextAdoptureTracker { private config; private isInitialized; private events; private batchTimer; private userId; private userProperties; private sessionId; private isDestroyed; private routeChangeCache; private webVitalsReported; private activationTracker; private currentRoute; private routeStartTime; private webVitalsEnabled; constructor(); /** * Initialize the Next.js tracker */ init(manualConfig?: Partial<NextAdoptureConfig>, bootstrapData?: BootstrapData): Promise<void>; /** * Track feature usage (automatically determines activation vs usage) */ track(featureId: string, metadata?: Record<string, unknown>): Promise<void>; /** * Track feature adoption */ trackAdoption(data: AdoptionEventData): Promise<void>; /** * Track feature exposure */ expose(featureId: string, exposureChannel?: string, metadata?: Record<string, unknown>, options?: VisibilityTrackingOptions): Promise<void>; /** * Identify user with properties */ identify(userId: string, properties?: UserProperties): Promise<void>; /** * Set current user without sending identify event (for UI framework integration) */ setUser(userId: string, properties?: UserProperties): void; /** * Track page view (Next.js specific) */ trackPageView(route: string, metadata?: Record<string, unknown>): Promise<void>; /** * Track route change (Next.js specific) */ trackRouteChange(from: string, to: string, metadata?: Record<string, unknown>): Promise<void>; /** * Track Core Web Vital (Next.js specific) */ trackWebVital(name: string, value: number, metadata?: Record<string, unknown>): Promise<void>; /** * Flush all queued events */ flush(): Promise<void>; /** * Clean shutdown */ destroy(): Promise<void>; /** * Check if tracker is ready */ isReady(): boolean; /** * Get current configuration */ getConfig(): NextAdoptureConfig | null; /** * Get current user ID */ getCurrentUserId(): string | null; /** * Get current session ID */ getSessionId(): string; /** * Initialize browser-specific features */ private initializeBrowserFeatures; /** * Send events to API */ private sendEvents; private sendSingleEvent; /** * Get or create anonymous ID */ private getAnonymousId; /** * Start batch timer for auto-flushing */ private startBatchTimer; } /** * Create a new client tracker instance */ declare function createClientTracker(config?: Partial<NextAdoptureConfig>): NextClientTracker; /** * Adopture Provider component for Next.js applications * Must be used with 'use client' directive */ declare function AdoptureProvider({ config, children, fallback, loadingComponent }: NextAdoptureProviderProps): react_jsx_runtime.JSX.Element; /** * Pages Router Provider component * For use with _app.tsx in Pages Router */ declare function AdopturePagesProvider({ config, children, fallback, loadingComponent }: NextAdoptureProviderProps): react_jsx_runtime.JSX.Element; /** * Hook to access Adopture context */ declare function useAdopture(): NextAdoptureContext; /** * Hook to access the tracker directly */ declare function useAdoptureTracker(): NextAdoptureTracker | null; /** * Bootstrap data injection component * Used to inject server-side bootstrap data into the client */ declare function AdoptureBootstrap({ data }: { data: BootstrapData; }): react_jsx_runtime.JSX.Element; /** * Main hook for accessing Adopture functionality with simplified API * * Features automatic activation/usage detection - no need to manually * track activation state. Just call track() and the SDK handles the rest. */ declare function useAdoptureTracking(): UseAdoptureReturn; /** * Hook for tracking feature usage with automatic activation/usage detection * * The SDK automatically determines whether this is a first-time activation * or subsequent usage based on internal state tracking. Developers no longer * need to manually track activation state. */ declare function useTrack(): UseTrackReturn; /** * Hook for tracking feature exposure */ declare function useExpose(): UseExposeReturn; /** * Hook for user identification */ declare function useIdentify(): { identify: (userId: string, properties?: UserProperties) => Promise<void>; isReady: boolean; }; /** * @deprecated Use useTrack() instead - automatic activation/usage detection is now built-in * * Hook for tracking adoption events (DEPRECATED) * * This hook is deprecated because the SDK now automatically determines * whether to send activation or usage events. Use the simpler `useTrack()` * hook instead, which handles this logic automatically. */ declare function useTrackAdoption(): { trackAdoption: (data: AdoptionEventData) => Promise<void>; isReady: boolean; }; /** * Hook that automatically tracks component mount/unmount */ declare function useComponentTracking(featureId: string, options?: { trackMount?: boolean; trackUnmount?: boolean; exposureChannel?: string; metadata?: Record<string, unknown>; }): void; /** * Hook for tracking user interactions (clicks, form submissions, etc.) */ declare function useInteractionTracking(featureId: string): { trackClick: (elementId?: string, metadata?: Record<string, unknown>) => void; trackFormSubmit: (formId?: string, metadata?: Record<string, unknown>) => void; trackInput: (inputId?: string, value?: string, metadata?: Record<string, unknown>) => void; trackScroll: (scrollPercentage?: number, metadata?: Record<string, unknown>) => void; trackError: (error: Error, metadata?: Record<string, unknown>) => void; }; /** * Hook for tracking page/component visibility using Intersection Observer */ declare function useVisibilityTracking(featureId: string, options?: { threshold?: number; rootMargin?: string; trackOnce?: boolean; }): (element: Element | null) => void; /** * Hook for tracking performance metrics */ declare function usePerformanceTracking(featureId: string): { trackTiming: (name: string, startTime: number, metadata?: Record<string, unknown>) => void; trackError: (error: Error, metadata?: Record<string, unknown>) => void; createTimer: (name: string) => { end: (metadata?: Record<string, unknown>) => void; }; }; /** * Props for AdoptureFeature component */ interface AdoptureFeatureProps { featureId: string; children: React$1.ReactNode; exposureChannel?: string; metadata?: Record<string, unknown>; trackVisibility?: boolean; visibilityOptions?: { threshold?: number; rootMargin?: string; trackOnce?: boolean; }; trackInteractions?: boolean; className?: string; } /** * Component that automatically tracks feature exposure and interactions */ declare function AdoptureFeature({ featureId, children, exposureChannel, metadata, trackVisibility, visibilityOptions, trackInteractions, className, }: AdoptureFeatureProps): react_jsx_runtime.JSX.Element; /** * Props for AdoptureTrackClick component */ interface AdoptureTrackClickProps { featureId: string; children: React$1.ReactNode; metadata?: Record<string, unknown>; onClick?: (event: React$1.MouseEvent) => void; as?: keyof JSX.IntrinsicElements | React$1.ComponentType<any>; [key: string]: any; } /** * Component that tracks click interactions */ declare function AdoptureTrackClick({ featureId, children, metadata, onClick, as: Component, ...props }: AdoptureTrackClickProps): React$1.ReactElement<any, string | React$1.JSXElementConstructor<any>>; /** * Props for AdoptureTrackForm component */ interface AdoptureTrackFormProps { featureId: string; children: React$1.ReactNode; metadata?: Record<string, unknown>; onSubmit?: (event: React$1.FormEvent) => void; trackInputs?: boolean; [key: string]: any; } /** * Component that tracks form interactions */ declare function AdoptureTrackForm({ featureId, children, metadata, onSubmit, trackInputs, ...props }: AdoptureTrackFormProps): react_jsx_runtime.JSX.Element; /** * Props for AdoptureConditionalFeature component */ interface AdoptureConditionalFeatureProps { featureId: string; condition: boolean | (() => boolean); children: React$1.ReactNode; fallback?: React$1.ReactNode; exposureChannel?: string; metadata?: Record<string, unknown>; trackExposure?: boolean; } /** * Component that conditionally renders content and tracks exposure */ declare function AdoptureConditionalFeature({ featureId, condition, children, fallback, exposureChannel, metadata, trackExposure, }: AdoptureConditionalFeatureProps): react_jsx_runtime.JSX.Element; /** * Props for AdopturePageView component */ interface AdopturePageViewProps { route?: string; metadata?: Record<string, unknown>; trackOnMount?: boolean; } /** * Component that tracks page views */ declare function AdopturePageView({ route, metadata, trackOnMount, }: AdopturePageViewProps): null; /** * Props for AdoptureScrollTracker component */ interface AdoptureScrollTrackerProps { featureId: string; thresholds?: number[]; metadata?: Record<string, unknown>; debounceMs?: number; } /** * Component that tracks scroll depth */ declare function AdoptureScrollTracker({ featureId, thresholds, metadata, debounceMs, }: AdoptureScrollTrackerProps): null; /** * Props for AdoptureErrorBoundary component */ interface AdoptureErrorBoundaryProps { featureId: string; children: React$1.ReactNode; fallback?: React$1.ComponentType<{ error: Error; retry: () => void; }>; metadata?: Record<string, unknown>; onError?: (error: Error) => void; } /** * Error boundary that tracks errors */ declare class AdoptureErrorBoundary extends React$1.Component<AdoptureErrorBoundaryProps, { hasError: boolean; error: Error | null; }> { private trackError; constructor(props: AdoptureErrorBoundaryProps); static getDerivedStateFromError(error: Error): { hasError: boolean; error: Error; }; componentDidCatch(error: Error, errorInfo: React$1.ErrorInfo): void; setTrackError: (trackError: (error: Error, metadata?: Record<string, unknown>) => void) => void; retry: () => void; render(): react_jsx_runtime.JSX.Element; } /** * Load client-side configuration from environment variables and manual config * Now also checks for .adopture.config.json file (client-side via injected config) */ declare function loadClientConfig(manualConfig?: Partial<NextAdoptureConfig>): NextAdoptureConfig; /** * 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; /** * Check if we're running on the client side */ declare function isClient(): 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; /** * 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 { AdoptureBootstrap, AdoptureConditionalFeature, AdoptureErrorBoundary, AdoptureFeature, AdopturePageView, AdopturePagesProvider, AdoptureProvider, AdoptureScrollTracker, AdoptureTrackClick, AdoptureTrackForm, type BootstrapData, type NextAdoptureConfig, type NextAdoptureContext, type NextAdoptureProviderProps, type NextAdoptureTracker, NextClientTracker, TTLCache, type UseAdoptureReturn, type UseExposeReturn, type UseTrackReturn, createClientTracker, extractEnvironmentFromApiKey, extractProjectIdFromApiKey, extractRoute, isClient, isDevelopment, isProduction, loadClientConfig, shouldExcludeRoute, useAdopture, useAdoptureTracker, useAdoptureTracking, useComponentTracking, useExpose, useIdentify, useInteractionTracking, usePerformanceTracking, useTrack, useTrackAdoption, useVisibilityTracking, validateConfig };