Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Export as MP4 option

Blue Mouse578eed0cd790
diff --git a/backend/Dockerfile b/backend/Dockerfile
index 80f94828c..bc49a390b 100644
--- a/backend/Dockerfile
+++ b/backend/Dockerfile
@@ -1,7 +1,9 @@
#Stage 1: Build
-FROM node:lts-alpine AS build
+FROM mcr.microsoft.com/playwright:v1.60.0-noble AS build
WORKDIR /build
+ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
COPY package*.json ./
+COPY scripts/patch-rrvideo.js ./scripts/patch-rrvideo.js
RUN npm ci --force
COPY . .
RUN npm run deploy:community
@@ -9,7 +11,7 @@ RUN node ./meta/dbip-free-sync.js
RUN npm prune --omit=dev --force
#Stage 2: Runtime
-FROM node:lts-alpine AS run
+FROM mcr.microsoft.com/playwright:v1.60.0-noble AS run
LABEL maintainer="swetrix.com <[email protected]>"
ENV TZ=UTC \
@@ -32,10 +34,11 @@ ENV OIDC_CLIENT_ID='' \
OIDC_DISCOVERY_URL='' \
OIDC_CLIENT_SECRET=''
-# Install and configure timezone
-RUN apk add --no-cache tzdata && \
+# Install video tooling and configure timezone
+RUN apt-get update && \
+ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ffmpeg tzdata && \
cp /usr/share/zoneinfo/$TZ /etc/localtime && \
- apk del tzdata
+ rm -rf /var/lib/apt/lists/*
# Use non-root numeric user
USER 999
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 0b626b576..1c00542f0 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -12,6 +12,7 @@ import {
Controller,
Body,
Query,
+ Param,
UseGuards,
UsePipes,
ValidationPipe,
@@ -28,7 +29,9 @@ import {
Header,
HttpException,
HttpStatus,
+ StreamableFile,
} from '@nestjs/common'
+import type { Response as ExpressResponse } from 'express'
import { OptionalJwtAccessTokenGuard } from '../auth/guards'
import { Auth, Public } from '../auth/decorators'
@@ -73,9 +76,11 @@ import { GetSessionsDto } from './dto/get-sessions.dto'
import { GetSessionDto } from './dto/get-session.dto'
import {
GetSessionReplayDto,
+ SessionReplayExportStartDto,
SessionReplayChunkDto,
SessionReplayStartDto,
} from './dto/session-replay.dto'
+import { SessionReplayExportService } from './session-replay-export.service'
import { GetProfilesDto } from './dto/get-profiles.dto'
import { GetProfileDto, GetProfileSessionsDto } from './dto/get-profile.dto'
import { ErrorDto } from './dto/error.dto'
@@ -240,6 +245,7 @@ export class AnalyticsController {
private readonly logger: AppLoggerService,
private readonly gscService: GSCService,
private readonly experimentService: ExperimentService,
+ private readonly sessionReplayExportService: SessionReplayExportService,
) {}
@ApiBearerAuth()
@@ -2760,6 +2766,79 @@ export class AnalyticsController {
return this.analyticsService.getSessionReplay(pid, psid, replayId)
}
+ @Post('session-replay/export')
+ @Auth(true, true)
+ async startSessionReplayExport(
+ @Body() data: SessionReplayExportStartDto,
+ @CurrentUserId() uid: string | null,
+ @Headers() headers: { 'x-password'?: string; 'user-agent'?: string },
+ @Ip() requestIp: string,
+ ) {
+ const { pid, psid, replayId } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+ await checkRateLimit(uid || ip || pid, 'session-replay-export-user', 5, 60)
+ await checkRateLimit(pid, 'session-replay-export-project', 20, 60)
+
+ this.logger.log(
+ `pid: ${pid}, psid: ${psid}, replayId: ${replayId || 'latest'}`,
+ 'POST /analytics/session-replay/export',
+ )
+
+ return this.sessionReplayExportService.startExport(pid, psid, replayId)
+ }
+
+ @Get('session-replay/export/:exportId')
+ @Auth(true, true)
+ async getSessionReplayExport(
+ @Param('exportId') exportId: string,
+ @CurrentUserId() uid: string | null,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const exportState =
+ await this.sessionReplayExportService.assertExportAccess(exportId)
+
+ await this.analyticsService.checkProjectAccess(
+ exportState.pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(exportState.pid)
+
+ return this.sessionReplayExportService.getExport(exportId)
+ }
+
+ @Get('session-replay/export/:exportId/download')
+ @Auth(true, true)
+ async downloadSessionReplayExport(
+ @Param('exportId') exportId: string,
+ @CurrentUserId() uid: string | null,
+ @Headers() headers: { 'x-password'?: string },
+ @Response({ passthrough: true }) response: ExpressResponse,
+ ): Promise<StreamableFile> {
+ const exportState =
+ await this.sessionReplayExportService.assertExportAccess(exportId)
+
+ await this.analyticsService.checkProjectAccess(
+ exportState.pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(exportState.pid)
+
+ return this.sessionReplayExportService.downloadExport(exportId, response)
+ }
+
@Get('profiles')
@Auth(true, true)
async getProfiles(
diff --git a/backend/apps/cloud/src/analytics/analytics.module.ts b/backend/apps/cloud/src/analytics/analytics.module.ts
index b8125aa36..2f4219963 100644
--- a/backend/apps/cloud/src/analytics/analytics.module.ts
+++ b/backend/apps/cloud/src/analytics/analytics.module.ts
@@ -1,5 +1,6 @@
import { Module, forwardRef } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
+import { BullModule } from '@nestjs/bullmq'
import { AnalyticsService } from './analytics.service'
import { AnalyticsController } from './analytics.controller'
@@ -13,6 +14,11 @@ import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
import { RevenueModule } from '../revenue/revenue.module'
import { ExperimentModule } from '../experiment/experiment.module'
+import {
+ SessionReplayExportService,
+ SESSION_REPLAY_EXPORT_QUEUE,
+} from './session-replay-export.service'
+import { SessionReplayExportProcessor } from './session-replay-export.processor'
@Module({
imports: [
@@ -22,12 +28,15 @@ import { ExperimentModule } from '../experiment/experiment.module'
ProjectModule,
forwardRef(() => RevenueModule),
forwardRef(() => ExperimentModule),
+ BullModule.registerQueue({ name: SESSION_REPLAY_EXPORT_QUEUE }),
],
providers: [
AnalyticsService,
BotDetectionService,
SaltService,
SessionReplayR2Service,
+ SessionReplayExportService,
+ SessionReplayExportProcessor,
HeartbeatGateway,
],
exports: [AnalyticsService, BotDetectionService, SaltService],
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 2739749f1..fa51b9448 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -1896,7 +1896,7 @@ export class AnalyticsService {
}
}
- async getSessionReplaySummary(pid: string, psid: string) {
+ async getSessionReplaySummary(pid: string, psid: string, replayId?: string) {
const { data } = await clickhouse
.query({
query: `
@@ -1912,12 +1912,13 @@ export class AnalyticsService {
FROM session_replay_chunks
WHERE pid = {pid:FixedString(12)}
AND psid = toUInt64OrNull({psid:String})
+ ${replayId ? 'AND replayId = {replayId:String}' : ''}
AND expiresAt > now()
GROUP BY replayId
ORDER BY lastCreated DESC
LIMIT 1
`,
- query_params: { pid, psid },
+ query_params: { pid, psid, replayId: replayId || '' },
})
.then((resultSet) =>
resultSet.json<{
@@ -2004,7 +2005,7 @@ export class AnalyticsService {
events.sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0))
return {
- replay: await this.getSessionReplaySummary(pid, psid),
+ replay: await this.getSessionReplaySummary(pid, psid, selectedReplayId),
events,
}
}
diff --git a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
index 6a5a96697..858c244f4 100644
--- a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
@@ -87,3 +87,5 @@ export class GetSessionReplayDto {
@MaxLength(80)
replayId?: string
}
+
+export class SessionReplayExportStartDto extends GetSessionReplayDto {}
diff --git a/backend/apps/cloud/src/analytics/session-replay-export.processor.ts b/backend/apps/cloud/src/analytics/session-replay-export.processor.ts
new file mode 100644
index 000000000..b09258643
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/session-replay-export.processor.ts
@@ -0,0 +1,32 @@
+import { Processor, WorkerHost } from '@nestjs/bullmq'
+import { Job } from 'bullmq'
+
+import {
+ SESSION_REPLAY_EXPORT_QUEUE,
+ SessionReplayExportJobData,
+ SessionReplayExportService,
+} from './session-replay-export.service'
+
+const concurrencyValue = Number(process.env.SESSION_REPLAY_EXPORT_CONCURRENCY)
+const concurrency =
+ Number.isFinite(concurrencyValue) && concurrencyValue > 0
+ ? Math.floor(concurrencyValue)
+ : 1
+
+@Processor(SESSION_REPLAY_EXPORT_QUEUE, { concurrency })
+export class SessionReplayExportProcessor extends WorkerHost {
+ constructor(
+ private readonly sessionReplayExportService: SessionReplayExportService,
+ ) {
+ super()
+ }
+
+ async process(job: Job<SessionReplayExportJobData>): Promise<void> {
+ if (job.data.type === 'cleanup') {
+ await this.sessionReplayExportService.cleanupExportJob(job.data)
+ return
+ }
+
+ await this.sessionReplayExportService.processExportJob(job.data)
+ }
+}
diff --git a/backend/apps/cloud/src/analytics/session-replay-export.service.ts b/backend/apps/cloud/src/analytics/session-replay-export.service.ts
new file mode 100644
index 000000000..51d4af556
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/session-replay-export.service.ts
@@ -0,0 +1,857 @@
+import { spawn } from 'child_process'
+import { randomUUID } from 'crypto'
+import * as fs from 'fs/promises'
+import * as os from 'os'
+import * as path from 'path'
+import {
+ BadRequestException,
+ Injectable,
+ Logger,
+ NotFoundException,
+ PayloadTooLargeException,
+ ServiceUnavailableException,
+ StreamableFile,
+} from '@nestjs/common'
+import { InjectQueue } from '@nestjs/bullmq'
+import { Queue } from 'bullmq'
+import type { Response } from 'express'
+
+import { redis } from '../common/constants'
+import { hash } from '../common/utils'
+import { AnalyticsService } from './analytics.service'
+import { SessionReplayR2Service } from './session-replay-r2.service'
+
+export const SESSION_REPLAY_EXPORT_QUEUE = 'session-replay-export'
+
+export type SessionReplayExportStatus =
+ | 'queued'
+ | 'processing'
+ | 'ready'
+ | 'failed'
+ | 'expired'
+
+export interface SessionReplayExportResponse {
+ exportId: string
+ status: SessionReplayExportStatus
+ progress: number
+ filename: string
+ expiresAt: string
+ error?: string
+}
+
+export type SessionReplayExportJobData =
+ | {
+ type: 'export'
+ exportId: string
+ pid: string
+ psid: string
+ replayId: string
+ }
+ | {
+ type: 'cleanup'
+ exportId: string
+ expiresAt: string
+ }
+
+export interface SessionReplayExportState extends SessionReplayExportResponse {
+ pid: string
+ psid: string
+ replayId: string
+ objectKey?: string
+ createdAt: string
+ updatedAt: string
+}
+
+type RrvideoEvent = Record<string, unknown> & {
+ type: number
+ timestamp: number
+ data: Record<string, unknown>
+}
+
+const DEFAULT_MAX_DURATION_MS = 30 * 60 * 1000
+const DEFAULT_MAX_EVENTS = 100000
+const DEFAULT_MAX_INPUT_BYTES = 150 * 1024 * 1024
+const DEFAULT_MAX_OUTPUT_BYTES = 500 * 1024 * 1024
+const DEFAULT_TTL_SECONDS = 24 * 60 * 60
+const DEFAULT_RENDER_TIMEOUT_MS = 60 * 60 * 1000
+const DEFAULT_VIEWPORT = { width: 1280, height: 720 }
+const TMP_DIR = path.resolve(os.tmpdir(), 'swetrix-session-replay-exports')
+const EXPORT_RENDERER_VERSION = 3
+const RRWEB_EVENT_TYPE_FULL_SNAPSHOT = 2
+const RRWEB_EVENT_TYPE_INCREMENTAL_SNAPSHOT = 3
+const RRWEB_EVENT_TYPE_META = 4
+const RRWEB_INCREMENTAL_SOURCE_VIEWPORT_RESIZE = 4
+
+const getPositiveEnvNumber = (key: string, fallback: number) => {
+ const value = Number(process.env[key])
+ return Number.isFinite(value) && value > 0 ? value : fallback
+}
+
+const getExportStateKey = (exportId: string) =>
+ `session-replay:export:${exportId}`
+
+@Injectable()
+export class SessionReplayExportService {
+ private readonly logger = new Logger(SessionReplayExportService.name)
+
+ private readonly maxDurationMs = getPositiveEnvNumber(
+ 'SESSION_REPLAY_EXPORT_MAX_DURATION_MS',
+ DEFAULT_MAX_DURATION_MS,
+ )
+
+ private readonly maxEvents = getPositiveEnvNumber(
+ 'SESSION_REPLAY_EXPORT_MAX_EVENTS',
+ DEFAULT_MAX_EVENTS,
+ )
+
+ private readonly maxInputBytes = getPositiveEnvNumber(
+ 'SESSION_REPLAY_EXPORT_MAX_INPUT_BYTES',
+ DEFAULT_MAX_INPUT_BYTES,
+ )
+
+ private readonly maxOutputBytes = getPositiveEnvNumber(
+ 'SESSION_REPLAY_EXPORT_MAX_OUTPUT_BYTES',
+ DEFAULT_MAX_OUTPUT_BYTES,
+ )
+
+ private readonly ttlSeconds = getPositiveEnvNumber(
+ 'SESSION_REPLAY_EXPORT_TTL_SECONDS',
+ DEFAULT_TTL_SECONDS,
+ )
+
+ private readonly renderTimeoutMs = getPositiveEnvNumber(
+ 'SESSION_REPLAY_EXPORT_RENDER_TIMEOUT_MS',
+ DEFAULT_RENDER_TIMEOUT_MS,
+ )
+
+ constructor(
+ private readonly analyticsService: AnalyticsService,
+ private readonly sessionReplayStorage: SessionReplayR2Service,
+ @InjectQueue(SESSION_REPLAY_EXPORT_QUEUE)
+ private readonly exportQueue: Queue<SessionReplayExportJobData>,
+ ) {}
+
+ async startExport(
+ pid: string,
+ psid: string,
+ replayId?: string,
+ ): Promise<SessionReplayExportResponse> {
+ if (!this.sessionReplayStorage.isConfigured()) {
+ throw new ServiceUnavailableException(
+ 'Session replay storage is not configured',
+ )
+ }
+
+ const replay = await this.analyticsService.getSessionReplaySummary(
+ pid,
+ psid,
+ replayId,
+ )
+
+ if (!replay?.hasReplay) {
+ throw new BadRequestException('Replay is no longer available')
+ }
+
+ this.validateReplayMetadata(replay.eventCount, replay.replayDuration)
+
+ const exportId = hash(
+ `${EXPORT_RENDERER_VERSION}:${pid}:${psid}:${replay.replayId}:${replay.eventCount}:${replay.replayDuration}`,
+ )
+ const existing = await this.getState(exportId)
+
+ if (existing && !this.shouldStartNewExport(existing)) {
+ return this.toResponse(existing)
+ }
+
+ if (existing?.objectKey) {
+ await this.sessionReplayStorage
+ .deleteObject(existing.objectKey)
+ .catch((reason) =>
+ this.logger.warn(
+ `Failed to delete stale session replay export ${exportId}: ${
+ reason instanceof Error ? reason.message : String(reason)
+ }`,
+ ),
+ )
+ }
+
+ const now = new Date()
+ const state: SessionReplayExportState = {
+ exportId,
+ pid,
+ psid,
+ replayId: replay.replayId,
+ status: 'queued',
+ progress: 0,
+ filename: this.getFilename(psid),
+ expiresAt: new Date(now.getTime() + this.ttlSeconds * 1000).toISOString(),
+ createdAt: now.toISOString(),
+ updatedAt: now.toISOString(),
+ }
+
+ await this.saveState(state)
+
+ try {
+ await this.exportQueue.add(
+ 'export-session-replay',
+ {
+ type: 'export',
+ exportId,
+ pid,
+ psid,
+ replayId: replay.replayId,
+ },
+ {
+ jobId: exportId,
+ attempts: 1,
+ removeOnComplete: true,
+ removeOnFail: true,
+ },
+ )
+ } catch (reason) {
+ await this.markFailed(state, reason)
+ throw new ServiceUnavailableException('Failed to start export')
+ }
+
+ return this.toResponse(state)
+ }
+
+ async getExport(exportId: string): Promise<SessionReplayExportResponse> {
+ const state = await this.getState(exportId)
+ if (!state) {
+ throw new NotFoundException('Export not found')
+ }
+
+ if (this.isExpired(state) && state.status !== 'expired') {
+ await this.expireState(state)
+ return this.toResponse({
+ ...state,
+ status: 'expired',
+ objectKey: undefined,
+ })
+ }
+
+ return this.toResponse(state)
+ }
+
+ async downloadExport(
+ exportId: string,
+ response: Response,
+ ): Promise<StreamableFile> {
+ const state = await this.getState(exportId)
+
+ if (!state || this.isExpired(state) || state.status === 'expired') {
+ throw new NotFoundException('Export not found')
+ }
+
+ if (state.status !== 'ready' || !state.objectKey) {
+ throw new BadRequestException('Export is not ready')
+ }
+
+ const object = await this.sessionReplayStorage.getObjectStream(
+ state.objectKey,
+ )
+
+ if (!object) {
+ await this.markFailed(state, new Error('Export file is missing'))
+ throw new NotFoundException('Export file not found')
+ }
+
+ response.setHeader('Content-Type', object.contentType || 'video/mp4')
+ response.setHeader(
+ 'Content-Disposition',
+ `attachment; filename="${state.filename}"`,
+ )
+ response.setHeader('Cache-Control', 'private, no-store')
+ if (object.contentLength) {
+ response.setHeader('Content-Length', object.contentLength)
+ }
+
+ return new StreamableFile(object.body)
+ }
+
+ async assertExportAccess(
+ exportId: string,
+ ): Promise<SessionReplayExportState> {
+ const state = await this.getState(exportId)
+ if (!state) {
+ throw new NotFoundException('Export not found')
+ }
+ return state
+ }
+
+ async processExportJob(
+ data: Extract<SessionReplayExportJobData, { type: 'export' }>,
+ ) {
+ const existing = await this.getState(data.exportId)
+ const state =
+ existing ||
+ ({
+ exportId: data.exportId,
+ pid: data.pid,
+ psid: data.psid,
+ replayId: data.replayId,
+ status: 'queued',
+ progress: 0,
+ filename: this.getFilename(data.psid),
+ expiresAt: new Date(Date.now() + this.ttlSeconds * 1000).toISOString(),
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ } satisfies SessionReplayExportState)
+
+ let workDir: string | null = null
+
+ try {
+ await this.updateState(state, { status: 'processing', progress: 5 })
+
+ const { replay, events } = await this.analyticsService.getSessionReplay(
+ data.pid,
+ data.psid,
+ data.replayId,
+ )
+
+ if (!replay?.hasReplay || !events.length) {
+ throw new Error('Replay is no longer available')
+ }
+
+ this.validateReplayMetadata(replay.eventCount, replay.replayDuration)
+ const exportEvents = this.prepareEventsForRrvideo(events)
+
+ const durationMs = this.getReplayDurationMs(
+ exportEvents,
+ replay.replayDuration,
+ )
+ this.validateReplayDuration(durationMs)
+
+ const serializedEvents = JSON.stringify(exportEvents)
+ const inputBytes = Buffer.byteLength(serializedEvents)
+
+ if (inputBytes > this.maxInputBytes) {
+ throw new Error('Replay is too large to export')
+ }
+
+ workDir = path.join(TMP_DIR, `${data.exportId}-${randomUUID()}`)
+ await fs.mkdir(workDir, { recursive: true, mode: 0o700 })
+
+ const inputPath = path.join(workDir, 'events.json')
+ const configPath = path.join(workDir, 'rrvideo.config.json')
+ const webmPath = path.join(workDir, 'replay.webm')
+ const mp4Path = path.join(workDir, 'replay.mp4')
+
+ await fs.writeFile(inputPath, serializedEvents, { mode: 0o600 })
+ await fs.writeFile(
+ configPath,
+ JSON.stringify(this.getRrvideoConfig(exportEvents)),
+ { mode: 0o600 },
+ )
+
+ await this.updateState(state, { status: 'processing', progress: 20 })
+
+ await this.runCommand(
+ this.getRrvideoBin(),
+ ['--input', inputPath, '--output', webmPath, '--config', configPath],
+ {
+ cwd: workDir,
+ rejectOutput: /Error initializing replayer|Failed to transform/i,
+ },
+ )
+
+ await this.updateState(state, { status: 'processing', progress: 70 })
+
+ await this.runCommand(
+ this.getFfmpegBin(),
+ [
+ '-y',
+ '-i',
+ webmPath,
+ '-c:v',
+ 'libx264',
+ '-pix_fmt',
+ 'yuv420p',
+ '-movflags',
+ '+faststart',
+ mp4Path,
+ ],
+ { cwd: workDir },
+ )
+
+ const outputStat = await fs.stat(mp4Path)
+ if (outputStat.size > this.maxOutputBytes) {
+ throw new Error('Replay export is too large to download')
+ }
+
+ await this.updateState(state, { status: 'processing', progress: 90 })
+
+ const objectKey = this.getObjectKey(data.pid, data.psid, data.exportId)
+ const output = await fs.readFile(mp4Path)
+ await this.sessionReplayStorage.putObject(objectKey, output, 'video/mp4')
+
+ await this.updateState(state, {
+ status: 'ready',
+ progress: 100,
+ objectKey,
+ error: undefined,
+ })
+
+ await this.exportQueue.add(
+ 'cleanup-session-replay-export',
+ {
+ type: 'cleanup',
+ exportId: data.exportId,
+ expiresAt: state.expiresAt,
+ },
+ {
+ jobId: `${data.exportId}:cleanup:${hash(state.expiresAt)}`,
+ delay: this.ttlSeconds * 1000,
+ attempts: 3,
+ removeOnComplete: true,
+ removeOnFail: true,
+ },
+ )
+ } catch (reason) {
+ await this.markFailed(state, reason)
+ throw reason
+ } finally {
+ if (workDir) {
+ await fs.rm(workDir, { recursive: true, force: true }).catch(() => null)
+ }
+ }
+ }
+
+ async cleanupExportJob(
+ data: Extract<SessionReplayExportJobData, { type: 'cleanup' }>,
+ ) {
+ const state = await this.getState(data.exportId)
+ if (!state) return
+
+ if (state.expiresAt !== data.expiresAt) return
+
+ if (state.objectKey) {
+ await this.sessionReplayStorage
+ .deleteObject(state.objectKey)
+ .catch((reason) =>
+ this.logger.warn(
+ `Failed to delete session replay export ${data.exportId}: ${
+ reason instanceof Error ? reason.message : String(reason)
+ }`,
+ ),
+ )
+ }
+
+ await this.expireState(state)
+ }
+
+ private validateReplayMetadata(eventCount: number, durationSeconds: number) {
+ if (eventCount > this.maxEvents) {
+ throw new PayloadTooLargeException('Replay has too many events to export')
+ }
+
+ this.validateReplayDuration(durationSeconds * 1000)
+ }
+
+ private validateReplayDuration(durationMs: number) {
+ if (durationMs > this.maxDurationMs) {
+ throw new PayloadTooLargeException('Replay is too long to export')
+ }
+ }
+
+ private prepareEventsForRrvideo(events: Record<string, unknown>[]) {
+ const normalised: Array<{ event: RrvideoEvent; index: number }> = []
+
+ events.forEach((event, index) => {
+ const normalisedEvent = this.normaliseReplayEvent(event)
+ if (normalisedEvent) {
+ normalised.push({ event: normalisedEvent, index })
+ }
+ })
+
+ normalised.sort(
+ (a, b) => a.event.timestamp - b.event.timestamp || a.index - b.index,
+ )
+
+ if (!normalised.length) {
+ throw new Error('Replay is no longer available')
+ }
+
+ const prepared = normalised.map(({ event }) => event)
+ if (
+ !prepared.some((event) => event.type === RRWEB_EVENT_TYPE_FULL_SNAPSHOT)
+ ) {
+ throw new Error('Replay is missing a full snapshot')
+ }
+
+ const viewport = this.getReplayViewport(prepared)
+ const href = this.getReplayHref(prepared)
+ let hasMeta = false
+ const withMeta = prepared.map((event) => {
+ if (event.type !== RRWEB_EVENT_TYPE_META) return event
+
+ hasMeta = true
+ return {
+ ...event,
+ data: {
+ ...this.getEventData(event),
+ href,
+ width: viewport.width,
+ height: viewport.height,
+ },
+ }
+ })
+
+ if (!hasMeta) {
+ withMeta.unshift({
+ type: RRWEB_EVENT_TYPE_META,
+ timestamp: withMeta[0].timestamp,
+ data: {
+ href,
+ width: viewport.width,
+ height: viewport.height,
+ },
+ })
+ }
+
+ return withMeta
+ }
+
+ private normaliseReplayEvent(
+ event: Record<string, unknown>,
+ ): RrvideoEvent | null {
+ const timestamp = Number(event.timestamp)
+ const type = this.normaliseEventType(event.type)
+
+ if (!Number.isFinite(timestamp) || type === null) {
+ return null
+ }
+
+ return {
+ ...event,
+ type,
+ timestamp,
+ data: this.getEventData(event),
+ }
+ }
+
+ private normaliseEventType(value: unknown) {
+ const numeric = Number(value)
+ if (Number.isInteger(numeric)) return numeric
+
+ if (typeof value !== 'string') return null
+
+ const eventTypes: Record<string, number> = {
+ DomContentLoaded: 0,
+ Load: 1,
+ FullSnapshot: RRWEB_EVENT_TYPE_FULL_SNAPSHOT,
+ IncrementalSnapshot: RRWEB_EVENT_TYPE_INCREMENTAL_SNAPSHOT,
+ Meta: RRWEB_EVENT_TYPE_META,
+ Custom: 5,
+ Plugin: 6,
+ Asset: 7,
+ }
+
+ return eventTypes[value] ?? null
+ }
+
+ private getEventData(event: Record<string, unknown>) {
+ return event.data && typeof event.data === 'object'
+ ? (event.data as Record<string, unknown>)
+ : {}
+ }
+
+ private getReplayDurationMs(
+ events: Record<string, unknown>[],
+ fallbackDurationSeconds: number,
+ ) {
+ let minTimestamp = Infinity
+ let maxTimestamp = -Infinity
+
+ for (const event of events) {
+ const timestamp = Number(event.timestamp)
+ if (!Number.isFinite(timestamp)) continue
+
+ minTimestamp = Math.min(minTimestamp, timestamp)
+ maxTimestamp = Math.max(maxTimestamp, timestamp)
+ }
+
+ if (!Number.isFinite(minTimestamp) || !Number.isFinite(maxTimestamp)) {
+ return fallbackDurationSeconds * 1000
+ }
+
+ return Math.max(fallbackDurationSeconds * 1000, maxTimestamp - minTimestamp)
+ }
+
+ private getRrvideoConfig(events: Record<string, unknown>[]) {
+ const viewport = this.getReplayViewport(events)
+
+ return {
+ width: viewport.width,
+ height: viewport.height,
+ speed: 1,
+ skipInactive: false,
+ mouseTail: true,
+ }
+ }
+
+ private getReplayViewport(events: Record<string, unknown>[]) {
+ let maxWidth = 0
+ let maxHeight = 0
+
+ for (const event of events) {
+ const data = this.getEventData(event)
+ const isViewportEvent =
+ Number(event.type) === RRWEB_EVENT_TYPE_META ||
+ (Number(event.type) === RRWEB_EVENT_TYPE_INCREMENTAL_SNAPSHOT &&
+ Number(data.source) === RRWEB_INCREMENTAL_SOURCE_VIEWPORT_RESIZE)
+
+ if (!isViewportEvent) continue
+
+ const viewport = this.getViewportCandidate(data)
+ if (!viewport) continue
+
+ maxWidth = Math.max(maxWidth, viewport.width)
+ maxHeight = Math.max(maxHeight, viewport.height)
+ }
+
+ if (!maxWidth || !maxHeight) {
+ return DEFAULT_VIEWPORT
+ }
+
+ return this.clampViewport({ width: maxWidth, height: maxHeight })
+ }
+
+ private getViewportCandidate(data: Record<string, unknown>) {
+ const width = Number(data.width)
+ const height = Number(data.height)
+
+ if (
+ !Number.isFinite(width) ||
+ !Number.isFinite(height) ||
+ width <= 0 ||
+ height <= 0
+ ) {
+ return null
+ }
+
+ return {
+ width: Math.round(width),
+ height: Math.round(height),
+ }
+ }
+
+ private clampViewport(viewport: { width: number; height: number }) {
+ return {
+ width: Math.min(1920, Math.max(320, viewport.width)),
+ height: Math.min(1080, Math.max(240, viewport.height)),
+ }
+ }
+
+ private getReplayHref(events: Record<string, unknown>[]) {
+ for (const event of events) {
+ if (Number(event.type) !== RRWEB_EVENT_TYPE_META) continue
+
+ const href = this.getEventData(event).href
+ if (typeof href === 'string' && href) {
+ return href
+ }
+ }
+
+ return 'about:blank'
+ }
+
+ private async runCommand(
+ command: string,
+ args: string[],
+ options: { cwd?: string; rejectOutput?: RegExp } = {},
+ ) {
+ await new Promise<void>((resolve, reject) => {
+ let settled = false
+ let output = ''
+ const child = spawn(command, args, {
+ cwd: options.cwd,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ const timeout = setTimeout(() => {
+ if (settled) return
+ settled = true
+ child.kill('SIGKILL')
+ reject(new Error(`${path.basename(command)} timed out`))
+ }, this.renderTimeoutMs)
+
+ const captureOutput = (chunk: Buffer) => {
+ output = `${output}${chunk.toString()}`
+ if (output.length > 8000) {
+ output = output.slice(-8000)
+ }
+ }
+
+ child.stdout.on('data', captureOutput)
+ child.stderr.on('data', captureOutput)
+
+ child.on('error', (reason) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timeout)
+ reject(reason)
+ })
+
+ child.on('close', (code) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timeout)
+
+ if (code === 0) {
+ if (options.rejectOutput?.test(output)) {
+ reject(
+ new Error(
+ `${path.basename(command)} reported a renderer error: ${output}`,
+ ),
+ )
+ return
+ }
+
+ resolve()
+ return
+ }
+
+ reject(
+ new Error(
+ `${path.basename(command)} failed with status ${code}: ${output}`,
+ ),
+ )
+ })
+ })
+ }
+
+ private getRrvideoBin() {
+ return (
+ process.env.RRVIDEO_BIN ||
+ path.join(
+ process.cwd(),
+ 'node_modules',
+ '.bin',
+ process.platform === 'win32' ? 'rrvideo.cmd' : 'rrvideo',
+ )
+ )
+ }
+
+ private getFfmpegBin() {
+ return process.env.FFMPEG_BIN || 'ffmpeg'
+ }
+
+ private getObjectKey(pid: string, psid: string, exportId: string) {
+ return ['session-replay-exports', pid, psid, `${exportId}.mp4`].join('/')
+ }
+
+ private getFilename(psid: string) {
+ const safePsid = psid.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 80)
+ return `swetrix-replay-${safePsid || 'session'}.mp4`
+ }
+
+ private async getState(
+ exportId: string,
+ ): Promise<SessionReplayExportState | null> {
+ const raw = await redis.get(getExportStateKey(exportId))
+ if (!raw) return null
+
+ try {
+ return JSON.parse(raw) as SessionReplayExportState
+ } catch {
+ return null
+ }
+ }
+
+ private async saveState(state: SessionReplayExportState) {
+ await redis.set(
+ getExportStateKey(state.exportId),
+ JSON.stringify(state),
+ 'EX',
+ this.ttlSeconds + 24 * 60 * 60,
+ )
+ }
+
+ private async updateState(
+ state: SessionReplayExportState,
+ update: Partial<SessionReplayExportState>,
+ ) {
+ const next = {
+ ...state,
+ ...update,
+ updatedAt: new Date().toISOString(),
+ }
+ Object.assign(state, next)
+ await this.saveState(next)
+ return next
+ }
+
+ private async markFailed(state: SessionReplayExportState, reason: unknown) {
+ this.logger.error(
+ `Session replay export ${state.exportId} failed: ${this.getDetailedError(
+ reason,
+ )}`,
+ )
+
+ await this.updateState(state, {
+ status: 'failed',
+ progress: 100,
+ error: this.getPublicError(reason),
+ objectKey: undefined,
+ })
+ }
+
+ private async expireState(state: SessionReplayExportState) {
+ await this.updateState(state, {
+ status: 'expired',
+ progress: 100,
+ objectKey: undefined,
+ error: undefined,
+ })
+ }
+
+ private isExpired(state: SessionReplayExportState) {
+ return Date.parse(state.expiresAt) <= Date.now()
+ }
+
+ private shouldStartNewExport(state: SessionReplayExportState) {
+ return (
+ this.isExpired(state) ||
+ state.status === 'expired' ||
+ state.status === 'failed'
+ )
+ }
+
+ private getPublicError(reason: unknown) {
+ const message = this.getDetailedError(reason)
+
+ if (message.includes('Replay is no longer available')) {
+ return 'Replay is no longer available'
+ }
+
+ if (
+ message.includes('too large') ||
+ message.includes('too long') ||
+ message.includes('too many events')
+ ) {
+ return 'Replay is too large to export'
+ }
+
+ return 'Could not export replay to MP4'
+ }
+
+ private getDetailedError(reason: unknown) {
+ return reason instanceof Error
+ ? reason.stack || reason.message
+ : String(reason)
+ }
+
+ private toResponse(
+ state: SessionReplayExportState,
+ ): SessionReplayExportResponse {
+ return {
+ exportId: state.exportId,
+ status: state.status,
+ progress: state.progress,
+ filename: state.filename,
+ expiresAt: state.expiresAt,
+ ...(state.error ? { error: state.error } : {}),
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/analytics/session-replay-r2.service.ts b/backend/apps/cloud/src/analytics/session-replay-r2.service.ts
index 7479ee516..21949956a 100644
--- a/backend/apps/cloud/src/analytics/session-replay-r2.service.ts
+++ b/backend/apps/cloud/src/analytics/session-replay-r2.service.ts
@@ -1,4 +1,5 @@
import crypto from 'crypto'
+import { Readable } from 'stream'
import { Injectable } from '@nestjs/common'
interface R2Config {
@@ -80,6 +81,32 @@ export class SessionReplayR2Service {
return Buffer.from(await response.arrayBuffer())
}
+ async getObjectStream(key: string): Promise<{
+ body: Readable
+ contentLength?: string
+ contentType?: string
+ } | null> {
+ const response = await this.signedFetch('GET', key)
+
+ if (response.status === 404) {
+ return null
+ }
+
+ if (!response.ok) {
+ throw new Error(`R2 GET failed with status ${response.status}`)
+ }
+
+ if (!response.body) {
+ return null
+ }
+
+ return {
+ body: Readable.fromWeb(response.body as any),
+ contentLength: response.headers.get('content-length') || undefined,
+ contentType: response.headers.get('content-type') || undefined,
+ }
+ }
+
async deleteObject(key: string): Promise<void> {
const response = await this.signedFetch('DELETE', key)
diff --git a/backend/package-lock.json b/backend/package-lock.json
index aa18c31be..4eaa70d92 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -64,6 +64,8 @@
"php-serialize": "^5.1.3",
"reflect-metadata": "^0.2.2",
"request-filtering-agent": "^3.2.0",
+ "rrweb": "2.0.1",
+ "rrvideo": "2.0.1",
"rxjs": "^7.8.2",
"sns-payload-validator": "^2.1.0",
"socket.io": "^4.8.3",
@@ -2214,6 +2216,37 @@
"npm": ">=5.10.0"
}
},
+ "node_modules/@open-tech-world/cli-progress-bar": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@open-tech-world/cli-progress-bar/-/cli-progress-bar-2.0.2.tgz",
+ "integrity": "sha512-miNmdKNdKp7Lhy295wxnJcWFrbIAoQmypoCynlG8HTQPxsG5dhOpPL5udsZFoW99RxcLAj2JTCaEhrosTzPE3g==",
+ "deprecated": "Please use @opentf/cli-pbar",
+ "license": "MIT",
+ "dependencies": {
+ "@open-tech-world/es-cli-styles": "^0.3.0",
+ "@open-tech-world/es-utils": "^0.10.0"
+ }
+ },
+ "node_modules/@open-tech-world/es-cli-styles": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@open-tech-world/es-cli-styles/-/es-cli-styles-0.3.0.tgz",
+ "integrity": "sha512-0SyxBAUkUDkjt83snx1QvPDk6zJJIb/xRbY0daWGG6ONCfx5RITxc0qty2tLmyBNsCM41+V1shtHNeSrEBu8KQ==",
+ "deprecated": "Please use @opentf/cli-styles",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ }
+ },
+ "node_modules/@open-tech-world/es-utils": {
+ "version": "0.10.0",
+ "resolved": "https://registry.npmjs.org/@open-tech-world/es-utils/-/es-utils-0.10.0.tgz",
+ "integrity": "sha512-JqpxcVk3Go4RAArI3oB18fhIMeeuNSThwmSQM7ScygVv2/AHRAxkkiodtggC7QniJvLs7i5AzL9pILNvAEBYDg==",
+ "deprecated": "Please use @opentf/utils",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ }
+ },
"node_modules/@opentelemetry/api": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
@@ -4132,6 +4165,44 @@
"integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==",
"license": "BSD-3-Clause"
},
+ "node_modules/@rrweb/packer": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/packer/-/packer-2.0.1.tgz",
+ "integrity": "sha512-2U8RkVe+ZK3gTtmKjJKjoh6QL1Q6wIlt3sBTJeCPERLr9e0JIimNrZ1+bog1L30CTVP3ULuDf5Ba7RZO+QNcHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@rrweb/types": "^2.0.1",
+ "fflate": "^0.4.4"
+ }
+ },
+ "node_modules/@rrweb/packer/node_modules/fflate": {
+ "version": "0.4.8",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.8.tgz",
+ "integrity": "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==",
+ "license": "MIT"
+ },
+ "node_modules/@rrweb/replay": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/replay/-/replay-2.0.1.tgz",
+ "integrity": "sha512-UrZONirb8o4t0urg1aJ8aMSWhNHvJ3a2usuVbPJIm/edyFbwTvvY9sg/rrXccyXOntFhhp73R5nCretODRZcCw==",
+ "license": "MIT",
+ "dependencies": {
+ "@rrweb/types": "^2.0.1",
+ "rrweb": "^2.0.1"
+ }
+ },
+ "node_modules/@rrweb/types": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.1.tgz",
+ "integrity": "sha512-x8cNaKFxdvS0/5IfKOj1xG8Htnw1fUwqoPqgP61bOaWqZL6t9UtRPpO9ZlMB2z+FiTxg9zlFFL+Da4ZpFuhoiA==",
+ "license": "MIT"
+ },
+ "node_modules/@rrweb/utils": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.1.tgz",
+ "integrity": "sha512-t+b+4rB23/e4EpoGMdPUr6cKtDsFuOb3LxA9IHE8e3A/Xo0nMUfH0bkwqdpUNa/VGDOdiGeG3bhHjuO9zWX54g==",
+ "license": "MIT"
+ },
"node_modules/@scarf/scarf": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",
@@ -4603,6 +4674,12 @@
"node": ">=10"
}
},
+ "node_modules/@tsconfig/svelte": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-1.0.13.tgz",
+ "integrity": "sha512-5lYJP45Xllo4yE/RUBccBT32eBlRDbqN8r1/MIvQbKxW3aFqaYPCNgm8D5V20X4ShHcwvYWNlKg3liDh1MlBoA==",
+ "license": "MIT"
+ },
"node_modules/@tybys/wasm-util": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
@@ -4663,6 +4740,12 @@
"@types/node": "*"
}
},
+ "node_modules/@types/css-font-loading-module": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/@types/css-font-loading-module/-/css-font-loading-module-0.0.7.tgz",
+ "integrity": "sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==",
+ "license": "MIT"
+ },
"node_modules/@types/ejs": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@types/ejs/-/ejs-3.1.5.tgz",
@@ -5175,6 +5258,12 @@
"@xtuc/long": "4.2.2"
}
},
+ "node_modules/@xstate/fsm": {
+ "version": "1.6.5",
+ "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.6.5.tgz",
+ "integrity": "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==",
+ "license": "MIT"
+ },
"node_modules/@xtuc/ieee754": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
@@ -5581,6 +5670,15 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
+ "node_modules/base64-arraybuffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
+ "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -8308,7 +8406,6 @@
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
- "dev": true,
"license": "ISC"
},
"node_modules/handlebars": {
@@ -9151,7 +9248,6 @@
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
"integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
@@ -9422,9 +9518,9 @@
}
},
"node_modules/liquidjs": {
- "version": "10.25.7",
- "resolved": "https://registry.npmjs.org/liquidjs/-/liquidjs-10.25.7.tgz",
- "integrity": "sha512-rPCjJLiD4eDhQjvv964AeXFC+HbeYBbZrd7Z82Q6hqv1lX7G+5w4SJcKLn9CAAAwHI4aS3dTdo083UB79K3pDA==",
+ "version": "10.27.0",
+ "resolved": "https://registry.npmjs.org/liquidjs/-/liquidjs-10.27.0.tgz",
+ "integrity": "sha512-tw/OA59K7aIBlMKIrKlumr37fiZUheShVHXY8cVctWisgY1p9mc5hreOvlreoS0wTiwlWk14Ya7305c2a/Cg5w==",
"license": "MIT",
"optional": true,
"dependencies": {
@@ -9884,6 +9980,12 @@
"node": ">=16 || 14 >=14.17"
}
},
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
"node_modules/mjml": {
"version": "5.0.0-beta.2",
"resolved": "https://registry.npmjs.org/mjml/-/mjml-5.0.0-beta.2.tgz",
@@ -10559,7 +10661,6 @@
}
],
"license": "MIT",
- "optional": true,
"bin": {
"nanoid": "bin/nanoid.cjs"
},
@@ -11513,7 +11614,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
- "devOptional": true,
"license": "ISC"
},
"node_modules/picomatch": {
@@ -11529,6 +11629,50 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/playwright": {
+ "version": "1.60.0",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
+ "integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.60.0"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.60.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
+ "integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright/node_modules/fsevents": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
"node_modules/pluralize": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz",
@@ -11567,7 +11711,6 @@
}
],
"license": "MIT",
- "optional": true,
"dependencies": {
"nanoid": "^3.3.12",
"picocolors": "^1.1.1",
@@ -12873,6 +13016,82 @@
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
+ "node_modules/rrdom": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.1.tgz",
+ "integrity": "sha512-z8GdQWFmVfa8GpcGkAqfBXseb89z0ciTPSBkID0qr0i6KHCye1MdQ4VoXFf0Ejp3ELe/c7AObu4zsbSbMT+hiw==",
+ "license": "MIT",
+ "dependencies": {
+ "rrweb-snapshot": "^2.0.1"
+ }
+ },
+ "node_modules/rrvideo": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrvideo/-/rrvideo-2.0.1.tgz",
+ "integrity": "sha512-gDf0oE1nLU4xMqdkm3nvAKWYLzkAIVSXOIL63CZZf75hqAzavEOJu3P0C7778z8yk18d2Yj79SdKmZyHSuc2IA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "@open-tech-world/cli-progress-bar": "^2.0.2",
+ "fs-extra": "^11.1.1",
+ "minimist": "^1.2.5",
+ "playwright": "^1.60.0",
+ "rrweb-player": "^2.0.1"
+ },
+ "bin": {
+ "rrvideo": "build/cli.js"
+ }
+ },
+ "node_modules/rrvideo/node_modules/fs-extra": {
+ "version": "11.3.5",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.5.tgz",
+ "integrity": "sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==",
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
+ "node_modules/rrweb": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.1.tgz",
+ "integrity": "sha512-MQYzOtI7aZft9ffDMT6rmRSAj6hO4W6T7iA4eB9Mtcuiv3M7DbnnxDMrcPW0sQXepgYN46YhfSKe75d/mlUHrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@rrweb/types": "^2.0.1",
+ "@rrweb/utils": "^2.0.1",
+ "@types/css-font-loading-module": "0.0.7",
+ "@xstate/fsm": "^1.4.0",
+ "base64-arraybuffer": "^1.0.1",
+ "mitt": "^3.0.0",
+ "rrdom": "^2.0.1",
+ "rrweb-snapshot": "^2.0.1"
+ }
+ },
+ "node_modules/rrweb-player": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb-player/-/rrweb-player-2.0.1.tgz",
+ "integrity": "sha512-v8PVnOy7Q3kXqWriGuzZo4ndGEV06nCMRkH/jSHweJfTLwpLqb2evgMj0S5FwQLsN2X1VM+L2/i7QWGJfgj9zw==",
+ "license": "MIT",
+ "dependencies": {
+ "@rrweb/packer": "^2.0.1",
+ "@rrweb/replay": "^2.0.1",
+ "@tsconfig/svelte": "^1.0.0"
+ }
+ },
+ "node_modules/rrweb-snapshot": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.1.tgz",
+ "integrity": "sha512-H8TA29ct2tpYtr5oaB0N+ksRY9bhEErfAYcKbce4+w8lqEUQChpKZd41HpBJLkp04b5QUfWUg4v6r9Okf8r7vA==",
+ "license": "MIT",
+ "dependencies": {
+ "postcss": "^8.4.38"
+ }
+ },
"node_modules/run-applescript": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-5.0.0.tgz",
@@ -13393,7 +13612,6 @@
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"license": "BSD-3-Clause",
- "optional": true,
"engines": {
"node": ">=0.10.0"
}
@@ -14469,7 +14687,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.0.0"
diff --git a/backend/package.json b/backend/package.json
index a5a267262..4216a33a1 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -11,6 +11,7 @@
"build": "npm run refresh-submodules && node --max-old-space-size=4096 ./node_modules/@nestjs/cli/bin/nest.js build cloud && mv apps/cloud/dist dist && npm run sentry:sourcemaps",
"build:no-submodules-refresh": "node --max-old-space-size=4096 ./node_modules/@nestjs/cli/bin/nest.js build cloud && mv apps/cloud/dist dist && npm run sentry:sourcemaps",
"postbuild": "cp .env dist/.env",
+ "postinstall": "node scripts/patch-rrvideo.js",
"format": "oxfmt --write apps/community/src apps/cloud/src",
"format:check": "oxfmt --check apps/community/src apps/cloud/src",
"clickhouse:initialise": "node migrations/clickhouse/initialise_selfhosted.js",
@@ -85,6 +86,8 @@
"php-serialize": "^5.1.3",
"reflect-metadata": "^0.2.2",
"request-filtering-agent": "^3.2.0",
+ "rrweb": "2.0.1",
+ "rrvideo": "2.0.1",
"rxjs": "^7.8.2",
"sns-payload-validator": "^2.1.0",
"socket.io": "^4.8.3",
diff --git a/backend/scripts/patch-rrvideo.js b/backend/scripts/patch-rrvideo.js
new file mode 100644
index 000000000..711b21ebd
--- /dev/null
+++ b/backend/scripts/patch-rrvideo.js
@@ -0,0 +1,116 @@
+const fs = require('fs')
+const path = require('path')
+
+const packagePath = require.resolve('rrvideo/package.json')
+const packageDir = path.dirname(packagePath)
+const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'))
+
+if (packageJson.version !== '2.0.1') {
+ throw new Error(`Unsupported rrvideo version: ${packageJson.version}`)
+}
+
+const filePath = path.join(packageDir, 'build', 'index.js')
+let source = fs.readFileSync(filePath, 'utf8')
+
+const playerBundle =
+ "require.resolve('rrweb-player'), '../../dist/rrweb-player.umd.cjs'"
+const rrwebBundle = "require.resolve('rrweb'), '../../dist/rrweb.umd.cjs'"
+
+if (source.includes(playerBundle)) {
+ source = source.replace(playerBundle, rrwebBundle)
+} else if (!source.includes(rrwebBundle)) {
+ throw new Error('Could not find rrvideo player bundle path')
+}
+
+const defaultResolutionRatio = ' resolutionRatio: 0.8,'
+const oneToOneResolutionRatio = ' resolutionRatio: 0.4,'
+
+if (source.includes(defaultResolutionRatio)) {
+ source = source.replace(defaultResolutionRatio, oneToOneResolutionRatio)
+} else if (!source.includes(oneToOneResolutionRatio)) {
+ throw new Error('Could not find rrvideo resolution ratio')
+}
+
+const defaultPageStyle =
+ ' <style>html, body {padding: 0; border: none; margin: 0;}</style>'
+const exportPageStyle = [
+ ' <style>',
+ ' html, body {',
+ ' width: 100%;',
+ ' height: 100%;',
+ ' padding: 0;',
+ ' border: none;',
+ ' margin: 0;',
+ ' overflow: hidden;',
+ ' background: #fff;',
+ ' }',
+ ' .replayer-wrapper {',
+ ' position: relative;',
+ ' overflow: hidden;',
+ ' background: #fff;',
+ ' transform: none !important;',
+ ' transform-origin: top left;',
+ ' }',
+ ' .replayer-wrapper iframe {',
+ ' border: 0;',
+ ' }',
+ ' </style>',
+].join('\n')
+
+if (source.includes(defaultPageStyle)) {
+ source = source.replace(defaultPageStyle, exportPageStyle)
+} else if (!source.includes(exportPageStyle)) {
+ throw new Error('Could not find rrvideo HTML page style')
+}
+
+const blockStart = source.indexOf(
+ ' const userConfig = ${JSON.stringify((config === null',
+)
+const blockEndMarker = [
+ ' } catch (error) {',
+ " console.error('Error initializing replayer:', error);",
+ ' window.onReplayFinish();',
+ ' }',
+].join('\n')
+const blockEnd = source.indexOf(blockEndMarker, blockStart)
+
+if (blockStart === -1 || blockEnd === -1) {
+ throw new Error('Could not find rrvideo HTML player block')
+}
+
+const blockReplacement = [
+ ' const userConfig = ${JSON.stringify((config === null || config === void 0 ? void 0 : config.rrwebPlayer) || {})};',
+ ' try {',
+ ' const insertStyleRules = Array.isArray(userConfig.insertStyleRules) ? userConfig.insertStyleRules : [];',
+ ' window.replayer = new rrweb.Replayer(events, {',
+ ' ...userConfig,',
+ ' root: document.body,',
+ ' insertStyleRules: [...insertStyleRules, \'html, body { background-color: #fff; }\'],',
+ ' });',
+ ' const resizeWrapper = () => {',
+ " const wrapper = document.querySelector('.replayer-wrapper');",
+ ' if (!wrapper) return;',
+ " wrapper.style.width = String(userConfig.width || window.innerWidth) + 'px';",
+ " wrapper.style.height = String(userConfig.height || window.innerHeight) + 'px';",
+ ' };',
+ ' resizeWrapper();',
+ " window.replayer.on('finish', () => window.onReplayFinish());",
+ " window.replayer.on('resize', resizeWrapper);",
+ ' setTimeout(() => window.replayer.play(), 0);',
+ ' } catch (error) {',
+ " console.error('Error initializing replayer:', error);",
+ ' window.onReplayFinish();',
+ ' }',
+].join('\n')
+
+const patched =
+ source.slice(0, blockStart) +
+ blockReplacement +
+ source.slice(blockEnd + blockEndMarker.length)
+
+if (patched === fs.readFileSync(filePath, 'utf8')) {
+ console.log('rrvideo patch already applied')
+} else {
+ fs.writeFileSync(filePath, patched)
+ console.log('Patched rrvideo to render with rrweb Replayer')
+}
diff --git a/packages/tracker-js/package-lock.json b/packages/tracker-js/package-lock.json
index e69b0dfea..cd566bc12 100644
--- a/packages/tracker-js/package-lock.json
+++ b/packages/tracker-js/package-lock.json
@@ -9,7 +9,7 @@
"version": "4.2.0",
"license": "MIT",
"dependencies": {
- "rrweb": "2.0.0"
+ "rrweb": "2.0.1"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^29.0.2",
@@ -1726,15 +1726,15 @@
]
},
"node_modules/@rrweb/types": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.0.tgz",
- "integrity": "sha512-p76i3Bdm/cjb/6NGqmFj0LkGXqC2dXs70AwirgVAsE1ndIa00TJo48La5yobHLsBOk5bfRHy6Yd+9O9VFKhAwQ==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.1.tgz",
+ "integrity": "sha512-x8cNaKFxdvS0/5IfKOj1xG8Htnw1fUwqoPqgP61bOaWqZL6t9UtRPpO9ZlMB2z+FiTxg9zlFFL+Da4ZpFuhoiA==",
"license": "MIT"
},
"node_modules/@rrweb/utils": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.0.tgz",
- "integrity": "sha512-0Q9djyxlwG1fs1TxT7VnKtt33tHku6PENlUAKSXZg8QSSI6aUXdCNZkkBt3JAgbBYVrGhQsYrz+DkCdAXqxs1w==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.1.tgz",
+ "integrity": "sha512-t+b+4rB23/e4EpoGMdPUr6cKtDsFuOb3LxA9IHE8e3A/Xo0nMUfH0bkwqdpUNa/VGDOdiGeG3bhHjuO9zWX54g==",
"license": "MIT"
},
"node_modules/@sinclair/typebox": {
@@ -4979,28 +4979,28 @@
}
},
"node_modules/rrdom": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.0.tgz",
- "integrity": "sha512-Yv+T/IBngNEjhbRv6yJzKdbhgMOiRCV+UA3R0HOpx4yySc8vl4I11Xr5BxCYrnt00l7CGjHbFB9VULEvcg1u6w==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.1.tgz",
+ "integrity": "sha512-z8GdQWFmVfa8GpcGkAqfBXseb89z0ciTPSBkID0qr0i6KHCye1MdQ4VoXFf0Ejp3ELe/c7AObu4zsbSbMT+hiw==",
"license": "MIT",
"dependencies": {
- "rrweb-snapshot": "^2.0.0"
+ "rrweb-snapshot": "^2.0.1"
}
},
"node_modules/rrweb": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.0.tgz",
- "integrity": "sha512-ID7NE8OdfAbxZKlTPc/EdL/8sLhTOVB1aZKoQ/M0peKGYB7dIDj0hsdJo+OVXfpiYMTtGzXnKfnMVUj4LnsrhQ==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.1.tgz",
+ "integrity": "sha512-MQYzOtI7aZft9ffDMT6rmRSAj6hO4W6T7iA4eB9Mtcuiv3M7DbnnxDMrcPW0sQXepgYN46YhfSKe75d/mlUHrQ==",
"license": "MIT",
"dependencies": {
- "@rrweb/types": "^2.0.0",
- "@rrweb/utils": "^2.0.0",
+ "@rrweb/types": "^2.0.1",
+ "@rrweb/utils": "^2.0.1",
"@types/css-font-loading-module": "0.0.7",
"@xstate/fsm": "^1.4.0",
"base64-arraybuffer": "^1.0.1",
"mitt": "^3.0.0",
- "rrdom": "^2.0.0",
- "rrweb-snapshot": "^2.0.0"
+ "rrdom": "^2.0.1",
+ "rrweb-snapshot": "^2.0.1"
}
},
"node_modules/rrweb-cssom": {
@@ -5011,9 +5011,9 @@
"license": "MIT"
},
"node_modules/rrweb-snapshot": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.0.tgz",
- "integrity": "sha512-mDYvvHVXYUD6wZj2AGz5UuupnYnhrWUmF+Hm+haZtVPx8bK3hpAMpu7YjPAoHVluv6KZJNJvVb/6HeBKwXTAvA==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.1.tgz",
+ "integrity": "sha512-H8TA29ct2tpYtr5oaB0N+ksRY9bhEErfAYcKbce4+w8lqEUQChpKZd41HpBJLkp04b5QUfWUg4v6r9Okf8r7vA==",
"license": "MIT",
"dependencies": {
"postcss": "^8.4.38"
diff --git a/packages/tracker-js/package.json b/packages/tracker-js/package.json
index 18a66052d..4f9c38b5d 100644
--- a/packages/tracker-js/package.json
+++ b/packages/tracker-js/package.json
@@ -45,7 +45,7 @@
"test:coverage": "jest --coverage"
},
"dependencies": {
- "rrweb": "2.0.0"
+ "rrweb": "2.0.1"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^29.0.2",
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 4e390a841..a506d6aef 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -1146,6 +1146,22 @@ export interface SessionReplayResponse {
events: Record<string, unknown>[]
}
+export type SessionReplayExportStatus =
+ | 'queued'
+ | 'processing'
+ | 'ready'
+ | 'failed'
+ | 'expired'
+
+export interface SessionReplayExportResponse {
+ exportId: string
+ status: SessionReplayExportStatus
+ progress: number
+ filename: string
+ expiresAt: string
+ error?: string
+}
+
export interface SessionDetailsResponse {
details: {
psid: string
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index b25c732e6..39a6b60df 100644
--- a/web/app/hooks/useAnalyticsProxy.ts
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -3,6 +3,7 @@ import { useCallback, useRef, useState } from 'react'
import type {
SessionsResponse,
SessionReplayResponse,
+ SessionReplayExportResponse,
ErrorsResponse,
FeatureFlagStats,
FeatureFlagProfilesResponse,
@@ -138,6 +139,72 @@ export function useSessionReplayProxy() {
return { fetchSessionReplay, data, error, isLoading }
}
+async function parseExportProxyResponse(
+ response: Response,
+): Promise<SessionReplayExportResponse> {
+ let result: ProxyResponse<SessionReplayExportResponse>
+ try {
+ result =
+ (await response.json()) as ProxyResponse<SessionReplayExportResponse>
+ } catch {
+ throw new Error(
+ `Invalid JSON from /api/session-replay-export (status ${response.status})`,
+ )
+ }
+
+ if (!response.ok || !result.data) {
+ throw new Error(
+ result.error || `Request failed (status ${response.status})`,
+ )
+ }
+
+ return result.data
+}
+
+export function useSessionReplayExportProxy() {
+ const startSessionReplayExport = useCallback(
+ async (projectId: string, psid: string, replayId?: string) => {
+ const response = await fetch('/api/session-replay-export', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ projectId, psid, replayId }),
+ })
+
+ return parseExportProxyResponse(response)
+ },
+ [],
+ )
+
+ const getSessionReplayExportStatus = useCallback(
+ async (projectId: string, exportId: string) => {
+ const query = new URLSearchParams({ projectId, exportId })
+ const response = await fetch(`/api/session-replay-export?${query}`)
+
+ return parseExportProxyResponse(response)
+ },
+ [],
+ )
+
+ const getSessionReplayExportDownloadUrl = useCallback(
+ (projectId: string, exportId: string) => {
+ const query = new URLSearchParams({
+ action: 'download',
+ projectId,
+ exportId,
+ })
+
+ return `/api/session-replay-export?${query}`
+ },
+ [],
+ )
+
+ return {
+ startSessionReplayExport,
+ getSessionReplayExportStatus,
+ getSessionReplayExportDownloadUrl,
+ }
+}
+
export function useErrorsProxy() {
const [data, setData] = useState<ErrorsResponse | null>(null)
const [error, setError] = useState<string | null>(null)
diff --git a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
index af3219591..0fb86a5f3 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
@@ -12,6 +12,7 @@ import {
CornersInIcon,
CornersOutIcon,
CursorClickIcon,
+ DownloadSimpleIcon,
GaugeIcon,
GearSixIcon,
ListBulletsIcon,
@@ -41,10 +42,14 @@ import './replayPlayer.css'
import { toast } from 'sonner'
import type {
+ SessionReplayExportResponse,
SessionReplayMetadata,
SessionReplayResponse,
} from '~/api/api.server'
-import { useSessionReplayProxy } from '~/hooks/useAnalyticsProxy'
+import {
+ useSessionReplayExportProxy,
+ useSessionReplayProxy,
+} from '~/hooks/useAnalyticsProxy'
import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
@@ -78,6 +83,7 @@ const PREVIEW_SEEK_STEP_MS = 500
const DEFAULT_REPLAY_VIEWPORT = { width: 1280, height: 720 }
const XHTML_XMLNS = 'http://www.w3.org/1999/xhtml'
const SCREENSHOT_ASSET_WAIT_MS = 1000
+const EXPORT_POLL_INTERVAL_MS = 2000
type ReplayEvent = Omit<eventWithTime, 'data'> & {
data?: Record<string, any>
@@ -178,15 +184,10 @@ const isTransparentColour = (colour?: string) => {
}
const escapeSvgAttribute = (value: string) =>
- value
- .replace(/&/g, '&amp;')
- .replace(/"/g, '&quot;')
- .replace(/</g, '&lt;')
+ value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
const getElementStyle = (element: Element) =>
- 'style' in element
- ? (element as HTMLElement | SVGElement).style
- : undefined
+ 'style' in element ? (element as HTMLElement | SVGElement).style : undefined
const isElementTag = (element: Element, tagName: string) =>
element.tagName.toLowerCase() === tagName
@@ -326,10 +327,7 @@ const copyReplayElementState = (source: Element, target: Element) => {
targetTextArea.value = sourceTextArea.value
targetTextArea.textContent = sourceTextArea.value
- } else if (
- isElementTag(source, 'select') &&
- isElementTag(target, 'select')
- ) {
+ } else if (isElementTag(source, 'select') && isElementTag(target, 'select')) {
const sourceSelect = source as HTMLSelectElement
const targetSelect = target as HTMLSelectElement
@@ -941,7 +939,7 @@ const PageflowMarkerTooltip = ({ marker }: { marker: PageflowMarker }) => {
size='sm'
weight='semibold'
colour='primary'
- className='min-w-0 leading-4 dark'
+ className='dark min-w-0 leading-4'
>
{marker.label}
</Text>
@@ -950,7 +948,7 @@ const PageflowMarkerTooltip = ({ marker }: { marker: PageflowMarker }) => {
as='div'
size='xs'
colour='secondary'
- className='mt-1 max-w-64 leading-4 wrap-anywhere dark'
+ className='dark mt-1 max-w-64 leading-4 wrap-anywhere'
>
{marker.detail}
</Text>
@@ -1023,9 +1021,17 @@ export const SessionReplayModal = ({
} = useTranslation('common')
const { timezone } = useViewProjectContext()
const { fetchSessionReplay, isLoading } = useSessionReplayProxy()
+ const {
+ startSessionReplayExport,
+ getSessionReplayExportStatus,
+ getSessionReplayExportDownloadUrl,
+ } = useSessionReplayExportProxy()
const [payload, setPayload] = useState<SessionReplayResponse | null>(null)
const [error, setError] = useState<string | null>(null)
const [isPreparing, setIsPreparing] = useState(false)
+ const [isExportStarting, setIsExportStarting] = useState(false)
+ const [exportStatus, setExportStatus] =
+ useState<SessionReplayExportResponse | null>(null)
const [duration, setDuration] = useState(0)
const [currentTime, setCurrentTime] = useState(0)
const [isPlaying, setIsPlaying] = useState(false)
@@ -1052,6 +1058,7 @@ export const SessionReplayModal = ({
const replayer = useRef<Replayer | null>(null)
const previewReplayer = useRef<Replayer | null>(null)
const previewSeekRaf = useRef<number | null>(null)
+ const exportPollTimeout = useRef<number | null>(null)
const playStart = useRef({ offset: 0, at: 0, speed: 1 })
const currentTimeRef = useRef(0)
const speedRef = useRef(1)
@@ -1129,6 +1136,14 @@ export const SessionReplayModal = ({
const shouldShowPreview =
Boolean(hoverPreview) && hasEvents && !error && duration > 0
const canControlReplay = hasEvents && !error && duration > 0
+ const isReplayExporting =
+ isExportStarting ||
+ exportStatus?.status === 'queued' ||
+ exportStatus?.status === 'processing'
+ const exportProgress = Math.max(
+ 0,
+ Math.min(100, Math.round(exportStatus?.progress || 0)),
+ )
const shouldShowControls =
!isPlaying ||
isPlayerHovered ||
@@ -1137,6 +1152,14 @@ export const SessionReplayModal = ({
!canControlReplay
const speedLabel =
speed === 1 ? t('project.sessionReplay.normalSpeed') : `${speed}×`
+ const exportToastId = `session-replay-export-${psid}`
+
+ const clearExportPoll = useCallback(() => {
+ if (exportPollTimeout.current) {
+ window.clearTimeout(exportPollTimeout.current)
+ exportPollTimeout.current = null
+ }
+ }, [])
useEffect(() => {
currentTimeRef.current = currentTime
@@ -1355,6 +1378,18 @@ export const SessionReplayModal = ({
if (!isOpen) setSettingsOpen(false)
}, [isOpen])
+ useEffect(() => {
+ if (isOpen) return
+
+ clearExportPoll()
+ setIsExportStarting(false)
+ setExportStatus(null)
+ }, [clearExportPoll, isOpen])
+
+ useEffect(() => {
+ return () => clearExportPoll()
+ }, [clearExportPoll])
+
const flashBezel = useCallback((kind: 'play' | 'pause') => {
setBezel({ kind, key: performance.now() })
}, [])
@@ -1584,9 +1619,144 @@ export const SessionReplayModal = ({
}
}
+ const downloadExport = useCallback(
+ (exportId: string) => {
+ const anchor = document.createElement('a')
+ anchor.href = getSessionReplayExportDownloadUrl(projectId, exportId)
+ anchor.rel = 'noopener'
+ document.body.appendChild(anchor)
+ anchor.click()
+ document.body.removeChild(anchor)
+ },
+ [getSessionReplayExportDownloadUrl, projectId],
+ )
+
+ const handleExportStatus = useCallback(
+ (status: SessionReplayExportResponse) => {
+ setExportStatus(status)
+
+ if (status.status === 'ready') {
+ clearExportPoll()
+ setIsExportStarting(false)
+ downloadExport(status.exportId)
+ toast.success(t('project.sessionReplay.exportDownloaded'), {
+ id: exportToastId,
+ })
+ setExportStatus(null)
+ return true
+ }
+
+ if (status.status === 'failed' || status.status === 'expired') {
+ clearExportPoll()
+ setIsExportStarting(false)
+ toast.error(status.error || t('project.sessionReplay.exportFailed'), {
+ id: exportToastId,
+ })
+ setExportStatus(null)
+ return true
+ }
+
+ toast.loading(
+ t('project.sessionReplay.exportPreparingProgress', {
+ progress: Math.max(0, Math.min(100, Math.round(status.progress))),
+ }),
+ { id: exportToastId },
+ )
+
+ return false
+ },
+ [clearExportPoll, downloadExport, exportToastId, t],
+ )
+
+ const startExportPolling = useCallback(
+ (exportId: string) => {
+ clearExportPoll()
+
+ const poll = async () => {
+ try {
+ const status = await getSessionReplayExportStatus(projectId, exportId)
+ if (handleExportStatus(status)) return
+
+ exportPollTimeout.current = window.setTimeout(
+ poll,
+ EXPORT_POLL_INTERVAL_MS,
+ )
+ } catch {
+ clearExportPoll()
+ setIsExportStarting(false)
+ setExportStatus(null)
+ toast.error(t('project.sessionReplay.exportFailed'), {
+ id: exportToastId,
+ })
+ }
+ }
+
+ exportPollTimeout.current = window.setTimeout(
+ poll,
+ EXPORT_POLL_INTERVAL_MS,
+ )
+ },
+ [
+ clearExportPoll,
+ exportToastId,
+ getSessionReplayExportStatus,
+ handleExportStatus,
+ projectId,
+ t,
+ ],
+ )
+
+ const exportReplay = useCallback(async () => {
+ if (!canControlReplay || isReplayExporting) return
+
+ clearExportPoll()
+ setIsExportStarting(true)
+ setSettingsOpen(false)
+ toast.loading(t('project.sessionReplay.exportPreparing'), {
+ id: exportToastId,
+ })
+
+ try {
+ const status = await startSessionReplayExport(
+ projectId,
+ psid,
+ replay?.replayId,
+ )
+ setIsExportStarting(false)
+
+ if (!handleExportStatus(status)) {
+ startExportPolling(status.exportId)
+ }
+ } catch (reason) {
+ setIsExportStarting(false)
+ setExportStatus(null)
+ toast.error(
+ reason instanceof Error
+ ? reason.message
+ : t('project.sessionReplay.exportFailed'),
+ { id: exportToastId },
+ )
+ }
+ }, [
+ canControlReplay,
+ clearExportPoll,
+ exportToastId,
+ handleExportStatus,
+ isReplayExporting,
+ projectId,
+ psid,
+ replay?.replayId,
+ startExportPolling,
+ startSessionReplayExport,
+ t,
+ ])
+
const close = () => {
replayer.current?.pause()
+ clearExportPoll()
setIsPlaying(false)
+ setIsExportStarting(false)
+ setExportStatus(null)
setHoverPreview(null)
setIsPlayerHovered(false)
setIsControlsFocused(false)
@@ -1674,14 +1844,15 @@ export const SessionReplayModal = ({
className='mx-auto mb-3 size-8 text-amber-400'
weight='duotone'
/>
- <Text
- colour='primary'
- weight='semibold'
- className='dark'
- >
+ <Text colour='primary' weight='semibold' className='dark'>
{t('project.sessionReplay.loadError')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mt-1 dark'>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='dark mt-1'
+ >
{error}
</Text>
</div>
@@ -1689,11 +1860,7 @@ export const SessionReplayModal = ({
) : null}
{!isPreparing && !error && payload && !hasEvents ? (
<div className='absolute inset-0 z-20 flex items-center justify-center px-6 text-center'>
- <Text
- colour='primary'
- weight='semibold'
- className='dark'
- >
+ <Text colour='primary' weight='semibold' className='dark'>
{t('project.sessionReplay.empty')}
</Text>
</div>
@@ -1824,7 +1991,7 @@ export const SessionReplayModal = ({
size='xs'
weight='semibold'
colour='primary'
- className='rounded bg-black/85 px-1.5 py-0.5 dark tabular-nums'
+ className='dark rounded bg-black/85 px-1.5 py-0.5 tabular-nums'
>
{formatReplayTime(hoverPreview.offset)}
</Text>
@@ -1891,7 +2058,7 @@ export const SessionReplayModal = ({
as='span'
size='xs'
colour='primary'
- className='px-1 tabular-nums dark sm:text-sm'
+ className='dark px-1 tabular-nums sm:text-sm'
>
{formatReplayTime(currentTime)} /{' '}
{formatReplayTime(duration)}
@@ -1940,7 +2107,7 @@ export const SessionReplayModal = ({
as='span'
size='sm'
colour='primary'
- className='flex-1 dark'
+ className='dark flex-1'
>
{t('project.sessionReplay.speed')}
</Text>
@@ -1948,7 +2115,7 @@ export const SessionReplayModal = ({
as='span'
size='sm'
colour='secondary'
- className='tabular-nums dark'
+ className='dark tabular-nums'
>
{speedLabel}
</Text>
@@ -1979,7 +2146,7 @@ export const SessionReplayModal = ({
as='span'
size='sm'
colour='primary'
- className='flex-1 dark'
+ className='dark flex-1'
>
{t('project.sessionReplay.timeline.title')}
</Text>
@@ -2011,11 +2178,55 @@ export const SessionReplayModal = ({
as='span'
size='sm'
colour='primary'
- className='flex-1 dark'
+ className='dark flex-1'
>
{t('project.sessionReplay.screenshot')}
</Text>
</Button>
+
+ <Button
+ variant='ghost'
+ focus={false}
+ role='menuitem'
+ tabIndex={
+ canControlReplay && !isReplayExporting
+ ? 0
+ : -1
+ }
+ onClick={exportReplay}
+ disabled={
+ !canControlReplay || isReplayExporting
+ }
+ className={SETTINGS_ROW_CLASS}
+ >
+ <DownloadSimpleIcon
+ weight='duotone'
+ className='size-5 shrink-0 text-gray-50'
+ aria-hidden
+ />
+ <Text
+ as='span'
+ size='sm'
+ colour='primary'
+ className='dark flex-1'
+ >
+ {t('project.sessionReplay.exportMp4')}
+ </Text>
+ {isReplayExporting ? (
+ <Text
+ as='span'
+ size='sm'
+ colour='secondary'
+ className='dark tabular-nums'
+ >
+ {isExportStarting
+ ? t(
+ 'project.sessionReplay.exportStarting',
+ )
+ : `${exportProgress}%`}
+ </Text>
+ ) : null}
+ </Button>
</div>
) : (
<div className='flex flex-col'>
diff --git a/web/app/routes/api.session-replay-export.ts b/web/app/routes/api.session-replay-export.ts
new file mode 100644
index 000000000..4a0161cf2
--- /dev/null
+++ b/web/app/routes/api.session-replay-export.ts
@@ -0,0 +1,122 @@
+import {
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+ data,
+} from 'react-router'
+
+import {
+ serverFetch,
+ streamingServerFetch,
+ type SessionReplayExportResponse,
+} from '~/api/api.server'
+import { getProjectPasswordCookie } from '~/utils/session.server'
+
+interface ProxyResponse<T> {
+ data: T | null
+ error: string | null
+}
+
+const getErrorMessage = (error: string | string[] | null) =>
+ Array.isArray(error) ? error.join(', ') : error
+
+const getCookieHeaders = (cookies: string[]) => {
+ const headers = new Headers()
+ cookies.forEach((cookie) => headers.append('Set-Cookie', cookie))
+ return headers
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const body = (await request.json()) as {
+ projectId?: string
+ psid?: string
+ replayId?: string
+ }
+
+ if (!body.projectId || !body.psid) {
+ return data<ProxyResponse<SessionReplayExportResponse>>(
+ { data: null, error: 'projectId and psid are required' },
+ { status: 400 },
+ )
+ }
+
+ const password = getProjectPasswordCookie(request, body.projectId)
+ const headers: Record<string, string> = {}
+ if (password) headers['x-password'] = password
+
+ const result = await serverFetch<SessionReplayExportResponse>(
+ request,
+ 'log/session-replay/export',
+ {
+ method: 'POST',
+ body: {
+ pid: body.projectId,
+ psid: body.psid,
+ replayId: body.replayId,
+ },
+ headers,
+ timeoutMs: 30000,
+ },
+ )
+
+ return data<ProxyResponse<SessionReplayExportResponse>>(
+ {
+ data: result.data,
+ error: getErrorMessage(result.error),
+ },
+ {
+ status: result.status,
+ headers: getCookieHeaders(result.cookies),
+ },
+ )
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const url = new URL(request.url)
+ const action = url.searchParams.get('action')
+ const projectId = url.searchParams.get('projectId')
+ const exportId = url.searchParams.get('exportId')
+
+ if (!projectId || !exportId) {
+ return data<ProxyResponse<SessionReplayExportResponse>>(
+ { data: null, error: 'projectId and exportId are required' },
+ { status: 400 },
+ )
+ }
+
+ const password = getProjectPasswordCookie(request, projectId)
+ const headers: Record<string, string> = {}
+ if (password) headers['x-password'] = password
+
+ if (action === 'download') {
+ const response = await streamingServerFetch(
+ request,
+ `log/session-replay/export/${encodeURIComponent(exportId)}/download`,
+ { headers },
+ )
+
+ return new Response(response.body, {
+ status: response.status,
+ headers: response.headers,
+ })
+ }
+
+ const result = await serverFetch<SessionReplayExportResponse>(
+ request,
+ `log/session-replay/export/${encodeURIComponent(exportId)}`,
+ {
+ headers,
+ timeoutMs: 30000,
+ },
+ )
+
+ return data<ProxyResponse<SessionReplayExportResponse>>(
+ {
+ data: result.data,
+ error: getErrorMessage(result.error),
+ },
+ {
+ status: result.status,
+ headers: getCookieHeaders(result.cookies),
+ },
+ )
+}
diff --git a/web/package-lock.json b/web/package-lock.json
index fec8b34e1..85a9be1b8 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -47,7 +47,7 @@
"remix-i18next": "^7.5.0",
"remix-sitemap": "^3.2.1",
"remix-utils": "^9.3.1",
- "rrweb": "^2.0.0",
+ "rrweb": "^2.0.1",
"sanitize-html": "^2.17.4",
"simple-icons": "^16.21.0",
"sonner": "^2.0.7",
@@ -4211,16 +4211,14 @@
]
},
"node_modules/@rrweb/types": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.0.tgz",
- "integrity": "sha512-p76i3Bdm/cjb/6NGqmFj0LkGXqC2dXs70AwirgVAsE1ndIa00TJo48La5yobHLsBOk5bfRHy6Yd+9O9VFKhAwQ==",
- "license": "MIT"
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.1.tgz",
+ "integrity": "sha512-x8cNaKFxdvS0/5IfKOj1xG8Htnw1fUwqoPqgP61bOaWqZL6t9UtRPpO9ZlMB2z+FiTxg9zlFFL+Da4ZpFuhoiA=="
},
"node_modules/@rrweb/utils": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.0.tgz",
- "integrity": "sha512-0Q9djyxlwG1fs1TxT7VnKtt33tHku6PENlUAKSXZg8QSSI6aUXdCNZkkBt3JAgbBYVrGhQsYrz+DkCdAXqxs1w==",
- "license": "MIT"
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.1.tgz",
+ "integrity": "sha512-t+b+4rB23/e4EpoGMdPUr6cKtDsFuOb3LxA9IHE8e3A/Xo0nMUfH0bkwqdpUNa/VGDOdiGeG3bhHjuO9zWX54g=="
},
"node_modules/@swc/helpers": {
"version": "0.5.18",
@@ -9331,35 +9329,32 @@
}
},
"node_modules/rrdom": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.0.tgz",
- "integrity": "sha512-Yv+T/IBngNEjhbRv6yJzKdbhgMOiRCV+UA3R0HOpx4yySc8vl4I11Xr5BxCYrnt00l7CGjHbFB9VULEvcg1u6w==",
- "license": "MIT",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.1.tgz",
+ "integrity": "sha512-z8GdQWFmVfa8GpcGkAqfBXseb89z0ciTPSBkID0qr0i6KHCye1MdQ4VoXFf0Ejp3ELe/c7AObu4zsbSbMT+hiw==",
"dependencies": {
- "rrweb-snapshot": "^2.0.0"
+ "rrweb-snapshot": "^2.0.1"
}
},
"node_modules/rrweb": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.0.tgz",
- "integrity": "sha512-ID7NE8OdfAbxZKlTPc/EdL/8sLhTOVB1aZKoQ/M0peKGYB7dIDj0hsdJo+OVXfpiYMTtGzXnKfnMVUj4LnsrhQ==",
- "license": "MIT",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.1.tgz",
+ "integrity": "sha512-MQYzOtI7aZft9ffDMT6rmRSAj6hO4W6T7iA4eB9Mtcuiv3M7DbnnxDMrcPW0sQXepgYN46YhfSKe75d/mlUHrQ==",
"dependencies": {
- "@rrweb/types": "^2.0.0",
- "@rrweb/utils": "^2.0.0",
+ "@rrweb/types": "^2.0.1",
+ "@rrweb/utils": "^2.0.1",
"@types/css-font-loading-module": "0.0.7",
"@xstate/fsm": "^1.4.0",
"base64-arraybuffer": "^1.0.1",
"mitt": "^3.0.0",
- "rrdom": "^2.0.0",
- "rrweb-snapshot": "^2.0.0"
+ "rrdom": "^2.0.1",
+ "rrweb-snapshot": "^2.0.1"
}
},
"node_modules/rrweb-snapshot": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.0.tgz",
- "integrity": "sha512-mDYvvHVXYUD6wZj2AGz5UuupnYnhrWUmF+Hm+haZtVPx8bK3hpAMpu7YjPAoHVluv6KZJNJvVb/6HeBKwXTAvA==",
- "license": "MIT",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.1.tgz",
+ "integrity": "sha512-H8TA29ct2tpYtr5oaB0N+ksRY9bhEErfAYcKbce4+w8lqEUQChpKZd41HpBJLkp04b5QUfWUg4v6r9Okf8r7vA==",
"dependencies": {
"postcss": "^8.4.38"
}
diff --git a/web/package.json b/web/package.json
index 8dcd5194e..ee38eb5ec 100644
--- a/web/package.json
+++ b/web/package.json
@@ -60,7 +60,7 @@
"remix-i18next": "^7.5.0",
"remix-sitemap": "^3.2.1",
"remix-utils": "^9.3.1",
- "rrweb": "^2.0.0",
+ "rrweb": "^2.0.1",
"sanitize-html": "^2.17.4",
"simple-icons": "^16.21.0",
"sonner": "^2.0.7",
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 149d457f2..185befeaa 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1979,6 +1979,12 @@
"screenshot": "Download screenshot",
"screenshotError": "Could not capture this replay frame. Cross-origin media can block screenshots.",
"screenshotDownloaded": "Replay screenshot downloaded",
+ "exportMp4": "Export to MP4",
+ "exportStarting": "Starting",
+ "exportPreparing": "Preparing MP4 export...",
+ "exportPreparingProgress": "Preparing MP4 export... {{progress}}%",
+ "exportDownloaded": "Replay MP4 downloaded",
+ "exportFailed": "Could not export replay to MP4",
"fullscreen": "Fullscreen",
"exitFullscreen": "Exit fullscreen",
"fullscreenError": "Could not enter fullscreen",