/** * @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; } /** * 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; } /** * 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; } /** * 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; } /** * 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; } /** * @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 MemoryAnalyticsStore * @package @geenius/analytics/memory * @description Deterministic in-process analytics provider used by tests, * demos, and parity checks. Data is intentionally ephemeral. */ /** * Input accepted when recording an event in the memory analytics store. */ interface AnalyticsStoreEventInput { id?: string; type?: AnalyticsEvent["type"]; name: string; properties?: Record; url?: string; referrer?: string; sessionId?: string; userId?: string; device?: DeviceInfo; timestamp?: number; } /** * Input accepted when recording a page view in the memory analytics store. */ interface AnalyticsStorePageViewInput { url: string; title?: string; referrer?: string; duration?: number; sessionId?: string; userId?: string; timestamp?: number; } /** * Filter options for memory-store event queries. */ interface AnalyticsEventFilter { name?: string; userId?: string; sessionId?: string; start?: number; end?: number; } /** * Pagination request for memory-store event listings. */ interface AnalyticsPaginationInput { limit?: number; cursor?: string; filter?: AnalyticsEventFilter; } /** * Cursor-based pagination result returned by the memory store. */ interface AnalyticsPaginationResult { items: AnalyticsEvent[]; nextCursor: string | null; } /** * Identity record stored by the memory analytics provider. */ interface IdentifiedUser { userId: string; traits?: UserTraits; updatedAt: number; } /** * Public memory analytics store contract used by tests, demos, and local runtimes. * * @property setUserProperties Merges profile traits into an identified memory user. * @property flush Resolves immediately because memory writes are not buffered. * @property shutdown Clears ephemeral memory state for tracker lifecycle parity. * @property purgeExpiredData Evicts events, page views, and user profiles older than the cutoff. */ interface MemoryAnalyticsStore { trackEvent(input: AnalyticsStoreEventInput): Promise; trackPageView(input: AnalyticsStorePageViewInput): Promise; identifyUser(userId: string, traits?: UserTraits): Promise; getEvent(id: string): Promise; listEvents(filter?: AnalyticsEventFilter): Promise; getEvents(query?: AnalyticsEventQuery): Promise>; getPageViews(query?: AnalyticsPageViewQuery): Promise>; getDashboardData(query?: AnalyticsDashboardQuery): Promise; getFunnelResults(query: FunnelResultsQuery): Promise; getCohortAnalysis(query?: CohortAnalysisQuery): Promise; paginateEvents(input?: AnalyticsPaginationInput): Promise; updateEvent(id: string, patch: Partial): Promise; deleteEvent(id: string): Promise; getTopPages(limit?: number): Promise>; getRealtimeStats(query?: RealtimeStatsQuery | number): Promise; setUserProperties(userId: string, traits: UserTraits): Promise; flush(): Promise; shutdown(): Promise; purgeExpiredData(cutoffTimestamp: number): Promise; deleteUserData(userId: string): Promise; clear(): Promise; } /** * Creates a deterministic in-process analytics store. * * @returns A memory analytics store with event, page-view, identity, and aggregate helpers. */ declare function createMemoryAnalyticsStore(): MemoryAnalyticsStore; export { type AnalyticsEventFilter, type AnalyticsPaginationInput, type AnalyticsPaginationResult, type AnalyticsStoreEventInput, type AnalyticsStorePageViewInput, type IdentifiedUser, type MemoryAnalyticsStore, createMemoryAnalyticsStore };