import { GeeniusError, GeeniusErrorOptions, ErrorCode } from '@geenius/errors'; import { z } from 'zod'; /** * @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; } /** * Normalized page-view payload tracked by the shared runtime. * * @property properties Optional page-view metadata such as campaign or route data. * @property duration Optional dwell time in milliseconds for the page. * @property ipAddress Optional client IP address, truncated before storage when IP masking is enabled. * @property sessionId Session identifier associated with the page view. */ interface PageView { url: string; title: string; referrer: string; properties?: Record; duration?: number; ipAddress?: string; sessionId: string; userId?: string; 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; } /** * Provider identifier supported by the shared package. */ type ProviderName = "posthog" | "mixpanel" | "google-analytics" | "plausible"; /** * Provider configuration used when registering analytics integrations. * * @property provider Provider identifier used to select the integration. * @property apiKey Provider API key, measurement ID, or equivalent identifier. */ interface ProviderConfig { provider: ProviderName; apiKey: string; host?: string; enabled?: boolean; } /** * 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; } /** * Paginated read result returned by storage adapters. * * @property items Records returned for the current page. * @property nextCursor Cursor supplied when another page is available. * @property total Optional total count when the provider can calculate one cheaply. */ interface AnalyticsReadResult { items: TRecord[]; nextCursor?: string; total?: number; } /** * Query options for reading stored analytics events. */ interface AnalyticsEventQuery { userId?: string; sessionId?: string; eventName?: string; eventType?: EventType; timeRange?: TimeRange; limit?: number; cursor?: string; } /** * Query options for reading stored page-view records. */ interface AnalyticsPageViewQuery { url?: string; userId?: string; sessionId?: string; timeRange?: TimeRange; limit?: number; cursor?: string; } /** * Query options for materializing dashboard aggregate data. */ interface AnalyticsDashboardQuery { timeRange?: TimeRange; limit?: number; cursor?: string; } /** * Query options for realtime aggregate reads. */ interface RealtimeStatsQuery { since?: number; now?: number; windowMs?: number; topPageLimit?: number; } /** * Query options for funnel aggregate reads. */ interface FunnelResultsQuery { steps: FunnelStep[]; timeRange?: TimeRange; limit?: number; } /** * Query options for cohort aggregate reads. */ interface CohortAnalysisQuery { cohortType?: "user" | "session"; intervals?: number[]; timeRange?: TimeRange; segment?: Record; } /** * Self-hosted analytics storage contract used before optional outbound provider sync. */ interface AnalyticsStorageAdapter { trackEvent(event: AnalyticsEvent): Promise; trackPageView(pageView: PageView): Promise; getEvents?(query?: AnalyticsEventQuery): Promise>; getPageViews?(query?: AnalyticsPageViewQuery): Promise>; getDashboardData?(query?: AnalyticsDashboardQuery): Promise; getRealtimeStats?(query?: RealtimeStatsQuery): Promise; getFunnelResults?(query: FunnelResultsQuery): Promise; getCohortAnalysis?(query?: CohortAnalysisQuery): Promise; identifyUser?(userId: string, traits?: UserTraits): Promise; setUserProperties?(userId: string, traits: UserTraits): Promise; flush?(): Promise; shutdown?(): Promise; purgeExpiredData?(cutoffTimestamp: number): Promise; deleteUserData?(userId: string): Promise; } /** * 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; } /** * Inclusive analytics time range used by filters and queries. */ interface TimeRange { start: number; end: 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; } /** * Privacy strategy used when sanitizing analytics payloads. */ type PrivacyMode = "mask" | "anonymize" | "redact"; /** * Privacy settings used to sanitize analytics payloads. * * @property maskedFields Field names that should be sanitized before export. */ interface PrivacySettings { mode: PrivacyMode; maskedFields: string[]; anonymizeIdentifiers: boolean; } /** * Retention datapoint for a single cohort interval. * * @property retainedUsers Number of users retained for the interval. * @property retentionRate Percentage retained at the interval boundary. */ interface CohortRetentionPoint { day: number; retainedUsers: number; retentionRate: number; } /** * Cohort bucket produced by the shared cohort analysis helpers. * * @property retained Retention datapoints for the cohort over time. */ interface CohortBucket { cohort: string; size: number; retained: CohortRetentionPoint[]; lastActivity: number; } /** * Full retention cohort analysis returned by the shared analytics helpers. * * @property intervals Day intervals included in the analysis. * @property cohorts Cohort buckets included in the analysis. */ interface CohortAnalysis { name: string; cohortType: "user" | "session"; intervals: number[]; cohorts: CohortBucket[]; generatedAt: number; } /** * Single frame in a shared session replay snapshot. * * @property deltaMs Milliseconds elapsed since the previous replay frame. */ interface SessionReplayFrame { id: string; kind: "event" | "page_view"; label: string; url: string; timestamp: number; deltaMs: number; sessionId: string; userId?: string; properties?: Record; } /** * Ordered session replay snapshot produced from tracked analytics activity. * * @property frames Ordered replay frames associated with the captured session. * @property activePages Unique page URLs touched during the session. */ interface SessionReplaySnapshot { sessionId: string; startedAt: number; endedAt: number; duration: number; frames: SessionReplayFrame[]; activePages: string[]; userId?: string; } /** * Interpolation values accepted by analytics translation helpers. */ type AnalyticsParams = Record; /** * Minimal translator contract used by package-owned analytics copy helpers. * * @param key Translation key in the analytics namespace. * @param params Optional interpolation values. * @returns Localized copy for the requested key. */ type AnalyticsTranslator = (key: string, params?: AnalyticsParams) => string; /** * Resolves an analytics translation key against the package fallback table. * * @param key Translation key in the analytics namespace. * @param params Optional interpolation values. * @returns Localized analytics copy. */ declare function translateAnalytics(key: string, params?: AnalyticsParams): string; /** * Resolves a pluralized analytics translation with fallback to the base key. * * @param key Base translation key without the plural suffix. * @param count Count used for plural selection and interpolation. * @param params Additional interpolation values. * @returns Localized plural copy. */ declare function pluralizeAnalytics(key: string, count: number, params?: AnalyticsParams): string; /** * Returns a localized label for a normalized analytics device token. * * @param device Device token from analytics payloads. * @param translator Optional host translator used before the fallback table. * @returns Localized or humanized device label. */ declare function getAnalyticsDeviceLabel(device: string, translator?: AnalyticsTranslator): string; /** * Formats a timestamp-like value for compact analytics UI surfaces. * * @param value Date-compatible value to render. * @param locale Optional BCP 47 locale override. * @returns Locale-aware short time string. */ declare function formatAnalyticsTime(value: number | string, locale?: string): string; /** * Inputs used to build SEO metadata for analytics page compositions. */ interface BuildAnalyticsSeoMetaOptions { title: string; description: string; path: string; keywords: string[]; } /** * SEO metadata emitted by the shared analytics page metadata builder. */ interface SEOMeta { title: string; description: string; canonical: string; keywords: string[]; image: { url: string; alt: string; }; type: "website"; jsonLd: Record; } /** * Builds canonical SEO metadata for analytics dashboard pages. * * @param options Page title, description, route path, and keyword list. * @returns Metadata object containing canonical URL, Open Graph image, and JSON-LD. */ declare function buildAnalyticsSeoMeta(options: BuildAnalyticsSeoMetaOptions): SEOMeta; /** * @module Cohorts * @package @geenius/analytics * @description Shared cohort-analysis helpers used by the runtime variants and * Convex queries to transform event streams into retention-oriented data sets. */ /** * Optional inputs that tailor shared cohort analysis output. * * @property name Optional label applied to the generated cohort report. * @property intervals Retention checkpoints, in days, used when computing cohort curves. * @property cohortType Identity model used to group records as users or sessions. */ interface CohortAnalysisOptions { name?: string; intervals?: number[]; cohortType?: "user" | "session"; } type BehavioralCohortRule = { kind: "event"; event: string; } | { kind: "trait"; field: string; value: unknown; } | { kind: "activity"; minEvents: number; since?: number; }; interface BehavioralCohortDefinition { id: string; name: string; rules: BehavioralCohortRule[]; match?: "all" | "any"; } interface BehavioralCohortResult { id: string; name: string; size: number; identities: string[]; eventCount: number; conversionRate: number; lastActivity: number; } interface CohortComparisonResult { baselineId: string; comparisonId: string; sizeDelta: number; eventCountDelta: number; conversionRateDelta: number; lastActivityDelta: number; } /** * Analyzes analytics events into retention-oriented cohort buckets. * * @param events Analytics events or page-derived events to group into cohorts. * @param options Optional naming, interval, and identity settings for the analysis. * @returns A normalized cohort analysis model ready for Convex storage and UI rendering. */ declare function analyzeCohorts(events: AnalyticsEvent[], options?: CohortAnalysisOptions): CohortAnalysis; /** * Converts retained-user counts into retention points for a cohort bucket. * * @param size Total size of the cohort bucket. * @param points Raw retained-user counts by day. * @returns Retention points with computed percentages for each interval. */ declare function createCohortRetentionPoints(size: number, points: Array<{ day: number; retainedUsers: number; }>): CohortRetentionPoint[]; declare function createBehavioralCohortDefinition(definition: BehavioralCohortDefinition): BehavioralCohortDefinition; declare function analyzeBehavioralCohorts(events: AnalyticsEvent[], definitions: BehavioralCohortDefinition[], options?: Pick): BehavioralCohortResult[]; declare function compareBehavioralCohorts(baseline: BehavioralCohortResult, comparison: BehavioralCohortResult): CohortComparisonResult; /** * @module AnalyticsConfig * @package @geenius/analytics * @description Provides the shared analytics configuration builder and the * default environment presets used by the tracker and provider integrations. * The fluent builder keeps package consumers on a typed, privacy-aware config path. */ type AnalyticsConfigurationBundle = { analytics: AnalyticsConfig; providers: Partial>; storage?: AnalyticsStorageAdapter | AnalyticsStorageAdapter[]; }; /** * Fluent builder for shared analytics configuration and provider registration. * * @example * ```ts * const config = createAnalyticsConfig() * .withProvider('posthog', { provider: 'posthog', apiKey: 'phc_xxx' }) * .withPageTracking(true) * .withClickTracking(true) * .build() * ``` */ declare class AnalyticsConfigBuilder { private config; private providers; private storage?; /** * Sets whether shared trackers should record page-view events. * * @param enabled Whether page-view tracking is enabled. * @returns The current builder instance for fluent chaining. */ withPageTracking(enabled: boolean): this; /** * Sets whether shared trackers should record click events. * * @param enabled Whether click tracking is enabled. * @returns The current builder instance for fluent chaining. */ withClickTracking(enabled: boolean): this; /** * Sets whether shared trackers should record global browser error events. * * @param enabled Whether browser error tracking is enabled. * @returns The current builder instance for fluent chaining. */ withErrorTracking(enabled: boolean): this; /** * Sets whether shared trackers should record browser performance metrics. * * @param enabled Whether performance tracking is enabled. * @returns The current builder instance for fluent chaining. */ withPerformanceTracking(enabled: boolean): this; /** * Sets whether shared trackers should respect the browser Do Not Track signal. * * @param enabled Whether Do Not Track should suppress analytics collection. * @returns The current builder instance for fluent chaining. */ withRespectDnt(enabled: boolean): this; /** * Sets the analytics session timeout in milliseconds. * * @param ms Session timeout in milliseconds. * @returns The current builder instance for fluent chaining. */ withSessionTimeout(ms: number): this; /** * Sets the number of queued track/page payloads that should trigger a flush. * * @param size Queue size threshold; values below 1 are normalized by the tracker. * @returns The current builder instance for fluent chaining. */ withBatchSize(size: number): this; /** * Sets the interval in milliseconds used to flush queued analytics payloads. * * @param ms Flush interval in milliseconds; zero disables interval flushing. * @returns The current builder instance for fluent chaining. */ withFlushInterval(ms: number): this; /** * Sets a per-event-name throttle window for custom analytics events. * * @param ms Throttle window in milliseconds; zero disables throttling. * @returns The current builder instance for fluent chaining. */ withEventThrottle(ms: number): this; /** * Enables or disables durable persistence for queued offline analytics payloads. * * @param enabled Whether queued payloads should be persisted locally. * @returns The current builder instance for fluent chaining. */ withOfflineQueuePersistence(enabled: boolean): this; /** * Sets the browser storage key used for the durable offline queue. * * @param key Storage key used to persist queued analytics payloads. * @returns The current builder instance for fluent chaining. */ withOfflineQueueKey(key: string): this; /** * Enables or disables automatic queue replay when the browser reconnects. * * @param enabled Whether queued payloads should flush on reconnect. * @returns The current builder instance for fluent chaining. */ withReplayOnReconnect(enabled: boolean): this; /** * Sets the retention window used by storage/provider purge hooks. * * @param days Number of days to retain analytics records and aggregates. * @returns The current builder instance for fluent chaining. */ withRetentionDays(days: number): this; /** * Adds routes that should be excluded from automatic page tracking. * * @param paths Route prefixes that should be skipped by the tracker. * @returns The current builder instance for fluent chaining. */ withExcludePaths(paths: string[]): this; /** * Enables or disables verbose analytics debug behavior. * * @param enabled Whether debug behavior should be enabled. * @returns The current builder instance for fluent chaining. */ withDebug(enabled: boolean): this; /** * Enables or disables masking of sensitive payload values. * * @param enabled Whether PII masking is enabled. * @returns The current builder instance for fluent chaining. */ withMaskPii(enabled: boolean): this; /** * Enables or disables IP truncation for event and page-view payloads. * * @param enabled Whether IP-shaped fields should be truncated before dispatch. * @returns The current builder instance for fluent chaining. */ withIpMasking(enabled: boolean): this; /** * Enables or disables anonymization of identifiers and payload strings. * * @param enabled Whether anonymization is enabled. * @returns The current builder instance for fluent chaining. */ withAnonymize(enabled: boolean): this; /** * Registers a provider configuration in the current bundle. * * @param name Provider name used as the registry key. * @param config Provider configuration associated with the given name. * @returns The current builder instance for fluent chaining. */ withProvider(name: ProviderName, config: ProviderConfig): this; /** * Registers one or more self-hosted storage adapters that persist sanitized * analytics data before optional third-party sync. * * @param storage Storage adapter or adapters used by the tracker. * @returns The current builder instance for fluent chaining. */ withStorage(storage: AnalyticsStorageAdapter | AnalyticsStorageAdapter[]): this; /** * Produces the final analytics configuration bundle. * * @returns The analytics settings plus provider registry for tracker creation. */ build(): AnalyticsConfigurationBundle; } /** * Creates a new fluent analytics configuration builder. * * @returns A fresh analytics configuration builder instance. */ declare function createAnalyticsConfig(): AnalyticsConfigBuilder; /** * Default analytics configuration bundles for common runtime environments. */ declare const defaultConfigs: Record<"development" | "production" | "testing", AnalyticsConfigurationBundle>; /** * Returns the default analytics configuration bundle for the requested environment. * * @param env Runtime environment name used to select the preset. * @returns The analytics configuration bundle for the requested environment. */ declare function getDefaultConfig(env?: "development" | "production" | "testing"): AnalyticsConfigurationBundle; /** * @module Constants * @package @geenius/analytics * @description Shared constants consumed by the tracker, UI variants, and * Storybook review surfaces. These values define provider names, polling * defaults, batch limits, and shared visual affordances. */ /** Supported analytics provider identifiers shared across all package variants. */ declare const PROVIDERS: readonly ["posthog", "mixpanel", "google-analytics", "plausible"]; /** Default inactivity window, in milliseconds, used when rolling analytics sessions. */ declare const DEFAULT_SESSION_TIMEOUT: number; /** Default polling interval, in milliseconds, for realtime analytics refreshes. */ declare const DEFAULT_REALTIME_INTERVAL = 5000; /** Maximum number of analytics events to send in a single provider batch. */ declare const MAX_EVENTS_PER_BATCH = 100; /** Maximum number of steps supported when evaluating a funnel definition. */ declare const MAX_FUNNEL_STEPS = 20; /** Shared metric formatting modes consumed by the dashboard and card components. */ declare const METRIC_FORMATS: { readonly number: "number"; readonly percent: "percent"; readonly duration: "duration"; readonly currency: "currency"; }; /** Shared iconography used by review surfaces and event-oriented UI components. */ declare const EVENT_ICONS: Record; /** Semantic trend colors shared by both Tailwind and vanilla-CSS renderers. */ declare const TREND_COLORS: { readonly up: "var(--gn-success)"; readonly down: "var(--gn-danger)"; readonly flat: "var(--gn-text-secondary)"; }; /** * @module Dashboard * @package @geenius/analytics * @description Shared dashboard widget contracts and aggregation helpers used * by the React, SolidJS, and Storybook surfaces. This module normalizes raw * analytics data into the consistent dashboard model exposed by the package. */ /** Supported dashboard widget kinds rendered by the shared analytics dashboards. */ type DashboardWidgetKind = "metric" | "chart" | "top-pages" | "device-breakdown" | "events" | "funnel" | "realtime" | "cohort" | "replay"; /** * Shared metadata present on every dashboard widget model. * * @property id Stable widget identifier used for rendering and diffing. * @property kind Widget kind that determines the renderer and data payload. * @property title Human-readable widget title shown in dashboards and Storybook fixtures. * @property description Optional supporting description for the widget card. * @property span Optional grid span used by composed dashboard layouts. */ interface DashboardWidgetBase { id: string; kind: DashboardWidgetKind; title: string; description?: string; span?: 1 | 2 | 3; } /** * Dashboard widget that renders a single summary metric. * * @property metric Metric payload shown by metric-focused dashboard cards. */ interface MetricDashboardWidget extends DashboardWidgetBase { kind: "metric"; metric: MetricSummary; } /** * Dashboard widget that renders a chart-backed series. * * @property chartType Optional visualization type used by the chart renderer. * @property data Ordered chart points consumed by the visual component. */ interface ChartDashboardWidget extends DashboardWidgetBase { kind: "chart"; chartType?: "bar" | "line"; data: ChartDataPoint[]; } /** * Dashboard widget that lists the top-performing pages. * * @property pages Ranked page summary entries derived from analytics traffic. */ interface TopPagesDashboardWidget extends DashboardWidgetBase { kind: "top-pages"; pages: AnalyticsDashboardData["topPages"]; } /** * Dashboard widget that summarizes device distribution. * * @property breakdown Device-count aggregate broken out by desktop, tablet, and mobile. */ interface DeviceBreakdownDashboardWidget extends DashboardWidgetBase { kind: "device-breakdown"; breakdown: AnalyticsDashboardData["deviceBreakdown"]; } /** * Dashboard widget that renders a recent-event stream. * * @property events Event rows shown in the widget. * @property maxRows Optional row cap used by compact dashboard layouts. */ interface EventDashboardWidget extends DashboardWidgetBase { kind: "events"; events: AnalyticsEvent[]; maxRows?: number; } /** * Dashboard widget that renders funnel conversion output. * * @property result Funnel analysis payload rendered by the widget. */ interface FunnelDashboardWidget extends DashboardWidgetBase { kind: "funnel"; result: FunnelResult; } /** * Dashboard widget that renders realtime activity output. * * @property stats Latest realtime analytics snapshot. * @property isLoading Optional loading state for live polling UIs. */ interface RealtimeDashboardWidget extends DashboardWidgetBase { kind: "realtime"; stats: RealtimeStats | null; isLoading?: boolean; } /** * Dashboard widget that renders cohort-retention output. * * @property analysis Cohort analysis payload rendered by the widget. */ interface CohortDashboardWidget extends DashboardWidgetBase { kind: "cohort"; analysis: CohortAnalysis; } /** * Dashboard widget that previews a session-replay snapshot. * * @property replay Session replay material used for the widget preview. */ interface ReplayDashboardWidget extends DashboardWidgetBase { kind: "replay"; replay: SessionReplaySnapshot; } /** Union of all dashboard widgets supported by the shared dashboard model. */ type DashboardWidget = MetricDashboardWidget | ChartDashboardWidget | TopPagesDashboardWidget | DeviceBreakdownDashboardWidget | EventDashboardWidget | FunnelDashboardWidget | RealtimeDashboardWidget | CohortDashboardWidget | ReplayDashboardWidget; /** * Shared dashboard layout consumed by the React, SolidJS, and Storybook surfaces. * * @property title Optional dashboard heading. * @property description Optional supporting copy describing the dashboard purpose. * @property widgets Ordered widget collection rendered by the dashboard builders. */ interface DashboardLayout { title?: string; description?: string; widgets: DashboardWidget[]; } /** Fluent builder for composing analytics dashboard layouts in user code and tests. */ declare class DashboardBuilder { private readonly widgets; private title?; private description?; /** * Sets the dashboard title and optional description. * * @param title Primary heading for the dashboard layout. * @param description Optional supporting description shown with the heading. * @returns The same builder instance for fluent chaining. */ withTitle(title: string, description?: string): this; /** * Adds a metric widget to the layout. * * @param widget Metric widget definition to append. * @returns The same builder instance for fluent chaining. */ metric(widget: MetricDashboardWidget): this; /** * Adds a chart widget to the layout. * * @param widget Chart widget definition to append. * @returns The same builder instance for fluent chaining. */ chart(widget: ChartDashboardWidget): this; /** * Adds a top-pages widget to the layout. * * @param widget Top-pages widget definition to append. * @returns The same builder instance for fluent chaining. */ topPages(widget: TopPagesDashboardWidget): this; /** * Adds a device-breakdown widget to the layout. * * @param widget Device-breakdown widget definition to append. * @returns The same builder instance for fluent chaining. */ deviceBreakdown(widget: DeviceBreakdownDashboardWidget): this; /** * Adds an event-stream widget to the layout. * * @param widget Event widget definition to append. * @returns The same builder instance for fluent chaining. */ events(widget: EventDashboardWidget): this; /** * Adds a funnel widget to the layout. * * @param widget Funnel widget definition to append. * @returns The same builder instance for fluent chaining. */ funnel(widget: FunnelDashboardWidget): this; /** * Adds a realtime widget to the layout. * * @param widget Realtime widget definition to append. * @returns The same builder instance for fluent chaining. */ realtime(widget: RealtimeDashboardWidget): this; /** * Adds a cohort-analysis widget to the layout. * * @param widget Cohort widget definition to append. * @returns The same builder instance for fluent chaining. */ cohort(widget: CohortDashboardWidget): this; /** * Adds a replay widget to the layout. * * @param widget Replay widget definition to append. * @returns The same builder instance for fluent chaining. */ replay(widget: ReplayDashboardWidget): this; /** * Finalizes the composed dashboard layout. * * @returns Dashboard layout containing a defensive copy of the accumulated widgets. */ build(): DashboardLayout; } /** * Creates a fluent dashboard builder for composing layout definitions. * * @returns New dashboard builder instance with no widgets configured yet. */ declare function createDashboardBuilder(): DashboardBuilder; /** * Creates a dashboard layout from a widget array and optional metadata. * * @param widgets Ordered widgets that should appear in the dashboard layout. * @param meta Optional dashboard title and description metadata. * @returns Shared dashboard layout ready for framework-specific rendering. */ declare function createDashboardLayout(widgets: DashboardWidget[], meta?: Omit): DashboardLayout; /** * Convex analytics-event row shape consumed when normalizing packaged query results. * * @property event Event name captured by the analytics provider. * @property type Event type label used to derive the shared event taxonomy. * @property properties Optional JSON-safe analytics properties. * @property url URL associated with the event. * @property referrer Optional referrer captured alongside the event. * @property userId Optional user identity associated with the event. * @property device Optional device metadata captured for the event. * @property timestamp Event timestamp in milliseconds since the Unix epoch. * @property sessionId Session identifier associated with the event. */ interface ConvexAnalyticsEvent { event: string; type: string; properties?: Record; url: string; referrer?: string; userId?: string; device?: { browser: string; os: string; device: "desktop" | "tablet" | "mobile"; screenWidth: number; screenHeight: number; language: string; }; timestamp: number; sessionId: string; } /** * Normalizes packaged Convex event rows into the shared analytics-event model. * * @param events Convex analytics rows returned by packaged queries. * @returns Shared analytics events ready for UI and helper consumption. */ declare function normalizeAnalyticsEvents(events: ConvexAnalyticsEvent[]): AnalyticsEvent[]; /** * Builds the shared dashboard-data summary from raw page views and events. * * @param options Source data used to derive dashboard metrics and breakdowns. * @returns Aggregated dashboard data used by the published UI variants. */ declare function buildAnalyticsDashboardData(options: { pageViews?: Array<{ url: string; title?: string; referrer?: string; duration?: number; sessionId: string; userId?: string; timestamp: number; }>; events?: ConvexAnalyticsEvent[]; topPages?: AnalyticsDashboardData["topPages"]; deviceBreakdown?: AnalyticsDashboardData["deviceBreakdown"]; }): AnalyticsDashboardData; /** * Builds a realtime dashboard snapshot from recent analytics activity. * * @param options Source records and window controls used to derive live metrics. * @returns Realtime stats populated with sessions, rate, conversions, and devices. */ declare function buildRealtimeStats(options?: { events?: ConvexAnalyticsEvent[]; pageViews?: Array<{ url: string; sessionId: string; userId?: string; timestamp: number; }>; now?: number; windowMs?: number; conversionEventNames?: string[]; topPageLimit?: number; }): RealtimeStats; /** * @module errors * @package @geenius/analytics * @description Defines the typed analytics error hierarchy shared across every * package variant. These errors wrap the published `@geenius/errors` * primitives so consumers can discriminate analytics-specific failures. */ /** * Options accepted by the analytics error hierarchy. * * @property code Optional error code override for specialised analytics errors. */ interface AnalyticsErrorOptions extends GeeniusErrorOptions { code?: ErrorCode; } /** * Base error for analytics-specific failures. * * @param options Structured error metadata passed to the shared Geenius base error. * @returns A typed analytics error instance. */ declare class AnalyticsError extends GeeniusError { constructor(options: AnalyticsErrorOptions); } /** * Error thrown when analytics configuration is invalid or incomplete. * * @param options Structured error metadata excluding fixed configuration fields. * @returns A typed analytics configuration error. */ declare class AnalyticsConfigurationError extends AnalyticsError { constructor(options: Omit); } /** * Error thrown when analytics context is accessed outside a provider boundary. * * @param options Structured error metadata excluding fixed context fields. * @returns A typed analytics context error. */ declare class AnalyticsContextError extends AnalyticsError { constructor(options: Omit); } /** * Error thrown when an upstream analytics provider fails or is unavailable. * * @param options Structured error metadata excluding fixed provider fields. * @returns A typed analytics provider error. */ declare class AnalyticsProviderError extends AnalyticsError { constructor(options: Omit); } /** * Error thrown when a launch adapter cannot support a relational or provider- * specific operation without lying about semantics. * * @param options Structured error metadata excluding fixed adapter fields. * @returns A typed unsupported-adapter error. */ declare class AdapterUnsupportedError extends AnalyticsError { constructor(options: Omit); } /** * @module Funnel * @package @geenius/analytics * @description Shared funnel-analysis helpers used by framework hooks, * primitives, and backend consumers to derive conversion performance from raw * analytics events. */ /** * Analyzes analytics events against an ordered funnel definition. * * @param events Analytics events to evaluate against the supplied steps. * @param steps Ordered funnel definition describing the expected conversion path. * @param name Human-readable funnel name used in the returned result. * @returns Funnel analysis data including step counts, drop-off, and conversion rates. */ declare function analyzeFunnel(events: AnalyticsEvent[], steps: FunnelStep[], name?: string): FunnelResult; /** * Creates a typed funnel-step array from inline step definitions. * * @param steps Funnel-step definitions in evaluation order. * @returns The supplied steps as a typed funnel-step array. */ declare function createFunnelSteps(...steps: Array<{ name: string; event: string; properties?: Record; }>): FunnelStep[]; /** * @module Privacy * @package @geenius/analytics * @description Privacy helpers for masking, anonymizing, or redacting * analytics payloads before they leave the shared runtime. These helpers power * tracker-level PII controls across all published variants. */ declare function hashString(value: string): string; declare function maskString(value: string): string; /** * Sanitizes a generic object by masking, anonymizing, or redacting sensitive fields. * * @param value Object to sanitize before transport or storage. * @param mode Sanitization strategy to apply to sensitive fields and nested values. * @returns A sanitized copy of the supplied object. */ declare function sanitizeObject(value: Record, mode?: PrivacyMode): Record; /** * Sanitizes arbitrary user traits while preserving the published user-traits shape. * * @param traits Optional user traits to sanitize. * @param mode Sanitization strategy to apply to nested values. * @returns A sanitized copy of the supplied traits, or `undefined`. */ declare function sanitizeUserTraits(traits: UserTraits | undefined, mode?: PrivacyMode): UserTraits | undefined; /** * Sanitizes an analytics event payload before it is dispatched to providers. * * @param event Analytics event to sanitize. * @param mode Sanitization strategy to apply to event identifiers and properties. * @returns A sanitized analytics event payload. */ declare function sanitizeAnalyticsEvent(event: AnalyticsEvent, mode?: PrivacyMode): AnalyticsEvent; /** * Sanitizes a page-view-like payload while preserving the incoming object shape. * * @param pageView Page-view record to sanitize. * @param mode Sanitization strategy to apply to URLs, referrers, and user identity. * @returns A sanitized copy of the supplied page-view object. */ declare function sanitizePageView; }>(pageView: T, mode?: PrivacyMode): T; /** * Reports whether an object contains keys treated as privacy-sensitive. * * @param value Object to inspect. * @returns `true` when a known sensitive key is present. */ declare function hasSensitiveKeys(value: Record): boolean; /** * Reports whether browser-level Do Not Track is enabled. * * @returns `true` when the current navigator advertises DNT. */ declare function isDoNotTrackEnabled(): boolean; /** * Builds a canonical consent settings payload with the public category names. * * @param overrides Optional category overrides for the consent payload. * @returns Consent settings with essential enabled and unset categories denied. */ declare function createConsentSettings(overrides?: Partial): ConsentSettings; /** * Checks whether a consent category is granted. * * @param settings Current consent settings, or `null` when not recorded. * @param category Category to check. * @returns `true` when the category is granted. */ declare function hasConsentFor(settings: ConsentSettings | null | undefined, category: "essential" | "analytics" | "marketing" | "personalization"): boolean; /** * Determines whether a timestamp is older than the configured retention window. * * @param timestamp Event timestamp in milliseconds. * @param retentionDays Number of days to retain data. * @param now Current timestamp used for deterministic tests. * @returns `true` when the record should be purged. */ declare function shouldPurgeByRetention(timestamp: number, retentionDays: number, now?: number): boolean; /** * Computes the oldest timestamp allowed by a retention window. * * @param retentionDays Number of days analytics data should be retained. * @param now Current timestamp used for deterministic tests. * @returns Cutoff timestamp, or `null` when no retention window is configured. */ declare function getRetentionCutoffTimestamp(retentionDays: number | undefined, now?: number): number | null; /** * Filters event and page-view records to the configured retention window. * * @param records Timestamped analytics records to filter. * @param retentionDays Number of days analytics data should be retained. * @param now Current timestamp used for deterministic tests. * @returns Records that are still inside the retention window. */ declare function filterRetainedAnalyticsRecords(records: readonly T[], retentionDays: number | undefined, now?: number): T[]; type RetentionAggregateTimestampKey = "timestamp" | "generatedAt" | "lastUpdated" | "analyzedAt" | "lastActivity"; type RetentionAggregate = Partial>; /** * Filters aggregate snapshots to the configured retention window. * * Aggregates without a known timestamp are preserved because the shared runtime * cannot prove they are expired. * * @param aggregates Aggregate snapshots to filter. * @param retentionDays Number of days analytics data should be retained. * @param now Current timestamp used for deterministic tests. * @returns Aggregates that are still inside the retention window. */ declare function filterRetainedAnalyticsAggregates(aggregates: readonly T[], retentionDays: number | undefined, now?: number): T[]; /** * Truncates an IPv4 or IPv6 address for analytics storage. * * @param ip Address to truncate. * @returns Truncated IP address, or the original value when unsupported. */ declare function truncateIpAddress(ip: string): string; /** * Produces a stable pseudonymous identifier for analytics records. * * @param value Source identifier to pseudonymize. * @param prefix Prefix used for the returned identifier. * @returns Stable pseudonymous identifier. */ declare function pseudonymizeIdentifier(value: string, prefix?: string): string; /** * Convenience object that groups the shared privacy helpers under one namespace. */ declare const privacyUtils: { sanitizeObject: typeof sanitizeObject; sanitizeUserTraits: typeof sanitizeUserTraits; sanitizeAnalyticsEvent: typeof sanitizeAnalyticsEvent; sanitizePageView: typeof sanitizePageView; hasSensitiveKeys: typeof hasSensitiveKeys; isDoNotTrackEnabled: typeof isDoNotTrackEnabled; createConsentSettings: typeof createConsentSettings; hasConsentFor: typeof hasConsentFor; shouldPurgeByRetention: typeof shouldPurgeByRetention; getRetentionCutoffTimestamp: typeof getRetentionCutoffTimestamp; filterRetainedAnalyticsRecords: typeof filterRetainedAnalyticsRecords; filterRetainedAnalyticsAggregates: typeof filterRetainedAnalyticsAggregates; truncateIpAddress: typeof truncateIpAddress; hashString: typeof hashString; maskString: typeof maskString; pseudonymizeIdentifier: typeof pseudonymizeIdentifier; }; /** * @module AnalyticsProviderInterface * @package @geenius/analytics * @description Defines the provider contract and base implementation used by * all shared analytics provider integrations. These types keep the tracker * runtime provider-agnostic while still supporting provider-specific setup. */ /** * Provider name token supported by the shared analytics package. */ type AnalyticsProviderName = ProviderName; /** * Provider-specific configuration required to initialize an analytics client. * * @property provider Provider identifier used to select the integration. * @property apiKey Provider API key, measurement ID, or equivalent identifier. * @property host Optional host override for self-hosted analytics backends. */ interface AnalyticsProviderConfig extends AnalyticsConfig { provider: AnalyticsProviderName; apiKey: string; host?: string; } /** * Contract implemented by all analytics providers used by the shared tracker. * * @property name Stable provider identifier exposed by the implementation. */ interface AnalyticsProvider { readonly name: AnalyticsProviderName; init(config: AnalyticsProviderConfig): void; trackEvent(event: AnalyticsEvent): Promise; trackPageView(pageView: PageView): Promise; identify(userId: string, traits?: UserTraits): Promise; setUserProperties(userId: string, traits: UserTraits): Promise; flush(): Promise; reset(): Promise; shutdown(): Promise; purgeExpiredData?(cutoffTimestamp: number): Promise; deleteUserData?(userId: string): Promise; } /** * Base class that stores configuration and supplies common provider defaults. */ declare abstract class BaseAnalyticsProvider implements AnalyticsProvider { abstract readonly name: AnalyticsProviderName; protected config: AnalyticsProviderConfig | null; /** * Stores the provider configuration for later event and identity calls. * * @param config Provider configuration for the current integration instance. * @returns Nothing. */ init(config: AnalyticsProviderConfig): void; /** * Returns the provider configuration or throws when initialization was skipped. * * @returns The previously stored provider configuration. * @throws {AnalyticsConfigurationError} Thrown when the provider was used before initialization. */ protected getRequiredConfig(): AnalyticsProviderConfig; abstract trackEvent(event: AnalyticsEvent): Promise; abstract trackPageView(pageView: PageView): Promise; /** * Identifies a user with optional trait metadata. Providers may override this * no-op default when they support identity calls. * * @param _userId User identifier associated with the current analytics subject. * @param _traits Optional user traits supplied to the provider. * @returns Nothing. */ identify(_userId: string, _traits?: UserTraits): Promise; /** * Updates provider-side user properties. Providers may override this no-op * default when they support profile traits separate from identify calls. * * @param _userId User identifier whose profile should be updated. * @param _traits User traits to attach to the provider profile. * @returns Nothing. */ setUserProperties(_userId: string, _traits: UserTraits): Promise; /** * Flushes any provider-owned queue. Providers may override this no-op default * when their SDK buffers analytics payloads. * * @returns Nothing. */ flush(): Promise; /** * Clears provider session state. Providers may override this no-op default * when they support resetting their local client state. * * @returns Nothing. */ reset(): Promise; /** * Shuts down provider-owned resources after the shared tracker has flushed. * * @returns Nothing. */ shutdown(): Promise; /** * Reports that durable provider retention purge is not available. * * Browser analytics SDKs generally cannot delete historical provider records * from the client. Providers that support a real server-side purge should * override this method instead of inheriting the typed unsupported error. * * @param cutoffTimestamp Oldest retained record timestamp in milliseconds. * @returns Nothing when an overriding provider supports the purge. * @throws {AdapterUnsupportedError} Thrown when the provider cannot safely purge durable data. */ purgeExpiredData(cutoffTimestamp: number): Promise; /** * Reports that durable provider user deletion is not available. * * Browser analytics SDKs can reset local identity state, but durable * provider-side deletion requires a server-authorized data deletion endpoint. * Providers that implement such an endpoint should override this method. * * @param userId User identifier to delete from the provider. * @returns Nothing when an overriding provider supports deletion. * @throws {AdapterUnsupportedError} Thrown when the provider cannot safely delete durable data. */ deleteUserData(userId: string): Promise; } /** * @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; } } /** * Google Analytics 4 provider backed by the browser `gtag.js` runtime. */ declare class GoogleAnalyticsProvider extends BaseAnalyticsProvider { readonly name: "google-analytics"; private initialized; private scriptSelector; /** * Initializes GA4 by injecting the `gtag.js` script and configuring the property. * * @param config Provider configuration containing the GA measurement ID. * @returns Nothing. */ init(config: AnalyticsProviderConfig): void; /** * Sends a shared analytics event to GA4. * * @param event Shared analytics event payload. * @returns Nothing. */ trackEvent(event: AnalyticsEvent): Promise; /** * Sends a page-view payload to GA4. * * @param pageView Shared page-view payload. * @returns Nothing. */ trackPageView(pageView: PageView): Promise; /** * Associates the current browser session with a user identifier and traits. * * @param userId Stable application user identifier. * @param traits Optional user properties forwarded to GA4. * @returns Nothing. */ identify(userId: string, traits?: UserTraits): Promise; /** * Updates GA4 user properties for the current user association. * * @param _userId Stable application user identifier, already sent via identify. * @param traits User properties forwarded to GA4. * @returns Nothing. */ setUserProperties(_userId: string, traits: UserTraits): Promise; /** * Clears the current GA4 user association. * * @returns Nothing. */ reset(): Promise; } /** * @module MixpanelProvider * @package @geenius/analytics * @description Implements the shared Mixpanel provider using the optional * `mixpanel-browser` client. The provider lazily initializes Mixpanel so * consumers only load the dependency when configured. */ /** * Mixpanel analytics provider backed by the optional browser tracker client. */ declare class MixpanelProvider extends BaseAnalyticsProvider { readonly name: "mixpanel"; private mixpanel; /** * Stores the Mixpanel configuration for later lazy client initialization. * * @param config Provider configuration containing the Mixpanel project token. * @returns Nothing. */ init(config: AnalyticsProviderConfig): void; private getClient; /** * Sends a shared analytics event to Mixpanel. * * @param event Shared analytics event payload. * @returns Nothing. */ trackEvent(event: AnalyticsEvent): Promise; /** * Sends a page-view payload to Mixpanel. * * @param pageView Shared page-view payload. * @returns Nothing. */ trackPageView(pageView: PageView): Promise; /** * Identifies the current user and syncs optional traits to Mixpanel People. * * @param userId Stable application user identifier. * @param traits Optional user traits forwarded to Mixpanel. * @returns Nothing. */ identify(userId: string, traits?: UserTraits): Promise; /** * Updates Mixpanel People traits for an already identified user. * * @param userId Stable application user identifier. * @param traits User traits forwarded to Mixpanel People. * @returns Nothing. */ setUserProperties(userId: string, traits: UserTraits): Promise; /** * Resets the Mixpanel client identity and local state. * * @returns Nothing. */ reset(): Promise; } /** * @module PlausibleProvider * @package @geenius/analytics * @description Plausible analytics provider. Posts events directly to * Plausible's `/api/event` endpoint (https://plausible.io/docs/events-api). * No external client library — the deprecated `plausible-tracker` npm package * is no longer required. */ /** * Plausible analytics provider backed by the native Plausible Events API. * Posts events directly via fetch — no third-party wrapper required. */ declare class PlausibleProvider extends BaseAnalyticsProvider { readonly name: "plausible"; /** * Stores the Plausible configuration for event dispatch. * * @param config Provider configuration. `apiKey` is the Plausible domain * (e.g. `"geenius.dev"`). `host` overrides the default API host for * self-hosted Plausible instances. */ init(config: AnalyticsProviderConfig): void; private send; private isLocalhost; /** * Sends a shared analytics event to Plausible via the Events API. * * @param event Shared analytics event payload. */ trackEvent(event: AnalyticsEvent): Promise; /** * Sends a page-view payload to Plausible via the Events API. * * @param pageView Shared page-view payload. */ trackPageView(pageView: PageView): Promise; } /** * @module PostHogProvider * @package @geenius/analytics * @description Implements the shared PostHog provider using the optional * `posthog-js` client. The provider lazily initializes PostHog and exposes the * feature-flag helpers needed by analytics-driven product surfaces. */ /** * PostHog analytics provider backed by the optional browser tracker client. */ declare class PostHogProvider extends BaseAnalyticsProvider { readonly name: "posthog"; private posthog; /** * Stores the PostHog configuration for later lazy client initialization. * * @param config Provider configuration containing the PostHog project key. * @returns Nothing. */ init(config: AnalyticsProviderConfig): void; private getClient; /** * Sends a shared analytics event to PostHog. * * @param event Shared analytics event payload. * @returns Nothing. */ trackEvent(event: AnalyticsEvent): Promise; /** * Sends a page-view payload to PostHog. * * @param pageView Shared page-view payload. * @returns Nothing. */ trackPageView(pageView: PageView): Promise; /** * Associates the current browser session with a user identifier and traits. * * @param userId Stable application user identifier. * @param traits Optional user traits forwarded to PostHog. * @returns Nothing. */ identify(userId: string, traits?: UserTraits): Promise; /** * Updates the current PostHog profile traits for an already identified user. * * @param userId Stable application user identifier. * @param traits User traits forwarded to PostHog. * @returns Nothing. */ setUserProperties(userId: string, traits: UserTraits): Promise; /** * Resets the PostHog client identity and local state. * * @returns Nothing. */ reset(): Promise; /** * Checks whether a PostHog feature flag is enabled for the current subject. * * @param flagKey Feature flag key to resolve. * @returns `true` when PostHog reports the flag as enabled. */ isFeatureEnabled(flagKey: string): Promise; /** * Returns the current PostHog feature flag payload for the supplied key. * * @param flagKey Feature flag key to resolve. * @returns The feature flag payload when PostHog has one for the current subject. */ getFeatureFlag(flagKey: string): Promise; /** * Registers a callback that runs whenever PostHog refreshes feature flags. * * @param callback Callback invoked with the list of active feature flags. * @returns Nothing. */ onFeatureFlags(callback: (flags: string[]) => void): Promise; } /** * @module SessionReplay * @package @geenius/analytics * @description Shared helpers for materializing lightweight session-replay * snapshots from events and page views. The Convex layer and UI variants use * these helpers to produce a consistent replay model. */ /** * Builds a lightweight session-replay snapshot from events and page views. * * @param events Analytics events and page views to normalize into replay frames. * @param sessionId Session identifier whose ordered activity should be materialized. * @returns Session replay snapshot with ordered frames and derived duration metadata. */ declare function buildSessionReplay(events: Array, sessionId: string): SessionReplaySnapshot; /** * Returns the ordered frame list from a session-replay snapshot. * * @param snapshot Session replay snapshot to inspect. * @returns Replay frames in playback order. */ declare function replaySessionFrames(snapshot: SessionReplaySnapshot): SessionReplayFrame[]; /** * @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. */ type TrackerProviderInput = AnalyticsProvider | ProviderConfig; type TrackerProviderRegistry = Partial>; interface TrackerConfig extends AnalyticsConfig { providers?: TrackerProviderInput[] | TrackerProviderRegistry; storage?: AnalyticsStorageAdapter | AnalyticsStorageAdapter[]; } type TrackerConfigInput = TrackerConfig | AnalyticsConfigurationBundle; /** * 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; } declare function createTracker(config: TrackerConfigInput): TrackerInstance; /** * @module validators * @package @geenius/analytics * @description Defines the shared Zod validators used by analytics runtime, * privacy, and dashboard helpers. These schemas keep runtime validation aligned * with the public TypeScript contract exported by the shared package. */ /** * Runtime validator for collected client device metadata. */ declare const DeviceInfoSchema: z.ZodObject<{ browser: z.ZodString; os: z.ZodString; device: z.ZodEnum<{ desktop: "desktop"; tablet: "tablet"; mobile: "mobile"; }>; screenWidth: z.ZodNumber; screenHeight: z.ZodNumber; language: z.ZodString; }, z.core.$strip>; /** * Runtime validator for identified user traits. */ declare const UserTraitsSchema: z.ZodObject<{ email: z.ZodOptional; name: z.ZodOptional; plan: z.ZodOptional; company: z.ZodOptional; }, z.core.$loose>; /** * Runtime validator for tracked analytics events. */ declare const AnalyticsEventSchema: z.ZodObject<{ id: z.ZodString; type: z.ZodEnum<{ page_view: "page_view"; click: "click"; form_submit: "form_submit"; custom: "custom"; }>; name: z.ZodString; properties: z.ZodOptional>; url: z.ZodString; referrer: z.ZodString; ipAddress: z.ZodOptional; sessionId: z.ZodString; userId: z.ZodOptional; traits: z.ZodOptional; name: z.ZodOptional; plan: z.ZodOptional; company: z.ZodOptional; }, z.core.$loose>>; device: z.ZodObject<{ browser: z.ZodString; os: z.ZodString; device: z.ZodEnum<{ desktop: "desktop"; tablet: "tablet"; mobile: "mobile"; }>; screenWidth: z.ZodNumber; screenHeight: z.ZodNumber; language: z.ZodString; }, z.core.$strip>; timestamp: z.ZodNumber; }, z.core.$strip>; /** * Runtime validator for tracked page-view payloads. */ declare const PageViewSchema: z.ZodObject<{ url: z.ZodString; title: z.ZodString; referrer: z.ZodString; properties: z.ZodOptional>; duration: z.ZodOptional; ipAddress: z.ZodOptional; sessionId: z.ZodString; userId: z.ZodOptional; timestamp: z.ZodNumber; }, z.core.$strip>; /** * Runtime validator for analytics consent choices. */ declare const ConsentSchema: z.ZodPipe; functional: z.ZodOptional; timestamp: z.ZodNumber; }, z.core.$strip>, z.ZodTransform<{ personalization: boolean; functional: boolean; essential: boolean; analytics: boolean; marketing: boolean; timestamp: number; }, { essential: boolean; analytics: boolean; marketing: boolean; timestamp: number; personalization?: boolean | undefined; functional?: boolean | undefined; }>>; /** * Runtime validator for funnel step definitions. */ declare const FunnelStepSchema: z.ZodObject<{ name: z.ZodString; event: z.ZodString; properties: z.ZodOptional>; }, z.core.$strip>; /** * Runtime validator for provider configuration. */ declare const ProviderConfigSchema: z.ZodObject<{ provider: z.ZodEnum<{ posthog: "posthog"; mixpanel: "mixpanel"; "google-analytics": "google-analytics"; plausible: "plausible"; }>; apiKey: z.ZodString; host: z.ZodOptional; enabled: z.ZodOptional; }, z.core.$strip>; /** * Runtime validator for numeric time ranges. */ declare const TimeRangeSchema: z.ZodObject<{ start: z.ZodNumber; end: z.ZodNumber; }, z.core.$strip>; /** * Runtime validator for privacy configuration. */ declare const PrivacySettingsSchema: z.ZodObject<{ mode: z.ZodEnum<{ mask: "mask"; anonymize: "anonymize"; redact: "redact"; }>; maskedFields: z.ZodArray; anonymizeIdentifiers: z.ZodBoolean; }, z.core.$strip>; /** * Runtime validator for cohort retention data points. */ declare const CohortRetentionPointSchema: z.ZodObject<{ day: z.ZodNumber; retainedUsers: z.ZodNumber; retentionRate: z.ZodNumber; }, z.core.$strip>; /** * Runtime validator for cohort buckets. */ declare const CohortBucketSchema: z.ZodObject<{ cohort: z.ZodString; size: z.ZodNumber; retained: z.ZodArray>; lastActivity: z.ZodNumber; }, z.core.$strip>; /** * Runtime validator for full cohort analyses. */ declare const CohortAnalysisSchema: z.ZodObject<{ name: z.ZodString; cohortType: z.ZodEnum<{ user: "user"; session: "session"; }>; intervals: z.ZodArray; cohorts: z.ZodArray>; lastActivity: z.ZodNumber; }, z.core.$strip>>; generatedAt: z.ZodNumber; }, z.core.$strip>; /** * Runtime validator for individual session replay frames. */ declare const SessionReplayFrameSchema: z.ZodObject<{ id: z.ZodString; kind: z.ZodEnum<{ page_view: "page_view"; event: "event"; }>; label: z.ZodString; url: z.ZodString; timestamp: z.ZodNumber; deltaMs: z.ZodNumber; sessionId: z.ZodString; userId: z.ZodOptional; properties: z.ZodOptional>; }, z.core.$strip>; /** * Runtime validator for full session replay snapshots. */ declare const SessionReplaySnapshotSchema: z.ZodObject<{ sessionId: z.ZodString; startedAt: z.ZodNumber; endedAt: z.ZodNumber; duration: z.ZodNumber; frames: z.ZodArray; label: z.ZodString; url: z.ZodString; timestamp: z.ZodNumber; deltaMs: z.ZodNumber; sessionId: z.ZodString; userId: z.ZodOptional; properties: z.ZodOptional>; }, z.core.$strip>>; activePages: z.ZodArray; userId: z.ZodOptional; }, z.core.$strip>; /** * @module SharedIndex * @package @geenius/analytics * @description Root barrel for the authored shared analytics runtime. This * entrypoint publishes the package contract consumed by every UI and Convex * variant, including types, runtime helpers, errors, validators, and provider * implementations without routing through nested barrel chains. */ /** Core analytics event, page-view, device, and dashboard contracts shared across every variant. */ /** Extended analytics configuration, funnel, realtime, and chart contracts shared across every variant. */ /** Privacy, cohort, and replay contracts shared across runtime, Storybook, and Convex surfaces. */ /** * Detects the current execution environment's browser and device characteristics. * * @returns Normalized device information safe to attach to analytics payloads. */ declare function detectDevice(): DeviceInfo; /** * Generates a best-effort session identifier for analytics events. * * @returns Session identifier suitable for correlating events in local runtimes. */ declare function generateSessionId(): string; /** * Determines whether analytics dispatch should proceed for the supplied configuration. * * @param config Analytics configuration that may respect browser tracking preferences. * @returns `true` when tracking is allowed in the current environment; otherwise `false`. */ declare function shouldTrack(config: AnalyticsConfig): boolean; /** Default analytics configuration used when consumers omit optional settings. */ declare const defaultAnalyticsConfig: AnalyticsConfig; export { AdapterUnsupportedError, type AnalyticsConfig, AnalyticsConfigBuilder, type AnalyticsConfigurationBundle, AnalyticsConfigurationError, AnalyticsContextError, type AnalyticsDashboardData, type AnalyticsDashboardQuery, AnalyticsError, type AnalyticsEvent, type AnalyticsEventQuery, AnalyticsEventSchema, type AnalyticsPageViewQuery, type AnalyticsProvider, type AnalyticsProviderConfig, AnalyticsProviderError, type AnalyticsProviderName, type AnalyticsReadResult, type AnalyticsStorageAdapter, BaseAnalyticsProvider, type BehavioralCohortDefinition, type BehavioralCohortResult, type BehavioralCohortRule, type ChartDashboardWidget, type ChartDataPoint, type CohortAnalysis, type CohortAnalysisOptions, type CohortAnalysisQuery, CohortAnalysisSchema, type CohortBucket, CohortBucketSchema, type CohortComparisonResult, type CohortDashboardWidget, type CohortRetentionPoint, CohortRetentionPointSchema, type ConsentCategory, ConsentSchema, type ConsentSettings, type ConvexAnalyticsEvent, DEFAULT_REALTIME_INTERVAL, DEFAULT_SESSION_TIMEOUT, type DashboardLayout, type DashboardWidget, type DashboardWidgetBase, type DashboardWidgetKind, type DeviceBreakdownDashboardWidget, type DeviceInfo, DeviceInfoSchema, EVENT_ICONS, type EventDashboardWidget, type EventType, type FunnelDashboardWidget, type FunnelResult, type FunnelResultsQuery, type FunnelStep, type FunnelStepResult, FunnelStepSchema, GoogleAnalyticsProvider, MAX_EVENTS_PER_BATCH, MAX_FUNNEL_STEPS, METRIC_FORMATS, type MetricDashboardWidget, type MetricSummary, MixpanelProvider, PROVIDERS, type PageView, PageViewSchema, PlausibleProvider, PostHogProvider, type PrivacyMode, type PrivacySettings, PrivacySettingsSchema, type ProviderConfig, ProviderConfigSchema, type ProviderName, type RealtimeDashboardWidget, type RealtimeStats, type RealtimeStatsQuery, type ReplayDashboardWidget, type SessionReplayFrame, SessionReplayFrameSchema, type SessionReplaySnapshot, SessionReplaySnapshotSchema, TREND_COLORS, type TimeRange, TimeRangeSchema, type TimelineEvent, type TopPageSummary, type TopPagesDashboardWidget, type TrackerConfig, type TrackerConfigInput, type TrackerInstance, type TrackerTrackOptions, type UserTraits, UserTraitsSchema, analyzeBehavioralCohorts, analyzeCohorts, analyzeFunnel, buildAnalyticsDashboardData, buildAnalyticsSeoMeta, buildRealtimeStats, buildSessionReplay, compareBehavioralCohorts, createAnalyticsConfig, createBehavioralCohortDefinition, createCohortRetentionPoints, createConsentSettings, createDashboardBuilder, createDashboardLayout, createFunnelSteps, createTracker, defaultAnalyticsConfig, defaultConfigs, detectDevice, filterRetainedAnalyticsAggregates, filterRetainedAnalyticsRecords, formatAnalyticsTime, generateSessionId, getAnalyticsDeviceLabel, getDefaultConfig, getRetentionCutoffTimestamp, hasConsentFor, hasSensitiveKeys, hashString, isDoNotTrackEnabled, maskString, normalizeAnalyticsEvents, pluralizeAnalytics, privacyUtils, pseudonymizeIdentifier, replaySessionFrames, sanitizeAnalyticsEvent, sanitizeObject, sanitizePageView, sanitizeUserTraits, shouldPurgeByRetention, shouldTrack, translateAnalytics, truncateIpAddress };