import { ReactElement, ReactNode } from 'react'; export { StyleSheet } from 'react-native'; /** * @module AnalyticsTypes * @package @geenius/analytics * @description Defines the shared analytics domain model used across the core * tracker, provider integrations, UI variants, and Convex support package. * These types establish the public contract that every variant builds on. */ /** * Analytics event category used by the shared tracker and validators. */ type EventType = "page_view" | "click" | "form_submit" | "custom"; /** * Browser and device metadata captured alongside analytics events. * * @property device Canonical device bucket derived from the client environment. */ interface DeviceInfo { browser: string; os: string; device: "desktop" | "tablet" | "mobile"; screenWidth: number; screenHeight: number; language: string; } /** * Normalized analytics event payload tracked by the shared runtime. * * @property properties Optional event-specific metadata payload. * @property ipAddress Optional client IP address, truncated before storage when IP masking is enabled. * @property sessionId Session identifier associated with the event. */ interface AnalyticsEvent { id: string; type: EventType; name: string; properties?: Record; url: string; referrer: string; ipAddress?: string; sessionId: string; userId?: string; traits?: UserTraits; device: DeviceInfo; timestamp: number; } /** * Shared tracker configuration toggles for privacy and event collection. * * @property allowPreConsentTracking Explicitly permits tracking before a consent choice. * @property batchSize Number of queued track/page payloads that triggers a flush. * @property flushIntervalMs Optional interval that flushes queued payloads. * @property eventThrottleMs Optional per-event-name throttle window for custom events. * @property persistOfflineQueue Whether queued track/page payloads should survive reloads. * @property offlineQueueKey Storage key used for the durable offline queue. * @property replayOnReconnect Whether the tracker should replay queued payloads on browser reconnect. * @property retentionDays Optional number of days to retain analytics records and aggregates. * @property excludePaths Route prefixes that should be skipped by automatic page tracking. * @property respectDnt Whether the browser Do Not Track signal should suppress collection. * @property maskPii Whether sensitive payload values are masked before dispatch; user IDs become stable pseudonymous IDs. * @property maskIp Whether IP-shaped payload fields should be truncated before storage or provider sync. * @property anonymize Whether identifiers and sensitive values should use anonymous hashes instead of readable masks. */ interface AnalyticsConfig { trackPageViews?: boolean; trackClicks?: boolean; trackErrors?: boolean; trackPerformance?: boolean; trackSessionStart?: boolean; trackNavigation?: boolean; allowPreConsentTracking?: boolean; batchSize?: number; flushIntervalMs?: number; eventThrottleMs?: number; persistOfflineQueue?: boolean; offlineQueueKey?: string; replayOnReconnect?: boolean; retentionDays?: number; respectDnt?: boolean; sessionTimeout?: number; excludePaths?: string[]; debug?: boolean; maskPii?: boolean; maskIp?: boolean; anonymize?: boolean; } /** * Ranked page summary row consumed by top-page tables. * * @property uniqueVisitors Distinct user or session count for the route. * @property averageTimeMs Average dwell time for the route, in milliseconds. */ interface TopPageSummary { url: string; views: number; uniqueVisitors?: number; averageTimeMs?: number; averageTimeSeconds?: number; averageTime?: string; } /** * Aggregated analytics dashboard payload consumed by UI variants. * * @property topPages Ranked page summary rows by view count, visitors, and dwell time. * @property deviceBreakdown Device counts grouped by canonical device bucket. */ interface AnalyticsDashboardData { totalPageViews: number; uniqueVisitors: number; topPages: TopPageSummary[]; topReferrers: Array<{ referrer: string; visits: number; }>; deviceBreakdown: { desktop: number; tablet: number; mobile: number; }; browserBreakdown: Record; } /** * Canonical consent categories exposed by the public analytics contract. */ type ConsentCategory = "essential" | "analytics" | "marketing" | "personalization"; /** * Consent payload controlling which categories of tracking are allowed. * * @property essential Required product and privacy operations that stay enabled. * @property personalization Product personalization and feature preference tracking. * @property functional Deprecated alias retained for existing integrations. * @property timestamp Time at which the consent decision was recorded. */ interface ConsentSettings { essential: boolean; analytics: boolean; marketing: boolean; personalization: boolean; functional?: boolean; timestamp: number; } /** * User traits forwarded to analytics providers during identification. */ interface UserTraits { email?: string; name?: string; plan?: string; company?: string; avatar?: string; [key: string]: unknown; } /** * Declarative definition of a funnel step in shared analytics analysis. * * @property properties Optional event-property filter that must match the step. */ interface FunnelStep { name: string; event: string; properties?: Record; } /** * Computed analytics result for a single funnel step. * * @property dropoffRate Percentage of entries lost before reaching the step. * @property conversionRate Percentage of initial entries that reached the step. * @property averageTimeFromPreviousMs Average elapsed time from the previous completed step. */ interface FunnelStepResult { name: string; event: string; count: number; dropoffRate: number; conversionRate: number; averageTimeFromPreviousMs?: number; } /** * Aggregated result for a complete funnel analysis. * * @property steps Ordered funnel step results from entry to conversion. * @property overallConversionRate Percentage of entries that completed the funnel. * @property averageTimeToConvertMs Average elapsed time from first to final step. */ interface FunnelResult { name: string; steps: FunnelStepResult[]; totalEntries: number; totalConversions: number; overallConversionRate: number; averageTimeToConvertMs?: number; analyzedAt: number; } /** * Snapshot of realtime visitor and page activity. * * @property activeSessions Number of currently active analytics sessions. * @property eventsPerSecond Recent event throughput for live dashboards. * @property conversions Number of conversion events in the active realtime window. * @property conversionRate Conversion percentage in the active realtime window. * @property deviceBreakdown Live visitor distribution by device bucket. * @property topActivePages Ranked active pages with live visitor counts. * @property lastUpdated Timestamp at which the snapshot was produced. */ interface RealtimeStats { activeVisitors: number; currentPageViews: number; activeSessions?: number; eventsPerSecond?: number; conversions?: number; conversionRate?: number; deviceBreakdown?: AnalyticsDashboardData["deviceBreakdown"]; topActivePages: Array<{ url: string; visitors: number; }>; lastUpdated: number; } /** * Computed metric summary rendered by dashboard cards and tables. * * @property trend Direction of movement relative to the previous value. * @property format Presentation mode used to format the numeric value. */ interface MetricSummary { label: string; value: number; previousValue?: number; change?: number; changePercent?: number; trend: "up" | "down" | "flat"; format: "number" | "percent" | "duration" | "currency"; } /** * Single chart datapoint rendered by analytics visualizations. */ interface ChartDataPoint { label: string; value: number; timestamp?: number; } /** * Timeline event rendered in recent-activity views. * * @property properties Optional event metadata associated with the timeline entry. */ interface TimelineEvent { id: string; event: string; userId?: string; properties?: Record; timestamp: number; } /** * @module GoogleAnalyticsProvider * @package @geenius/analytics * @description Implements the shared Google Analytics 4 provider using the * global `gtag.js` browser script. The provider injects the runtime script on * demand and adapts shared event/page payloads to GA4 conventions. */ declare global { interface Window { dataLayer: unknown[]; gtag: (...args: unknown[]) => void; } } /** * @module Tracker * @package @geenius/analytics * @description Shared tracker factory that coordinates provider dispatch, * consent checks, and privacy sanitization for every published analytics * variant. Framework bindings wrap this tracker rather than reimplementing the * dispatch lifecycle themselves. */ /** * Options for categorizing manual events against granular consent settings. * * @property scope Consent category required before the tracker dispatches the event. * * @example * ```ts * await tracker.track("campaign_cta_clicked", {}, { scope: "marketing" }) * ``` */ interface TrackerTrackOptions { scope?: ConsentCategory; } /** * Public tracker contract shared by framework bindings and standalone consumers. * * @property track Dispatches a custom analytics event with optional consent scope. * @property page Dispatches a page-view record when tracking is enabled for the URL. * @property pageView Dispatches a page-view record using the canonical public method name. * @property identify Associates subsequent events with a known user identity. * @property setUserProperties Updates user traits attached to later events and provider profiles. * @property flush Dispatches queued track/page payloads to storage and providers. * @property reset Clears identity state and rolls the session identifier forward. * @property shutdown Flushes queued work and shuts down initialized providers. * @property purgeExpiredData Purges records and aggregates outside the retention window. * @property consent Updates the in-memory consent gate used before dispatching analytics. * @property deleteUserData Deletes a known user from self-hosted storage and provider integrations. * @property forgetUser Alias for deleteUserData, useful for right-to-forget UI copy. * @property startAutoTracking Installs browser listeners for configured automatic tracking. * @property getSessionId Returns the current session identifier used for new events. * @property isReady Indicates whether the tracker instance is initialized and usable. */ interface TrackerInstance { track: (name: string, properties?: Record, options?: TrackerTrackOptions) => Promise; page: (url: string, properties?: Record) => Promise; pageView: (url: string, properties?: Record) => Promise; identify: (userId: string, traits?: UserTraits) => Promise; setUserProperties: (traits: UserTraits) => Promise; flush: () => Promise; reset: () => Promise; shutdown: () => Promise; purgeExpiredData: (now?: number) => Promise; consent: (settings: ConsentSettings) => void; deleteUserData: (userId: string) => Promise; forgetUser: (userId: string) => Promise; startAutoTracking: () => () => void; getSessionId: () => string; isReady: () => boolean; } interface AnalyticsContextOptions { optional?: boolean; } interface NativeAnalyticsActions { consent: (settings: ConsentSettings) => void; deleteUserData: (userId: string) => Promise; forgetUser: (userId: string) => Promise; identify: (userId: string, traits?: UserTraits) => Promise; isReady: boolean; page: TrackerInstance["page"]; reset: TrackerInstance["reset"]; sessionId: string; track: TrackerInstance["track"]; } /** * @module ReactNativeIndex * @package @geenius/analytics/react-native * @description React Native analytics surface using native host primitives, * StyleSheet-compatible styles, accessibility labels, and testID selectors. * * Importing this barrel pulls `react` and `react-native` at module load * (the value imports below). Consumers that need the public types but * cannot resolve `react-native` at runtime (SSR, web Storybook setups, * Node test harnesses, type-only barrels) must import from the dedicated * type-only entry point: * * ```ts * import type { AnalyticsProviderProps } from "@geenius/analytics/react-native/types" * ``` * * That subpath resolves to an empty JavaScript module at runtime and * loads only the `.d.ts` declarations. See `./types.ts` and * audit-finding #214. */ /** Shared StyleSheet entries used by the native analytics components. */ declare const nativeStyles: { stack: { gap: number; padding: number; }; row: { alignItems: "center"; flexDirection: "row"; gap: number; }; title: { fontSize: number; fontWeight: "700"; }; muted: { opacity: number; }; card: { borderRadius: number; padding: number; }; state: { gap: number; }; stateAction: { borderRadius: number; padding: number; }; consentCategory: { alignItems: "center"; flexDirection: "row"; gap: number; }; skeletonLine: { borderRadius: number; opacity: number; padding: number; }; skeletonText: { opacity: number; }; }; /** Props accepted by {@link AnalyticsProvider}. */ interface AnalyticsProviderProps { config?: AnalyticsConfig; tracker?: TrackerInstance; initialConsent?: ConsentSettings | null; children?: ReactNode; } /** Options accepted by {@link useAnalyticsContext}. */ interface UseAnalyticsContextOptions extends AnalyticsContextOptions { } /** Native consent state exposed by {@link AnalyticsProvider}. */ interface AnalyticsConsentContextValue { consentSettings: ConsentSettings | null; updateConsent: (settings: ConsentSettings) => void; } /** Provides a shared analytics tracker to descendant React Native components. */ declare function AnalyticsProvider(props: AnalyticsProviderProps): ReactElement; /** Resolves the analytics tracker from context, or `null` when optional and unmounted. */ declare function useAnalyticsContext(options?: UseAnalyticsContextOptions): TrackerInstance | null; /** Reads the native consent state from the nearest analytics provider. */ declare function useAnalyticsConsent(): AnalyticsConsentContextValue | null; /** Native analytics action surface returned by {@link useAnalytics}. */ interface UseAnalyticsReturn extends NativeAnalyticsActions { } /** Returns native analytics actions bound to the context tracker (or a fresh one). */ declare function useAnalytics(config?: AnalyticsConfig): UseAnalyticsReturn; /** Fires a `page` event for `url` whenever it changes. */ declare function usePageView(url: string, config?: AnalyticsConfig): void; /** Return shape for {@link useFunnel}. */ interface UseFunnelReturn { result: FunnelResult | null; analyze: (events: AnalyticsEvent[]) => FunnelResult; } /** Provides a memoised `analyze` callback for funnel evaluation on demand. */ declare function useFunnel(name: string, steps: FunnelStep[]): UseFunnelReturn; /** Convenience hook exposing `identify` and `reset` from the active tracker. */ declare function useIdentify(config?: AnalyticsConfig): { identify: (userId: string, traits?: UserTraits) => Promise; reset: () => Promise; }; /** Loads realtime stats once via `fetcher` and exposes loading state. */ interface UseRealtimeStatsOptions { /** Poll interval in milliseconds. Defaults to 5000. Pass 0 to disable polling. */ intervalMs?: number; } declare function useRealtimeStats(fetcher?: () => Promise, options?: UseRealtimeStatsOptions): { stats: RealtimeStats | null; isLoading: boolean; error: Error | null; refresh: () => Promise; }; /** Props for {@link StatsCard}. */ interface StatsCardProps { label: string; value: string | number; change?: string; trend?: "up" | "down" | "flat"; } /** Native card displaying a labelled headline metric and optional trend. */ declare function StatsCard(props: StatsCardProps): ReactElement; /** Native card rendering a single {@link MetricSummary}. */ declare function MetricCard(props: { metric: MetricSummary; }): ReactElement; /** Native card listing chart data points as labelled rows. */ declare function ChartCard(props: { title: string; data: ChartDataPoint[]; }): ReactElement; /** Props for {@link EventTable}. */ interface EventTableProps { emptyMessage?: string; error?: Error | string | null; events: AnalyticsEvent[]; maxRows?: number; isLoading?: boolean; onRetry?: () => void; } /** Native list rendering recent analytics events with loading, error, and empty states. */ declare function EventTable(props: EventTableProps): ReactElement; /** Props for {@link TopPagesTable}. */ interface TopPagesTableProps { emptyMessage?: string; error?: Error | string | null; isLoading?: boolean; onRetry?: () => void; pages: Array<{ url: string; views: number; uniqueVisitors?: number; averageTimeMs?: number; averageTimeSeconds?: number; averageTime?: string; }>; } /** Native list of top-viewed pages with loading, error, and empty states. */ declare function TopPagesTable(props: TopPagesTableProps): ReactElement; /** Native card rendering a desktop/tablet/mobile breakdown of sessions. */ declare function DeviceBreakdown(props: { breakdown: AnalyticsDashboardData["deviceBreakdown"]; }): ReactElement; /** Native badge showing the current active-visitor count with a loading fallback. */ declare function RealtimeBadge(props: { stats: RealtimeStats | null; isLoading?: boolean; }): ReactElement; /** Scrollable native timeline of recent {@link TimelineEvent} entries. */ declare function Timeline(props: { events: TimelineEvent[]; maxVisible?: number; }): ReactElement; /** Native card rendering each step of a {@link FunnelResult} with conversion/drop-off detail. */ declare function FunnelChart(props: { result: FunnelResult; }): ReactElement; /** Props for {@link ConsentBanner}. */ interface ConsentBannerProps { initialSettings?: Partial; onAccept?: (settings: ConsentSettings) => void; onReject?: (settings: ConsentSettings) => void; onSavePreferences?: (settings: ConsentSettings) => void; show?: boolean; } /** Native consent banner with per-category switches, accept-all, save, and reject actions. */ declare function ConsentBanner(props: ConsentBannerProps): ReactElement | null; /** Widget descriptor consumed by {@link DashboardBuilder}. */ interface DashboardBuilderWidget { id: string; title: string; /** Optional pre-rendered ReactElement; if omitted, only the legend is shown. */ render?: () => ReactElement; /** Optional description rendered under the widget title. */ description?: string; } /** Layout descriptor consumed by {@link DashboardBuilder}. */ interface DashboardBuilderLayout { title: string; widgets?: DashboardBuilderWidget[]; } /** Native dashboard composition shell — renders title + widget sections with legends. */ declare function DashboardBuilder(props: { layout: DashboardBuilderLayout; }): ReactElement; /** Props for {@link AnalyticsDashboardPage}. */ interface AnalyticsDashboardPageProps { data?: AnalyticsDashboardData; emptyMessage?: string; error?: Error | string | null; isLoading?: boolean; onRetry?: () => void; recentEvents?: AnalyticsEvent[]; /** Optional chart datapoints rendered above the funnel section. */ chart?: { title: string; data: ChartDataPoint[]; }; /** Optional precomputed funnel result rendered in the conversion section. */ funnel?: FunnelResult; /** Optional timeline events rendered in the activity section. */ timeline?: TimelineEvent[]; /** Optional realtime snapshot rendered in the realtime badge. */ realtimeStats?: RealtimeStats | null; isRealtimeLoading?: boolean; } /** Native dashboard page composing the analytics widgets with loading/error/empty states. */ declare function AnalyticsDashboardPage(props: AnalyticsDashboardPageProps): ReactElement; export { type AnalyticsConfig as A, type AnalyticsConsentContextValue, AnalyticsDashboardPage, AnalyticsProvider, type AnalyticsProviderProps, type ChartDataPoint as C, ChartCard, ConsentBanner, DashboardBuilder, type DashboardBuilderLayout, type DashboardBuilderWidget, DeviceBreakdown, EventTable, type FunnelResult as F, FunnelChart, type MetricSummary as M, MetricCard, type RealtimeStats as R, RealtimeBadge, StatsCard, type StatsCardProps, type TimelineEvent as T, Timeline, TopPagesTable, type UserTraits as U, type UseAnalyticsContextOptions, type UseAnalyticsReturn, type UseFunnelReturn, type UseRealtimeStatsOptions, type AnalyticsDashboardData as a, type AnalyticsEvent as b, type ConsentSettings as c, type FunnelStep as d, type TrackerInstance as e, nativeStyles, useAnalytics, useAnalyticsConsent, useAnalyticsContext, useFunnel, useIdentify, usePageView, useRealtimeStats };