Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(sdk): add @cap/sdk-recorder package

Richie McIlroy76ab10d7ff1c
diff --git a/packages/sdk-recorder/package.json b/packages/sdk-recorder/package.json
new file mode 100644
index 000000000..5fb71d773
--- /dev/null
+++ b/packages/sdk-recorder/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "@cap/sdk-recorder",
+ "version": "0.1.0",
+ "description": "Cap Recording SDK for third-party integrations",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts",
+ "./react": "./src/react/index.ts"
+ },
+ "scripts": {
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {},
+ "peerDependencies": {
+ "react": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@types/react": "^19.0.0",
+ "@types/react-dom": "^19.0.0",
+ "typescript": "^5.7.3"
+ }
+}
diff --git a/packages/sdk-recorder/src/core/mime-types.ts b/packages/sdk-recorder/src/core/mime-types.ts
new file mode 100644
index 000000000..30154cd34
--- /dev/null
+++ b/packages/sdk-recorder/src/core/mime-types.ts
@@ -0,0 +1,17 @@
+const PREFERRED_MIME_TYPES = [
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp8,opus",
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ "video/mp4",
+];
+
+export function getSupportedMimeType(): string {
+ for (const mimeType of PREFERRED_MIME_TYPES) {
+ if (MediaRecorder.isTypeSupported(mimeType)) {
+ return mimeType;
+ }
+ }
+ return "";
+}
diff --git a/packages/sdk-recorder/src/core/stream-manager.ts b/packages/sdk-recorder/src/core/stream-manager.ts
new file mode 100644
index 000000000..7c39f6b3a
--- /dev/null
+++ b/packages/sdk-recorder/src/core/stream-manager.ts
@@ -0,0 +1,106 @@
+import type { RecordingMode } from "../types";
+
+export interface StreamConfig {
+ mode: RecordingMode;
+ camera?: { deviceId?: string; enabled?: boolean };
+ microphone?: { deviceId?: string; enabled?: boolean };
+ systemAudio?: boolean;
+}
+
+export interface ManagedStreams {
+ display: MediaStream | null;
+ camera: MediaStream | null;
+ microphone: MediaStream | null;
+}
+
+export async function acquireStreams(
+ config: StreamConfig,
+): Promise<ManagedStreams> {
+ const result: ManagedStreams = {
+ display: null,
+ camera: null,
+ microphone: null,
+ };
+
+ if (config.mode !== "camera") {
+ const displayMediaOptions: DisplayMediaStreamOptions = {
+ video: true,
+ audio: config.systemAudio ?? false,
+ };
+
+ if (config.mode === "window") {
+ (displayMediaOptions as Record<string, unknown>).preferCurrentTab = false;
+ }
+
+ result.display =
+ await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
+ }
+
+ if (config.camera?.enabled !== false) {
+ const constraints: MediaStreamConstraints = {
+ video: config.camera?.deviceId
+ ? { deviceId: { exact: config.camera.deviceId } }
+ : true,
+ audio: false,
+ };
+ try {
+ result.camera = await navigator.mediaDevices.getUserMedia(constraints);
+ } catch {
+ result.camera = null;
+ }
+ }
+
+ if (config.microphone?.enabled !== false) {
+ const constraints: MediaStreamConstraints = {
+ video: false,
+ audio: config.microphone?.deviceId
+ ? { deviceId: { exact: config.microphone.deviceId } }
+ : true,
+ };
+ try {
+ result.microphone =
+ await navigator.mediaDevices.getUserMedia(constraints);
+ } catch {
+ result.microphone = null;
+ }
+ }
+
+ return result;
+}
+
+export function releaseStreams(streams: ManagedStreams) {
+ for (const stream of Object.values(streams)) {
+ if (stream) {
+ for (const track of stream.getTracks()) {
+ track.stop();
+ }
+ }
+ }
+}
+
+export function buildCompositeStream(streams: ManagedStreams): MediaStream {
+ const tracks: MediaStreamTrack[] = [];
+
+ if (streams.display) {
+ for (const track of streams.display.getVideoTracks()) {
+ tracks.push(track);
+ }
+ for (const track of streams.display.getAudioTracks()) {
+ tracks.push(track);
+ }
+ }
+
+ if (streams.camera && !streams.display) {
+ for (const track of streams.camera.getVideoTracks()) {
+ tracks.push(track);
+ }
+ }
+
+ if (streams.microphone) {
+ for (const track of streams.microphone.getAudioTracks()) {
+ tracks.push(track);
+ }
+ }
+
+ return new MediaStream(tracks);
+}
diff --git a/packages/sdk-recorder/src/index.ts b/packages/sdk-recorder/src/index.ts
new file mode 100644
index 000000000..06d224dc7
--- /dev/null
+++ b/packages/sdk-recorder/src/index.ts
@@ -0,0 +1,273 @@
+import { getSupportedMimeType } from "./core/mime-types";
+import {
+ acquireStreams,
+ buildCompositeStream,
+ type ManagedStreams,
+ releaseStreams,
+} from "./core/stream-manager";
+import type {
+ RecorderEventMap,
+ RecorderOptions,
+ RecorderPhase,
+ RecordingResult,
+} from "./types";
+import { MultipartClient } from "./upload/multipart-client";
+
+export type {
+ RecorderOptions,
+ RecorderPhase,
+ RecordingResult,
+ RecorderEventMap,
+};
+
+const DEFAULT_API_BASE = "https://cap.so";
+
+type EventHandler<K extends keyof RecorderEventMap> = (
+ event: RecorderEventMap[K],
+) => void;
+
+export class CapRecorder {
+ private options: Required<
+ Pick<RecorderOptions, "publicKey" | "apiBase" | "mode">
+ > &
+ RecorderOptions;
+ private _phase: RecorderPhase = "idle";
+ private _videoId: string | null = null;
+ private _durationMs = 0;
+ private recorder: MediaRecorder | null = null;
+ private streams: ManagedStreams | null = null;
+ private chunks: Blob[] = [];
+ private durationInterval: ReturnType<typeof setInterval> | null = null;
+ private accumulatedMs = 0;
+ private lastResumeTime = 0;
+ private selectedMimeType = "";
+ private client: MultipartClient;
+ private listeners = new Map<
+ string,
+ Set<EventHandler<keyof RecorderEventMap>>
+ >();
+
+ constructor(options: RecorderOptions) {
+ this.options = {
+ apiBase: DEFAULT_API_BASE,
+ mode: "fullscreen",
+ ...options,
+ };
+ this.client = new MultipartClient(
+ this.options.apiBase,
+ this.options.publicKey,
+ );
+ }
+
+ get phase(): RecorderPhase {
+ return this._phase;
+ }
+
+ get videoId(): string | null {
+ return this._videoId;
+ }
+
+ get durationMs(): number {
+ return this._durationMs;
+ }
+
+ on<K extends keyof RecorderEventMap>(
+ event: K,
+ handler: EventHandler<K>,
+ ): () => void {
+ if (!this.listeners.has(event)) {
+ this.listeners.set(event, new Set());
+ }
+ const set = this.listeners.get(event);
+ if (set) set.add(handler as EventHandler<keyof RecorderEventMap>);
+ return () => {
+ this.listeners.get(event)?.delete(handler);
+ };
+ }
+
+ private emit<K extends keyof RecorderEventMap>(
+ event: K,
+ data: RecorderEventMap[K],
+ ) {
+ const handlers = this.listeners.get(event);
+ if (handlers) {
+ for (const handler of handlers) {
+ try {
+ handler(data);
+ } catch {}
+ }
+ }
+ }
+
+ private setPhase(phase: RecorderPhase) {
+ this._phase = phase;
+ this.emit("phasechange", { phase });
+ }
+
+ async start(): Promise<void> {
+ if (this._phase !== "idle") {
+ throw new Error(`Cannot start from phase "${this._phase}"`);
+ }
+
+ try {
+ this.setPhase("requesting-permission");
+
+ this.streams = await acquireStreams({
+ mode: this.options.mode,
+ camera: this.options.camera,
+ microphone: this.options.microphone,
+ systemAudio: this.options.systemAudio,
+ });
+
+ const composite = buildCompositeStream(this.streams);
+ if (composite.getTracks().length === 0) {
+ throw new Error("No media tracks available");
+ }
+
+ const mimeType = getSupportedMimeType();
+ this.selectedMimeType = mimeType;
+ this.recorder = new MediaRecorder(composite, {
+ mimeType: mimeType || undefined,
+ });
+
+ this.chunks = [];
+ this.recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) {
+ this.chunks.push(e.data);
+ }
+ };
+
+ if (this.streams.display) {
+ const videoTrack = this.streams.display.getVideoTracks()[0];
+ if (videoTrack) {
+ videoTrack.onended = () => {
+ this.stop();
+ };
+ }
+ }
+
+ this.recorder.start(1000);
+ this.accumulatedMs = 0;
+ this.lastResumeTime = Date.now();
+ this.startDurationTimer();
+ this.setPhase("recording");
+ } catch (error) {
+ this.setPhase("error");
+ this.emit("error", {
+ error: error instanceof Error ? error : new Error(String(error)),
+ });
+ this.cleanup();
+ throw error;
+ }
+ }
+
+ pause(): void {
+ if (this._phase !== "recording" || !this.recorder) return;
+ this.accumulatedMs += Date.now() - this.lastResumeTime;
+ this.recorder.pause();
+ this.stopDurationTimer();
+ this.setPhase("paused");
+ }
+
+ resume(): void {
+ if (this._phase !== "paused" || !this.recorder) return;
+ this.recorder.resume();
+ this.lastResumeTime = Date.now();
+ this.startDurationTimer();
+ this.setPhase("recording");
+ }
+
+ async stop(): Promise<RecordingResult> {
+ if (
+ (this._phase !== "recording" && this._phase !== "paused") ||
+ !this.recorder
+ ) {
+ throw new Error(`Cannot stop from phase "${this._phase}"`);
+ }
+
+ this.setPhase("stopping");
+ this.stopDurationTimer();
+
+ const recorder = this.recorder;
+ return new Promise((resolve, reject) => {
+ recorder.onstop = async () => {
+ try {
+ const result = await this.uploadRecording();
+ resolve(result);
+ } catch (err) {
+ reject(err);
+ }
+ };
+ recorder.stop();
+ });
+ }
+
+ destroy(): void {
+ if (this.recorder && this.recorder.state !== "inactive") {
+ this.recorder.stop();
+ }
+ this.cleanup();
+ this.setPhase("idle");
+ }
+
+ private async uploadRecording(): Promise<RecordingResult> {
+ this.setPhase("uploading");
+
+ try {
+ const blob = new Blob(this.chunks, {
+ type: this.selectedMimeType || "video/webm",
+ });
+
+ const { videoId, shareUrl, embedUrl } = await this.client.createVideo({
+ userId: this.options.userId,
+ });
+
+ this._videoId = videoId;
+
+ await this.client.uploadBlob(videoId, blob);
+
+ const result: RecordingResult = {
+ videoId,
+ shareUrl,
+ embedUrl,
+ };
+
+ this.setPhase("complete");
+ this.emit("complete", result);
+ this.cleanup();
+
+ return result;
+ } catch (error) {
+ this.setPhase("error");
+ const err = error instanceof Error ? error : new Error(String(error));
+ this.emit("error", { error: err });
+ this.cleanup();
+ throw err;
+ }
+ }
+
+ private startDurationTimer() {
+ this.durationInterval = setInterval(() => {
+ this._durationMs =
+ this.accumulatedMs + (Date.now() - this.lastResumeTime);
+ this.emit("durationchange", { durationMs: this._durationMs });
+ }, 100);
+ }
+
+ private stopDurationTimer() {
+ if (this.durationInterval) {
+ clearInterval(this.durationInterval);
+ this.durationInterval = null;
+ }
+ }
+
+ private cleanup() {
+ this.stopDurationTimer();
+ if (this.streams) {
+ releaseStreams(this.streams);
+ this.streams = null;
+ }
+ this.recorder = null;
+ this.chunks = [];
+ }
+}
diff --git a/packages/sdk-recorder/src/react/index.ts b/packages/sdk-recorder/src/react/index.ts
new file mode 100644
index 000000000..1bd9dbddb
--- /dev/null
+++ b/packages/sdk-recorder/src/react/index.ts
@@ -0,0 +1 @@
+export { useCapRecorder } from "./useCapRecorder";
diff --git a/packages/sdk-recorder/src/react/useCapRecorder.ts b/packages/sdk-recorder/src/react/useCapRecorder.ts
new file mode 100644
index 000000000..77fcb7771
--- /dev/null
+++ b/packages/sdk-recorder/src/react/useCapRecorder.ts
@@ -0,0 +1,90 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { CapRecorder } from "../index";
+import type { RecorderOptions, RecorderPhase, RecordingResult } from "../types";
+
+export function useCapRecorder(options: RecorderOptions) {
+ const { publicKey, apiBase, mode, userId, camera, microphone, systemAudio } =
+ options;
+ const cameraEnabled = camera?.enabled;
+ const cameraDeviceId = camera?.deviceId;
+ const microphoneEnabled = microphone?.enabled;
+ const microphoneDeviceId = microphone?.deviceId;
+ const recorderRef = useRef<CapRecorder | null>(null);
+ const [phase, setPhase] = useState<RecorderPhase>("idle");
+ const [videoId, setVideoId] = useState<string | null>(null);
+ const [durationMs, setDurationMs] = useState(0);
+
+ useEffect(() => {
+ const recorder = new CapRecorder({
+ publicKey,
+ apiBase,
+ mode,
+ userId,
+ camera:
+ cameraEnabled !== undefined || cameraDeviceId !== undefined
+ ? { enabled: cameraEnabled, deviceId: cameraDeviceId }
+ : undefined,
+ microphone:
+ microphoneEnabled !== undefined || microphoneDeviceId !== undefined
+ ? { enabled: microphoneEnabled, deviceId: microphoneDeviceId }
+ : undefined,
+ systemAudio,
+ });
+ recorderRef.current = recorder;
+
+ const unsubPhase = recorder.on("phasechange", (e) => {
+ setPhase(e.phase);
+ });
+ const unsubDuration = recorder.on("durationchange", (e) => {
+ setDurationMs(e.durationMs);
+ });
+ const unsubComplete = recorder.on("complete", (e) => {
+ setVideoId(e.videoId);
+ });
+
+ return () => {
+ unsubPhase();
+ unsubDuration();
+ unsubComplete();
+ recorder.destroy();
+ };
+ }, [
+ publicKey,
+ apiBase,
+ mode,
+ userId,
+ cameraEnabled,
+ cameraDeviceId,
+ microphoneEnabled,
+ microphoneDeviceId,
+ systemAudio,
+ ]);
+
+ const start = useCallback(async () => {
+ await recorderRef.current?.start();
+ }, []);
+
+ const pause = useCallback(() => {
+ recorderRef.current?.pause();
+ }, []);
+
+ const resume = useCallback(() => {
+ recorderRef.current?.resume();
+ }, []);
+
+ const stop = useCallback(async (): Promise<RecordingResult | undefined> => {
+ return recorderRef.current?.stop();
+ }, []);
+
+ return {
+ phase,
+ videoId,
+ durationMs,
+ isRecording: phase === "recording",
+ isPaused: phase === "paused",
+ start,
+ pause,
+ resume,
+ stop,
+ };
+}
diff --git a/packages/sdk-recorder/src/types.ts b/packages/sdk-recorder/src/types.ts
new file mode 100644
index 000000000..2eb591eab
--- /dev/null
+++ b/packages/sdk-recorder/src/types.ts
@@ -0,0 +1,35 @@
+export type RecordingMode = "fullscreen" | "window" | "tab" | "camera";
+
+export type RecorderPhase =
+ | "idle"
+ | "requesting-permission"
+ | "ready"
+ | "recording"
+ | "paused"
+ | "stopping"
+ | "uploading"
+ | "complete"
+ | "error";
+
+export interface RecorderOptions {
+ publicKey: string;
+ apiBase?: string;
+ userId?: string;
+ mode?: RecordingMode;
+ camera?: { deviceId?: string; enabled?: boolean };
+ microphone?: { deviceId?: string; enabled?: boolean };
+ systemAudio?: boolean;
+}
+
+export interface RecordingResult {
+ videoId: string;
+ shareUrl: string;
+ embedUrl: string;
+}
+
+export type RecorderEventMap = {
+ phasechange: { phase: RecorderPhase };
+ durationchange: { durationMs: number };
+ error: { error: Error };
+ complete: RecordingResult;
+};
diff --git a/packages/sdk-recorder/src/upload/multipart-client.ts b/packages/sdk-recorder/src/upload/multipart-client.ts
new file mode 100644
index 000000000..49fba9684
--- /dev/null
+++ b/packages/sdk-recorder/src/upload/multipart-client.ts
@@ -0,0 +1,105 @@
+const CHUNK_SIZE = 5 * 1024 * 1024;
+
+export class MultipartClient {
+ private apiBase: string;
+ private publicKey: string;
+
+ constructor(apiBase: string, publicKey: string) {
+ this.apiBase = apiBase;
+ this.publicKey = publicKey;
+ }
+
+ private async request(path: string, body: unknown) {
+ const response = await fetch(
+ `${this.apiBase}/api/developer/sdk/v1${path}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${this.publicKey}`,
+ },
+ body: JSON.stringify(body),
+ },
+ );
+ if (!response.ok) {
+ const text = await response.text().catch(() => "Unknown error");
+ throw new Error(`SDK API error (${response.status}): ${text}`);
+ }
+ return response.json();
+ }
+
+ async createVideo(options?: {
+ name?: string;
+ userId?: string;
+ metadata?: Record<string, unknown>;
+ }): Promise<{
+ videoId: string;
+ s3Key: string;
+ shareUrl: string;
+ embedUrl: string;
+ }> {
+ return this.request("/videos/create", options ?? {});
+ }
+
+ async uploadBlob(
+ videoId: string,
+ blob: Blob,
+ onProgress?: (progress: number) => void,
+ ): Promise<void> {
+ const { uploadId } = await this.request("/upload/multipart/initiate", {
+ videoId,
+ contentType: blob.type || "video/mp4",
+ });
+
+ const totalParts = Math.ceil(blob.size / CHUNK_SIZE);
+ const completedParts: Array<{
+ partNumber: number;
+ etag: string;
+ size: number;
+ }> = [];
+
+ for (let i = 0; i < totalParts; i++) {
+ const start = i * CHUNK_SIZE;
+ const end = Math.min(start + CHUNK_SIZE, blob.size);
+ const chunk = blob.slice(start, end);
+ const partNumber = i + 1;
+
+ const { presignedUrl } = await this.request(
+ "/upload/multipart/presign-part",
+ {
+ videoId,
+ uploadId,
+ partNumber,
+ },
+ );
+
+ const uploadResponse = await fetch(presignedUrl, {
+ method: "PUT",
+ body: chunk,
+ });
+
+ if (!uploadResponse.ok) {
+ await this.request("/upload/multipart/abort", {
+ videoId,
+ uploadId,
+ });
+ throw new Error(`Failed to upload part ${partNumber}`);
+ }
+
+ const etag = uploadResponse.headers.get("ETag") ?? "";
+ completedParts.push({
+ partNumber,
+ etag,
+ size: end - start,
+ });
+
+ onProgress?.(completedParts.length / totalParts);
+ }
+
+ await this.request("/upload/multipart/complete", {
+ videoId,
+ uploadId,
+ parts: completedParts,
+ });
+ }
+}
diff --git a/packages/sdk-recorder/tsconfig.json b/packages/sdk-recorder/tsconfig.json
new file mode 100644
index 000000000..ea362db35
--- /dev/null
+++ b/packages/sdk-recorder/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["DOM", "DOM.Iterable", "ES2020"],
+ "jsx": "react-jsx",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "declaration": true,
+ "declarationMap": true,
+ "outDir": "dist",
+ "rootDir": "src"
+ },
+ "include": ["src"]
+}