2.9 KiB
session.ts
(no submodules)
Purpose
Tracks the lifecycle of a single browser session for @suaveplan/analytics-browser. The SessionManager owns the session ID, the start time, the page-view counter, the captured document.referrer, and the inactivity-timeout state machine. Consumers attach it to a tracker (tracker.setSessionId(session.getSessionId())) and call recordPageView() / touch() as user interaction occurs. The class is fully clock-injectable so tests can drive the inactivity timeout without sleeping.
Features
- Cryptographically-random session ID (defaults to the package's shared
generateId). - Inactivity timeout —
isActive()returnsfalseaftertimeoutMsof silence; the nextrecordPageView()is a no-op untilrenew()is called. - Manual
renew()— resets the ID, start time, page-view count, and active flag (used on logout / login or app-managed session boundary events). - Injectable
clock,idGenerator, andreferrerfor deterministic tests and SSR.
Usage: Basic
import { SessionManager } from "@suaveplan/analytics-browser/session";
const session = new SessionManager({ timeoutMs: 30 * 60 * 1000 });
session.recordPageView();
const info = session.getInfo();
Usage: Advanced
import { SessionManager } from "@suaveplan/analytics-browser/session";
let now = 0;
const session = new SessionManager({
timeoutMs: 60_000,
clock: () => now,
idGenerator: () => "test-session",
referrer: "https://example.com",
});
now = 30_000;
session.recordPageView();
now = 120_000; // exceeds timeoutMs since last activity
session.isActive(); // → false
session.renew(); // mint a fresh session id
API Reference
class SessionManagernew SessionManager(options?)—options: SessionOptions { timeoutMs?, referrer?, clock?, idGenerator? }getSessionId(): stringgetReferrer(): stringgetPageViews(): numberrecordPageView(): void— no-op when session is inactivetouch(): void— resets the inactivity clockgetDuration(): number— milliseconds sincestartedAtisActive(): boolean— auto-expires pasttimeoutMsend(): void— explicitly terminates the sessionrenew(): string— mints a fresh session id, zeros page views, resets the inactivity clockgetInfo(): SessionInfo—{ id, startedAt, pageViews, duration, referrer, isActive }
Implementation Notes
getDuration returns the live duration when the session is active, otherwise the duration up to the last activity timestamp. This keeps the duration stable after end() is called — repeated getDuration() calls on an ended session return the same value rather than drifting upward with wall-clock time. The document.referrer lookup is guarded by typeof document !== "undefined" so SSR contexts default to "" rather than throwing.