@anyreplay/browser 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +57 -0
- package/dist/index.cjs +660 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +228 -0
- package/dist/index.d.ts +228 -0
- package/dist/index.js +621 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recorder.ts","../src/config.ts","../src/events.ts","../src/sampling.ts","../src/transport.ts","../src/visitor.ts"],"sourcesContent":["import { record } from 'rrweb';\nimport type { AnyReplayOptions, ResolvedOptions } from './config.js';\nimport { resolveOptions } from './config.js';\nimport { NAVIGATE_TAG, TRACK_TAG, validateTrack } from './events.js';\nimport { isSampledIn } from './sampling.js';\nimport { Transport, type RecordedEvent, type SessionMeta } from './transport.js';\nimport {\n inCooldown, notePageCount, resolveIdentity, reserveSeq, safeStorage, startCooldown, touchSession,\n} from './visitor.js';\n\nexport type RecorderStatus = 'idle' | 'awaiting-consent' | 'recording' | 'sampled-out' | 'stopped';\n\nexport interface RecorderHandle {\n status: () => RecorderStatus;\n sessionId: () => string | null;\n consent: (granted: boolean) => void;\n identify: (traits: { userId?: string; email?: string }) => void;\n /**\n * Tags this moment of the recording so it shows on the player's timeline.\n *\n * `name` is 1–64 characters of `[A-Za-z0-9_.:-]`; `properties` must be a\n * plain JSON object of at most 4 KB. Anything else is dropped with a warning\n * in debug mode — never an exception, since this runs inside the page's\n * own handlers.\n */\n track: (name: string, properties?: Record<string, unknown>) => void;\n stop: () => void;\n flush: () => Promise<void>;\n}\n\n/** Rage click: several clicks in nearly the same spot in quick succession. */\nconst RAGE_CLICK_COUNT = 3;\nconst RAGE_CLICK_WINDOW_MS = 1000;\nconst RAGE_CLICK_RADIUS_PX = 30;\n\n/**\n * Events tracked before rrweb is emitting — while consent is pending, or\n * while the document is still loading — wait here. Enough for an app's boot\n * sequence; a page that tracks more than this before anything is recorded is\n * looping, and keeping the oldest ones tells the story better than the newest.\n */\nconst MAX_PENDING_EVENTS = 32;\n\nexport function createRecorder(rawOptions: AnyReplayOptions): RecorderHandle {\n const options: ResolvedOptions = resolveOptions(rawOptions);\n\n const local = safeStorage(() => globalThis.localStorage);\n const session = safeStorage(() => globalThis.sessionStorage);\n const identity = resolveIdentity(local, session);\n\n let status: RecorderStatus = 'idle';\n let stopRecording: (() => void) | undefined;\n let pageCount = identity.pageCount;\n\n if (!isSampledIn(identity.visitorId, options.sampleRate)) {\n // Decided from the visitor id, so this answer is stable across pages.\n return inertHandle('sampled-out', identity.sessionId);\n }\n\n if (inCooldown(session)) {\n // The previous page was told this session may not be started. That answer\n // will not have changed a page load later.\n if (options.debug) console.warn('[anyreplay] not recording: ingest refused a new session recently');\n return inertHandle('stopped', identity.sessionId);\n }\n\n const transport = new Transport(\n options,\n {\n projectKey: options.projectKey,\n sessionId: identity.sessionId,\n visitorId: identity.visitorId,\n initialSeq: identity.nextSeq,\n },\n {\n onSeqReserved: (next) => reserveSeq(session, next),\n onStopped: (reason) => {\n status = 'stopped';\n stopRecording?.();\n stopRecording = undefined;\n // Only the verdict about the session itself is remembered across pages.\n // A transport failure or an origin problem is either transient or one\n // request per page load to notice it is fixed; a full quota is neither.\n if (reason === 'rejected_402') startCooldown(session);\n if (options.debug) console.warn(`[anyreplay] recording stopped: ${reason}`);\n },\n },\n );\n\n const collectMeta = (): SessionMeta => ({\n startedAt: Date.now(),\n url: safeLocation(),\n lang: typeof navigator !== 'undefined' ? navigator.language : undefined,\n userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,\n screenWidth: typeof window !== 'undefined' ? window.innerWidth : undefined,\n screenHeight: typeof window !== 'undefined' ? window.innerHeight : undefined,\n referrer: typeof document !== 'undefined' ? document.referrer || undefined : undefined,\n // The cap is a decision about starting a session, so it goes only where\n // ingest makes that decision: chunk 0. A resumed page starts later.\n ...(options.maxSessionsPerMonth !== undefined && identity.nextSeq === 0\n ? { sessionCap: options.maxSessionsPerMonth }\n : {}),\n });\n\n const recentClicks: { x: number; y: number; t: number }[] = [];\n\n const noteInteraction = (event: RecordedEvent): void => {\n // rrweb IncrementalSnapshot(3) with MouseInteraction(2) source carries clicks.\n const data = event.data as { source?: number; type?: number; x?: number; y?: number } | undefined;\n if (event.type !== 3 || data?.source !== 2 || typeof data.x !== 'number') return;\n\n const now = event.timestamp;\n recentClicks.push({ x: data.x, y: data.y ?? 0, t: now });\n while (recentClicks.length > 0 && now - recentClicks[0]!.t > RAGE_CLICK_WINDOW_MS) recentClicks.shift();\n\n if (recentClicks.length >= RAGE_CLICK_COUNT) {\n const first = recentClicks[0]!;\n const clustered = recentClicks.every(\n (c) => Math.abs(c.x - first.x) < RAGE_CLICK_RADIUS_PX && Math.abs(c.y - first.y) < RAGE_CLICK_RADIUS_PX,\n );\n if (clustered) transport.mergeFlags({ hasRageClick: true });\n }\n };\n\n /* ----------------------------- custom events ---------------------------- */\n\n const pending: { tag: string; payload: unknown }[] = [];\n let draining = false;\n let drainScheduled = false;\n\n /**\n * Hands the queue of waiting events to rrweb, in order.\n *\n * `addCustomEvent` throws until rrweb has finished its first snapshot,\n * which it takes on `load` when the recorder starts in a still-loading\n * document — and it flips to accepting only after the snapshot's own\n * events have been emitted, so draining from inside `emit` can be refused\n * too. A refusal is retried on the next event and, in case no event comes,\n * on a timer. A queued event is stamped with the time it is handed over,\n * not the time `track` was called: a marker a few hundred milliseconds late\n * is still on the timeline, and one dated before the snapshot is not.\n */\n const drainPending = (): void => {\n if (draining || pending.length === 0) return;\n draining = true;\n try {\n while (pending.length > 0) {\n const next = pending[0]!;\n record.addCustomEvent(next.tag, next.payload);\n pending.shift();\n }\n } catch {\n if (!drainScheduled && status === 'recording') {\n drainScheduled = true;\n setTimeout(() => { drainScheduled = false; drainPending(); }, 50);\n }\n } finally {\n draining = false;\n }\n };\n\n const emitCustom = (tag: string, payload: unknown): void => {\n if (status === 'stopped') return;\n if (status === 'recording') {\n try {\n record.addCustomEvent(tag, payload);\n return;\n } catch {\n /* not emitting yet — queue it */\n }\n }\n if (pending.length >= MAX_PENDING_EVENTS) {\n if (options.debug) console.warn(`[anyreplay] dropped ${tag}: too many events before recording started`);\n return;\n }\n pending.push({ tag, payload });\n };\n\n /* ------------------------------ navigation ------------------------------ */\n\n let lastUrl = safeLocation();\n\n /**\n * A route change in a single-page app is a page view.\n *\n * rrweb records the DOM mutations that come with it, but nothing in the\n * stream says \"this is a new page\" — so the marker is emitted here, and\n * ingest indexes it for the player. Same-URL changes are ignored: routers\n * call `replaceState` for scroll positions and query tweaks, and each of\n * those is not a page.\n */\n const noteNavigation = (): void => {\n const url = safeLocation();\n if (!url || url === lastUrl) return;\n lastUrl = url;\n pageCount += 1;\n notePageCount(session, pageCount);\n transport.mergeFlags({ pageCount });\n emitCustom(NAVIGATE_TAG, { url, title: typeof document !== 'undefined' ? document.title : '' });\n };\n\n const begin = (): void => {\n if (status === 'recording' || status === 'stopped') return;\n status = 'recording';\n transport.setMeta(collectMeta());\n // The page the recorder starts on is a page view. Without this the\n // counter only ever reflects in-app navigations, so a single-page visit\n // reports zero pages — and on a resumed session it is the previous page's\n // count plus one, so the hop is visible.\n transport.mergeFlags({ pageCount });\n transport.start();\n\n stopRecording = record({\n emit: (event) => {\n const typed = event as unknown as RecordedEvent;\n noteInteraction(typed);\n touchSession(session, typed.timestamp);\n transport.push(typed);\n drainPending();\n },\n maskAllInputs: options.maskAllInputs,\n maskTextClass: options.maskClass,\n blockClass: options.blockClass,\n // Passwords are never recorded, regardless of configuration.\n maskInputOptions: { password: true, email: true, tel: true },\n // Canvas capture is expensive and off unless a customer opts in later.\n recordCanvas: false,\n collectFonts: false,\n });\n // Every page begins with a full snapshot (rrweb takes one on start), so\n // events tracked before this point land right after it.\n drainPending();\n\n attachLifecycleHooks();\n };\n\n const attachLifecycleHooks = (): void => {\n if (typeof window === 'undefined') return;\n\n // pagehide is the reliable end-of-page signal; unload does not fire on\n // mobile Safari and beforeunload breaks the back/forward cache.\n window.addEventListener('pagehide', () => { transport.flushWithBeacon(); }, { capture: true });\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') transport.flushWithBeacon();\n });\n window.addEventListener('error', () => transport.mergeFlags({ hasError: true }));\n window.addEventListener('unhandledrejection', () => transport.mergeFlags({ hasError: true }));\n\n // Wrapped after the original runs, so `location` already shows the new URL.\n const patch = (method: 'pushState' | 'replaceState'): void => {\n const original = history[method].bind(history);\n history[method] = function patched(...args: Parameters<History['pushState']>) {\n const result = original(...args);\n noteNavigation();\n return result;\n };\n };\n patch('pushState');\n patch('replaceState');\n window.addEventListener('popstate', noteNavigation);\n };\n\n if (options.requireConsent) {\n status = 'awaiting-consent';\n } else {\n begin();\n }\n\n return {\n status: () => status,\n sessionId: () => identity.sessionId,\n consent: (granted) => {\n if (granted) begin();\n else transport.stop('consent_withdrawn');\n },\n identify: (traits) => {\n if (!traits.userId && !traits.email) return;\n void fetch(`${options.ingestUrl}/v1/ingest/identify`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'omit',\n body: JSON.stringify({\n projectKey: options.projectKey,\n sessionId: identity.sessionId,\n ...traits,\n }),\n }).catch(() => { /* identity is best-effort; never surface to the page */ });\n },\n track: (name, properties) => {\n const payload = validateTrack(name, properties);\n if (typeof payload === 'string') {\n if (options.debug) console.warn(`[anyreplay] track() ignored: ${payload}`);\n return;\n }\n emitCustom(TRACK_TAG, payload);\n },\n stop: () => transport.stop('stopped_by_page'),\n flush: () => transport.flush(),\n };\n}\n\nfunction safeLocation(): string | undefined {\n try {\n return typeof location !== 'undefined' ? location.href : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction inertHandle(status: RecorderStatus, sessionId: string | null): RecorderHandle {\n return {\n status: () => status,\n sessionId: () => sessionId,\n consent: () => {},\n identify: () => {},\n track: () => {},\n stop: () => {},\n flush: async () => {},\n };\n}\n","export interface AnyReplayOptions {\n /** Public project key from the dashboard. */\n projectKey: string;\n /** Ingest endpoint. Override only for self-hosted deployments. */\n ingestUrl?: string;\n /** Fraction of visitors recorded, 0–1. Decided once per visitor, not per page. */\n sampleRate?: number;\n /** Mask every text input. Leaving this on is the supported configuration. */\n maskAllInputs?: boolean;\n /** Elements with this class have their text masked. */\n maskClass?: string;\n /** Elements with this class are not recorded at all. */\n blockClass?: string;\n /** Wait for `anyreplay('consent', true)` before recording anything. */\n requireConsent?: boolean;\n /** Flush when the buffer reaches this many events. */\n maxEventsPerChunk?: number;\n /** Flush at least this often, in milliseconds. */\n flushIntervalMs?: number;\n /** Recording stops after this many consecutive transport failures. */\n maxConsecutiveFailures?: number;\n /**\n * The most sessions this project may record per calendar month (UTC).\n *\n * Sent with the first chunk of every new session; ingest refuses a session\n * that would exceed it with 402 `session_cap_reached` and the recorder stops\n * for that visit. A cap set in the dashboard also applies, and the lower one\n * wins. Positive integer, at most 1,000,000.\n */\n maxSessionsPerMonth?: number;\n debug?: boolean;\n}\n\nexport interface ResolvedOptions extends Required<Omit<AnyReplayOptions, 'ingestUrl' | 'maxSessionsPerMonth'>> {\n ingestUrl: string;\n maxSessionsPerMonth?: number;\n}\n\nexport const DEFAULTS: Omit<ResolvedOptions, 'projectKey'> = {\n ingestUrl: 'https://in.anyreplay.com',\n sampleRate: 1,\n // Default-deny. Recording a customer's password field once is a breach; the\n // cost of the safe default is a configuration line for the rare field that\n // genuinely needs to be visible.\n maskAllInputs: true,\n maskClass: 'ar-mask',\n blockClass: 'ar-block',\n requireConsent: false,\n maxEventsPerChunk: 200,\n flushIntervalMs: 5000,\n maxConsecutiveFailures: 5,\n debug: false,\n};\n\nexport class ConfigError extends Error {}\n\nconst KEY_PATTERN = /^ar_pk_(live|test)_[0-9a-f]{24}$/;\n/** Matches what ingest's schema accepts, so a value that passes here is never a 422 later. */\nconst MAX_SESSION_CAP = 1_000_000;\n\nexport function resolveOptions(input: AnyReplayOptions): ResolvedOptions {\n if (!input || typeof input !== 'object') throw new ConfigError('anyreplay: options object required');\n if (!KEY_PATTERN.test(input.projectKey ?? '')) {\n throw new ConfigError('anyreplay: projectKey looks wrong — copy it from the dashboard');\n }\n\n const sampleRate = input.sampleRate ?? DEFAULTS.sampleRate;\n if (!(sampleRate >= 0 && sampleRate <= 1)) {\n throw new ConfigError('anyreplay: sampleRate must be between 0 and 1');\n }\n\n const cap = input.maxSessionsPerMonth;\n if (cap !== undefined && !(Number.isInteger(cap) && cap >= 1 && cap <= MAX_SESSION_CAP)) {\n throw new ConfigError(`anyreplay: maxSessionsPerMonth must be a whole number between 1 and ${MAX_SESSION_CAP}`);\n }\n\n return {\n ...DEFAULTS,\n ...input,\n projectKey: input.projectKey,\n sampleRate,\n ingestUrl: (input.ingestUrl ?? DEFAULTS.ingestUrl).replace(/\\/+$/, ''),\n // A caller who explicitly passes false gets what they asked for; anything\n // else (including undefined) keeps masking on.\n maskAllInputs: input.maskAllInputs === false ? false : true,\n };\n}\n","/**\n * Custom events: the moments a page tags with `track()`.\n *\n * They travel inside the rrweb stream as rrweb's own Custom event type, so\n * they carry the recording's clock and replay in order with everything else.\n * Ingest recognises them by these tags; the names are a contract with\n * apps/ingest/src/custom-events.ts.\n */\nexport const TRACK_TAG = 'anyreplay.track';\nexport const NAVIGATE_TAG = 'anyreplay.navigate';\n\n/** Short and URL-safe: an event name is a label, not a message. Ingest applies the same rule. */\nexport const EVENT_NAME_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;\n/** Properties are stored with the event and indexed by nobody; a bag bigger than this is a payload, not context. */\nexport const MAX_PROPERTIES_BYTES = 4 * 1024;\n\nexport interface TrackPayload {\n name: string;\n properties: Record<string, unknown>;\n}\n\n/**\n * Checks what the page passed to `track()`, returning the payload to send or\n * the reason it was refused. Never throws: the page's own code is calling\n * this on a click handler, and a recorder that throws there breaks the click.\n */\nexport function validateTrack(name: unknown, properties: unknown): TrackPayload | string {\n if (typeof name !== 'string' || !EVENT_NAME_PATTERN.test(name)) {\n return `event name must be 1-64 characters of [A-Za-z0-9_.:-], got ${JSON.stringify(name)}`;\n }\n if (properties === undefined || properties === null) return { name, properties: {} };\n if (typeof properties !== 'object' || Array.isArray(properties)) {\n return `properties for \"${name}\" must be a plain object`;\n }\n let serialised: string;\n try {\n serialised = JSON.stringify(properties);\n } catch {\n return `properties for \"${name}\" are not JSON-serialisable`;\n }\n if (serialised === undefined || byteLength(serialised) > MAX_PROPERTIES_BYTES) {\n return `properties for \"${name}\" exceed ${MAX_PROPERTIES_BYTES} bytes once serialised`;\n }\n // The parsed copy, not the original: a getter or a class instance on the\n // caller's object must not reach the wire, and a later mutation must not\n // change what was tracked.\n return { name, properties: JSON.parse(serialised) as Record<string, unknown> };\n}\n\nfunction byteLength(text: string): number {\n return typeof TextEncoder === 'function' ? new TextEncoder().encode(text).length : text.length * 3;\n}\n","/**\n * FNV-1a. Small, fast, and good enough to spread visitor ids uniformly across\n * the unit interval — this is a bucketing decision, not a security one.\n */\nexport function hashToUnitInterval(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash / 0xffffffff;\n}\n\n/**\n * Decides sampling from the visitor id rather than a coin flip.\n *\n * The same visitor therefore gets the same answer on every page and every\n * visit: a recorded journey stays whole instead of appearing as disconnected\n * fragments, and changing the rate moves a predictable slice of the population.\n */\nexport function isSampledIn(visitorId: string, sampleRate: number): boolean {\n if (sampleRate >= 1) return true;\n if (sampleRate <= 0) return false;\n return hashToUnitInterval(visitorId) < sampleRate;\n}\n","import type { ResolvedOptions } from './config.js';\n\nexport interface RecordedEvent {\n type: number;\n timestamp: number;\n data?: unknown;\n}\n\nexport interface SessionMeta {\n startedAt: number;\n url?: string;\n lang?: string;\n userAgent?: string;\n screenWidth?: number;\n screenHeight?: number;\n referrer?: string;\n /** `maxSessionsPerMonth`, sent only with chunk 0 of a new session. */\n sessionCap?: number;\n}\n\nexport interface ChunkFlags {\n hasError?: boolean;\n hasRageClick?: boolean;\n pageCount?: number;\n}\n\nexport interface TransportContext {\n projectKey: string;\n sessionId: string;\n visitorId: string;\n /** The first chunk number to use. Non-zero when a page resumes a session. */\n initialSeq?: number;\n}\n\n/** How many times one flush may move to a new chunk number before giving up. */\nconst MAX_STALE_RECOVERIES = 3;\n\n/**\n * The first free chunk number, when ingest says the one just sent was taken.\n *\n * Ingest answers a repeated (session, seq) with 202 and `duplicate: true`,\n * because to the server it looks like a retry. When this transport had never\n * sent that number before, it was not a retry: the number was used by an\n * earlier page of the session, or by another tab sharing it, and the events\n * were discarded. Servers that know the answer say where numbering continues.\n */\nasync function staleSeqHint(response: Response, sent: number): Promise<number | undefined> {\n try {\n if (typeof response.json !== 'function') return undefined;\n const reply = await response.json() as { duplicate?: unknown; nextSeq?: unknown };\n if (reply.duplicate !== true) return undefined;\n const next = reply.nextSeq;\n return typeof next === 'number' && Number.isInteger(next) && next > sent ? next : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport type TransportState = 'open' | 'stopped';\n\n/**\n * The Fetch standard caps the total body size of in-flight `keepalive`\n * requests at 64 KiB, and a browser rejects an oversized one outright — the\n * promise rejects with a bare TypeError, indistinguishable from being offline.\n *\n * The margin below is for the request headers, which count towards the same\n * budget, and for a second flush overlapping the first.\n */\nconst KEEPALIVE_BODY_LIMIT_BYTES = 56 * 1024;\n\n/**\n * Whether a payload may be sent with `keepalive`.\n *\n * Deciding this from the event *count* is the trap: the first chunk of every\n * session is a Meta plus a single full DOM snapshot — two events, and on a real\n * page routinely several hundred kilobytes. Sizing by count marks it as small,\n * the browser refuses it, and the recorder counts a network failure it can\n * never recover from; after `maxConsecutiveFailures` it stops for good. The\n * symptom is a site that records nothing at all while the snippet looks\n * perfectly installed.\n */\nexport function withinKeepaliveLimit(payload: string): boolean {\n const bytes = typeof TextEncoder === 'function'\n ? new TextEncoder().encode(payload).length\n // No TextEncoder: assume the worst rather than risk the rejection.\n : payload.length * 3;\n return bytes <= KEEPALIVE_BODY_LIMIT_BYTES;\n}\n\nexport interface TransportHooks {\n onStopped?: (reason: string) => void;\n onSent?: (seq: number, eventCount: number) => void;\n /** Called with the next free chunk number before a request using the current one leaves. */\n onSeqReserved?: (nextSeq: number) => void;\n}\n\n/**\n * Ships buffered events to ingest.\n *\n * Three properties matter more than throughput here, because this code runs\n * inside somebody else's product:\n *\n * - It must never throw into the host page.\n * - It must never keep retrying a request the server has rejected on its\n * merits (a bad key, a disallowed origin) — that is an infinite loop.\n * - It must not lose the tail of a session when the tab closes.\n */\nexport class Transport {\n private buffer: RecordedEvent[] = [];\n private seq = 0;\n private consecutiveFailures = 0;\n private state: TransportState = 'open';\n private timer: ReturnType<typeof setInterval> | undefined;\n private pendingMeta: SessionMeta | undefined;\n private flags: ChunkFlags = {};\n private inFlight = false;\n /** The chunk number of the last request that left, to tell a retry from a first attempt. */\n private lastAttemptedSeq = -1;\n private staleRecoveries = 0;\n\n constructor(\n private readonly options: ResolvedOptions,\n private readonly context: TransportContext,\n private readonly hooks: TransportHooks = {},\n ) {\n this.seq = context.initialSeq ?? 0;\n }\n\n get isStopped(): boolean {\n return this.state === 'stopped';\n }\n\n get bufferedCount(): number {\n return this.buffer.length;\n }\n\n get sentChunks(): number {\n return this.seq;\n }\n\n /** Attaches metadata to the next chunk. Sent once, with the session's first chunk. */\n setMeta(meta: SessionMeta): void {\n this.pendingMeta = meta;\n }\n\n mergeFlags(flags: ChunkFlags): void {\n this.flags = { ...this.flags, ...flags };\n }\n\n start(): void {\n if (this.timer) return;\n this.timer = setInterval(() => void this.flush(), this.options.flushIntervalMs);\n // Never hold a Node process open; harmless in browsers.\n (this.timer as unknown as { unref?: () => void }).unref?.();\n }\n\n stop(reason: string): void {\n this.state = 'stopped';\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n this.buffer = [];\n this.hooks.onStopped?.(reason);\n }\n\n push(event: RecordedEvent): void {\n if (this.state === 'stopped') return;\n this.buffer.push(event);\n if (this.buffer.length >= this.options.maxEventsPerChunk) void this.flush();\n }\n\n private body(events: RecordedEvent[]): string {\n return JSON.stringify({\n projectKey: this.context.projectKey,\n sessionId: this.context.sessionId,\n visitorId: this.context.visitorId,\n seq: this.seq,\n events,\n ...(this.pendingMeta ? { meta: this.pendingMeta } : {}),\n ...(Object.keys(this.flags).length > 0 ? { flags: this.flags } : {}),\n });\n }\n\n /** Sends whatever is buffered. Safe to call when there is nothing to send. */\n async flush(): Promise<void> {\n if (this.state === 'stopped' || this.inFlight || this.buffer.length === 0) return;\n\n this.inFlight = true;\n const events = this.buffer;\n this.buffer = [];\n let resend = false;\n\n try {\n const retry = this.lastAttemptedSeq === this.seq;\n this.lastAttemptedSeq = this.seq;\n // Reserved before the request leaves: a page that is closed mid-flight\n // must not hand this number to the next page of the same session.\n this.hooks.onSeqReserved?.(this.seq + 1);\n const payload = this.body(events);\n const response = await fetch(`${this.options.ingestUrl}/v1/ingest/events`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: payload,\n // Ingest is unauthenticated by design; sending credentials would be a\n // cross-site cookie leak for no benefit.\n credentials: 'omit',\n keepalive: withinKeepaliveLimit(payload),\n });\n\n if (response.ok) {\n const nextSeq = retry ? undefined : await staleSeqHint(response, this.seq);\n if (nextSeq !== undefined && this.staleRecoveries < MAX_STALE_RECOVERIES) {\n // These events were new and the server discarded them. Send them\n // again under the first number it has not seen.\n this.staleRecoveries += 1;\n this.seq = nextSeq;\n this.requeue(events);\n resend = true;\n return;\n }\n this.staleRecoveries = 0;\n this.seq += 1;\n this.pendingMeta = undefined;\n this.consecutiveFailures = 0;\n this.hooks.onSent?.(this.seq - 1, events.length);\n return;\n }\n\n // 4xx other than 429 is a verdict, not a hiccup: the key is wrong, the\n // origin is not allowed, or the payload is malformed. Retrying cannot\n // change the answer, so stop instead of hammering the endpoint forever.\n if (response.status >= 400 && response.status < 500 && response.status !== 429) {\n this.stop(`rejected_${response.status}`);\n return;\n }\n\n this.requeue(events);\n this.registerFailure();\n } catch {\n // Network error: the user may simply be offline. Keep the events.\n this.requeue(events);\n this.registerFailure();\n } finally {\n this.inFlight = false;\n if (resend) void this.flush();\n }\n }\n\n /**\n * Puts a failed batch back at the front of the queue.\n *\n * Bounded on purpose: a long offline period must not grow the buffer until\n * the tab runs out of memory. Older events are dropped first — a replay\n * missing its beginning is still useful; a crashed page is not.\n */\n private requeue(events: RecordedEvent[]): void {\n const limit = this.options.maxEventsPerChunk * 10;\n this.buffer = [...events, ...this.buffer].slice(-limit);\n }\n\n private registerFailure(): void {\n this.consecutiveFailures += 1;\n if (this.consecutiveFailures >= this.options.maxConsecutiveFailures) {\n this.stop('too_many_failures');\n }\n }\n\n /**\n * Last-gasp send when the page is going away.\n *\n * `fetch` is cancelled once the document unloads, so the tail of every\n * session would be lost. `sendBeacon` hands the payload to the browser, which\n * delivers it after the page is gone.\n */\n flushWithBeacon(): boolean {\n if (this.state === 'stopped' || this.buffer.length === 0) return false;\n\n const events = this.buffer;\n const payload = this.body(events);\n this.buffer = [];\n\n try {\n if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n // text/plain avoids a CORS preflight, which cannot complete during unload.\n this.hooks.onSeqReserved?.(this.seq + 1);\n const blob = new Blob([payload], { type: 'text/plain;charset=UTF-8' });\n const queued = navigator.sendBeacon(`${this.options.ingestUrl}/v1/ingest/events`, blob);\n if (queued) {\n this.seq += 1;\n this.pendingMeta = undefined;\n return true;\n }\n }\n } catch {\n /* fall through */\n }\n\n this.buffer = events;\n return false;\n }\n}\n","const VISITOR_KEY = 'anyreplay.vid';\nconst SESSION_KEY = 'anyreplay.sid';\nconst SESSION_TS_KEY = 'anyreplay.sts';\n/** The next chunk number the current session may use. */\nconst SEQ_KEY = 'anyreplay.seq';\n/** Page views so far in the current session, so a reload continues the count. */\nconst PAGE_KEY = 'anyreplay.pc';\n/** Until when (epoch ms) this tab should not try to record, after ingest refused a new session. */\nconst COOLDOWN_KEY = 'anyreplay.cd';\n\n/**\n * How long a tab waits after a 402 before trying to record again.\n *\n * A quota or cap is a monthly fact; retrying on every page load would put one\n * refused request per navigation on ingest, from every visitor, for the rest\n * of the month. Two minutes is long enough to make that negligible and short\n * enough that an upgrade takes effect while the customer is still watching.\n */\nconst QUOTA_COOLDOWN_MS = 2 * 60 * 1000;\n\n/** A new session starts after this much inactivity, matching common analytics. */\nconst SESSION_IDLE_MS = 30 * 60 * 1000;\n\nfunction randomId(bytes = 16): string {\n const array = new Uint8Array(bytes);\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(array);\n } else {\n for (let i = 0; i < bytes; i += 1) array[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** RFC 4122 v4, formatted. Ingest requires a UUID for the session id. */\nexport function uuidv4(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n const hex = randomId(16).split('');\n hex[12] = '4';\n hex[16] = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);\n const s = hex.join('');\n return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;\n}\n\ninterface Storage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\n/**\n * Storage that degrades instead of throwing.\n *\n * `localStorage` throws on access in some privacy modes, and a recorder that\n * throws inside the customer's page is far worse than one that stops recording.\n */\nexport function safeStorage(source: () => globalThis.Storage | undefined): Storage {\n const read = (): globalThis.Storage | undefined => {\n try { return source(); } catch { return undefined; }\n };\n return {\n get: (key) => { try { return read()?.getItem(key) ?? null; } catch { return null; } },\n set: (key, value) => { try { read()?.setItem(key, value); } catch { /* ignore */ } },\n remove: (key) => { try { read()?.removeItem(key); } catch { /* ignore */ } },\n };\n}\n\nexport interface Identity {\n visitorId: string;\n sessionId: string;\n isNewSession: boolean;\n /** The chunk number to continue from: 0 for a new session, later for a resumed one. */\n nextSeq: number;\n /** Which page view of the session this is: 1 for a new session, previous + 1 for a resumed one. */\n pageCount: number;\n}\n\n/**\n * Resolves who this is and which session they are in.\n *\n * The visitor id persists across visits (it is what sampling is decided on, so\n * a sampled-out visitor stays sampled out rather than flickering). The session\n * id resets after a period of inactivity.\n */\nexport function resolveIdentity(\n local: Storage,\n session: Storage,\n now: number = Date.now(),\n): Identity {\n let visitorId = local.get(VISITOR_KEY);\n if (!visitorId || !/^[A-Za-z0-9_-]{8,64}$/.test(visitorId)) {\n visitorId = `v${randomId(12)}`;\n local.set(VISITOR_KEY, visitorId);\n }\n\n const previousId = session.get(SESSION_KEY);\n const previousTs = Number(session.get(SESSION_TS_KEY) ?? 0);\n const expired = !previousId || !previousTs || now - previousTs > SESSION_IDLE_MS;\n\n const sessionId = expired ? uuidv4() : previousId;\n session.set(SESSION_KEY, sessionId);\n session.set(SESSION_TS_KEY, String(now));\n\n // A resumed session continues its chunk numbering. Starting again at 0 on\n // every page load collides with chunks the server already holds for this\n // session, and ingest drops a repeated (session, seq) as a retry — silently\n // losing everything recorded after the first page.\n const storedSeq = Number(session.get(SEQ_KEY));\n const nextSeq = !expired && Number.isInteger(storedSeq) && storedSeq > 0 ? storedSeq : 0;\n session.set(SEQ_KEY, String(nextSeq));\n\n // A full navigation is a page view of the same session. Starting the count\n // at 1 on every page would report a ten-page visit as one page.\n const storedPages = Number(session.get(PAGE_KEY));\n const pageCount = !expired && Number.isInteger(storedPages) && storedPages > 0 ? storedPages + 1 : 1;\n session.set(PAGE_KEY, String(pageCount));\n\n return { visitorId, sessionId, isNewSession: expired, nextSeq, pageCount };\n}\n\n/** Records the page count so the next page of the session continues from it. */\nexport function notePageCount(session: { set(key: string, value: string): void }, count: number): void {\n session.set(PAGE_KEY, String(count));\n}\n\n/** True while this tab is still inside the cool-down that followed a 402. */\nexport function inCooldown(session: Storage, now: number = Date.now()): boolean {\n const until = Number(session.get(COOLDOWN_KEY));\n return Number.isFinite(until) && until > now;\n}\n\nexport function startCooldown(session: Storage, now: number = Date.now()): void {\n session.set(COOLDOWN_KEY, String(now + QUOTA_COOLDOWN_MS));\n}\n\n/** Records that chunk numbers below `next` are taken, before the request that uses one leaves. */\nexport function reserveSeq(session: { set(key: string, value: string): void }, next: number): void {\n session.set(SEQ_KEY, String(next));\n}\n\nexport function touchSession(session: Storage, now: number = Date.now()): void {\n session.set(SESSION_TS_KEY, String(now));\n}\n\nexport { VISITOR_KEY, SESSION_KEY, SESSION_TS_KEY, SEQ_KEY, PAGE_KEY, COOLDOWN_KEY, SESSION_IDLE_MS, QUOTA_COOLDOWN_MS };\n"],"mappings":";;;;;AAAA,SAAS,cAAc;;;ACsChB,IAAM,WAAgD;AAAA,EAC3D,WAAW;AAAA,EACX,YAAY;AAAA;AAAA;AAAA;AAAA,EAIZ,eAAe;AAAA,EACf,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,wBAAwB;AAAA,EACxB,OAAO;AACT;AAEO,IAAM,cAAN,cAA0B,MAAM;AAAC;AAExC,IAAM,cAAc;AAEpB,IAAM,kBAAkB;AAEjB,SAAS,eAAe,OAA0C;AA5DzE;AA6DE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,YAAY,oCAAoC;AACnG,MAAI,CAAC,YAAY,MAAK,WAAM,eAAN,YAAoB,EAAE,GAAG;AAC7C,UAAM,IAAI,YAAY,qEAAgE;AAAA,EACxF;AAEA,QAAM,cAAa,WAAM,eAAN,YAAoB,SAAS;AAChD,MAAI,EAAE,cAAc,KAAK,cAAc,IAAI;AACzC,UAAM,IAAI,YAAY,+CAA+C;AAAA,EACvE;AAEA,QAAM,MAAM,MAAM;AAClB,MAAI,QAAQ,UAAa,EAAE,OAAO,UAAU,GAAG,KAAK,OAAO,KAAK,OAAO,kBAAkB;AACvF,UAAM,IAAI,YAAY,uEAAuE,eAAe,EAAE;AAAA,EAChH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
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Session replay recorder for the browser: DOM-based recording with input masking on by default, custom events, and chunked delivery to AnyReplay.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://anyreplay.com",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/baemtech/anyreplay-sdk.git",
|
|
10
|
+
"directory": "browser"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/baemtech/anyreplay-sdk/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"session-replay",
|
|
17
|
+
"session-recording",
|
|
18
|
+
"rrweb",
|
|
19
|
+
"analytics",
|
|
20
|
+
"user-research",
|
|
21
|
+
"anyreplay"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./dist/index.cjs",
|
|
25
|
+
"module": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"import": "./dist/index.js",
|
|
31
|
+
"require": "./dist/index.cjs"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"!dist/cdn",
|
|
38
|
+
"README.md",
|
|
39
|
+
"LICENSE"
|
|
40
|
+
],
|
|
41
|
+
"sideEffects": false,
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsup",
|
|
47
|
+
"size": "node scripts/size.mjs",
|
|
48
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
49
|
+
"test": "vitest run"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"rrweb": "2.0.0-alpha.4"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"jsdom": "25.0.1",
|
|
56
|
+
"tsup": "8.3.5",
|
|
57
|
+
"typescript": "5.8.3",
|
|
58
|
+
"vitest": "2.1.8"
|
|
59
|
+
}
|
|
60
|
+
}
|