@unisphere/models-sdk-js 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "@unisphere/models-sdk-js",
3
+ "version": "1.2.0",
4
+ "author": "kaltura",
5
+ "private": false,
6
+ "license": "AGPL-3.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/kaltura/models"
10
+ },
11
+ "types": "./src/index.d.ts",
12
+ "dependencies": {},
13
+ "publishConfig": {
14
+ "registry": "https://registry.npmjs.org"
15
+ },
16
+ "module": "./index.esm.js",
17
+ "type": "module"
18
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Kaltura Avatar SDK - Main Public API
3
+ *
4
+ * This is the main entry point for the Kaltura Avatar SDK. It provides a simple,
5
+ * high-level API for creating avatar sessions, controlling avatar behavior, and
6
+ * managing video streams.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const session = new KalturaAvatarSession('your-api-key');
11
+ *
12
+ * await session.createSession({ avatarId: 'avatar-123' });
13
+ * session.attachAvatar(videoElement);
14
+ * await session.sayText('Hello from Kaltura Avatar!');
15
+ * await session.endSession();
16
+ * ```
17
+ */
18
+ import { AvatarConfig, ConnectionState, CreateSessionOptions, SessionState, SessionEvent } from './types';
19
+ /**
20
+ * Kaltura Avatar Session - Main SDK class
21
+ */
22
+ export declare class KalturaAvatarSession {
23
+ private readonly controlSDK;
24
+ private readonly rtcSDK;
25
+ private readonly logger;
26
+ private state;
27
+ private sessionId;
28
+ private eventHandlers;
29
+ /**
30
+ * Create a new Kaltura Avatar Session
31
+ *
32
+ * @param apiKey - API key for authentication
33
+ * @param config - Optional configuration
34
+ */
35
+ constructor(apiKey: string, config?: AvatarConfig);
36
+ /**
37
+ * Create a new avatar session
38
+ *
39
+ * This method:
40
+ * 1. Creates a session with the backend
41
+ * 2. Initializes the client
42
+ * 3. Establishes WebRTC connection
43
+ *
44
+ * @param options - Session creation options
45
+ */
46
+ createSession(options: CreateSessionOptions): Promise<void>;
47
+ /**
48
+ * Attach avatar video to a video element
49
+ *
50
+ * @param videoElement - HTML video element to display avatar
51
+ */
52
+ attachAvatar(videoElement: HTMLVideoElement): void;
53
+ /**
54
+ * Send audio file for the avatar to speak
55
+ *
56
+ * @param mp3File - MP3 file or Blob to speak
57
+ */
58
+ say(mp3File: File | Blob): Promise<void>;
59
+ /**
60
+ * Send text for the avatar to speak
61
+ *
62
+ * The text will be automatically chunked into 3-word segments for optimal processing.
63
+ *
64
+ * @param text - Text for the avatar to speak
65
+ */
66
+ sayText(text: string): Promise<void>;
67
+ /**
68
+ * Interrupt the avatar's current speech
69
+ */
70
+ interrupt(): Promise<void>;
71
+ /**
72
+ * End the avatar session and cleanup resources
73
+ */
74
+ endSession(): Promise<void>;
75
+ /**
76
+ * Get current session state
77
+ */
78
+ getSessionState(): SessionState;
79
+ /**
80
+ * Get current connection state
81
+ */
82
+ getConnectionState(): ConnectionState;
83
+ /**
84
+ * Get current session ID
85
+ */
86
+ getSessionId(): string | null;
87
+ /**
88
+ * Register event handler
89
+ *
90
+ * @param event - Event name
91
+ * @param callback - Callback function
92
+ */
93
+ on(event: SessionEvent, callback: (data?: any) => void): void;
94
+ /**
95
+ * Unregister event handler
96
+ *
97
+ * @param event - Event name
98
+ * @param callback - Callback function
99
+ */
100
+ off(event: SessionEvent, callback: (data?: unknown) => void): void;
101
+ /**
102
+ * Setup event handlers for RTC SDK
103
+ */
104
+ private setupRTCEventHandlers;
105
+ /**
106
+ * Ensure session is in READY state
107
+ * @throws AvatarError if not ready
108
+ */
109
+ private ensureReady;
110
+ /**
111
+ * Set internal session state
112
+ *
113
+ * @param state - New session state
114
+ */
115
+ private setState;
116
+ /**
117
+ * Emit event to registered handlers
118
+ *
119
+ * @param event - Event name
120
+ * @param data - Event data
121
+ */
122
+ private emit;
123
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Avatar Control SDK - HTTP API Client
3
+ *
4
+ * Handles all HTTP communication with the avatar backend including:
5
+ * - Session lifecycle (create, init, end)
6
+ * - Avatar control (say, sayText, interrupt)
7
+ * - JWT token management
8
+ * - Request retry logic
9
+ */
10
+ import { RetryConfig } from '../types';
11
+ import { VisualVoiceConfig, CreateSessionResponse, InitClientResponse } from './types';
12
+ /**
13
+ * Configuration for the Avatar Control SDK
14
+ */
15
+ export interface ControlSDKConfig {
16
+ /** Base URL for the avatar backend API */
17
+ baseUrl: string;
18
+ /** API key for authentication */
19
+ apiKey: string;
20
+ /** Retry configuration */
21
+ retryConfig?: RetryConfig;
22
+ /** Log level */
23
+ logLevel?: string;
24
+ /** Request timeout in milliseconds */
25
+ timeoutMs?: number;
26
+ }
27
+ /**
28
+ * Avatar Control SDK - Manages HTTP communication with avatar backend
29
+ */
30
+ export declare class AvatarControlSDK {
31
+ private readonly baseUrl;
32
+ private readonly apiKey;
33
+ private readonly retryConfig;
34
+ private readonly logger;
35
+ private readonly timeoutMs;
36
+ private sessionToken;
37
+ constructor(config: ControlSDKConfig);
38
+ /**
39
+ * Create a new avatar session
40
+ *
41
+ * @param config - Visual and voice configuration
42
+ * @returns Session ID and JWT token
43
+ */
44
+ createSession(config: VisualVoiceConfig): Promise<CreateSessionResponse>;
45
+ /**
46
+ * Initialize client and get WHEP URL for WebRTC connection
47
+ *
48
+ * @param sessionId - Session identifier
49
+ * @returns WHEP URL for WebRTC connection
50
+ */
51
+ initClient(sessionId: string): Promise<InitClientResponse>;
52
+ /**
53
+ * Send text for the avatar to speak
54
+ *
55
+ * @param sessionId - Session identifier
56
+ * @param text - Text chunk to speak
57
+ * @param turnId - Turn ID for grouping related chunks
58
+ * @param isFinal - Whether this is the final chunk in the turn
59
+ */
60
+ sayText(sessionId: string, text: string, turnId: string, isFinal: boolean): Promise<void>;
61
+ /**
62
+ * Send audio file for the avatar to speak
63
+ *
64
+ * @param sessionId - Session identifier
65
+ * @param audioFile - MP3 file to speak
66
+ */
67
+ say(sessionId: string, audioFile: File | Blob): Promise<void>;
68
+ /**
69
+ * Interrupt the avatar's current speech
70
+ *
71
+ * @param sessionId - Session identifier
72
+ */
73
+ interrupt(sessionId: string): Promise<void>;
74
+ /**
75
+ * End the avatar session
76
+ *
77
+ * @param sessionId - Session identifier
78
+ */
79
+ endSession(sessionId: string): Promise<void>;
80
+ /**
81
+ * Make an HTTP request with retry logic and timeout
82
+ *
83
+ * @param endpoint - API endpoint (relative to baseUrl)
84
+ * @param options - Fetch options
85
+ * @returns Response data
86
+ */
87
+ private makeRequest;
88
+ /**
89
+ * Ensure JWT token is available
90
+ * @throws AvatarError if not authenticated
91
+ */
92
+ private ensureAuthenticated;
93
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Avatar Control SDK exports
3
+ */
4
+ export * from './AvatarControlSDK';
5
+ export * from './types';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Types for the Avatar Control SDK (HTTP API)
3
+ */
4
+ /**
5
+ * Configuration for visual and voice settings
6
+ */
7
+ export interface VisualVoiceConfig {
8
+ /** Avatar visual ID */
9
+ avatarId: string;
10
+ /** Optional voice ID for the avatar */
11
+ voiceId?: string;
12
+ }
13
+ /**
14
+ * Response from session creation endpoint
15
+ */
16
+ export interface CreateSessionResponse {
17
+ /** Whether the session was created successfully */
18
+ success: boolean;
19
+ /** Unique session identifier */
20
+ sessionId: string;
21
+ /** JWT token for authenticating subsequent requests */
22
+ token: string;
23
+ /** Optional error message if creation failed */
24
+ error?: string;
25
+ }
26
+ /**
27
+ * Response from client initialization endpoint
28
+ */
29
+ export interface InitClientResponse {
30
+ /** Whether initialization was successful */
31
+ success: boolean;
32
+ /** WHEP URL for WebRTC connection */
33
+ whepUrl: string;
34
+ /** Optional error message if initialization failed */
35
+ error?: string;
36
+ }
37
+ /**
38
+ * Internal request body for say-text endpoint
39
+ */
40
+ export interface SayTextRequest {
41
+ /** Text chunk to speak */
42
+ text: string;
43
+ /** Turn ID for grouping related chunks */
44
+ turnId: string;
45
+ /** Whether this is the final chunk in the turn */
46
+ isFinal: boolean;
47
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Kaltura Avatar SDK
3
+ *
4
+ * A TypeScript SDK for integrating with Kaltura's speech-to-video avatar service.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { KalturaAvatarSession } from '@kaltura-corp/unisphere-rtc-avatar';
9
+ *
10
+ * const session = new KalturaAvatarSession('your-api-key');
11
+ *
12
+ * // Create session
13
+ * await session.createSession({ avatarId: 'avatar-123' });
14
+ *
15
+ * // Attach to video element
16
+ * const videoElement = document.getElementById('avatar-video') as HTMLVideoElement;
17
+ * session.attachAvatar(videoElement);
18
+ *
19
+ * // Send text for avatar to speak
20
+ * await session.sayText('Hello from Kaltura Avatar!');
21
+ *
22
+ * // Interrupt speech
23
+ * await session.interrupt();
24
+ *
25
+ * // End session
26
+ * await session.endSession();
27
+ * ```
28
+ *
29
+ * @packageDocumentation
30
+ */
31
+ export { KalturaAvatarSession } from './KalturaAvatarSession';
32
+ export type { AvatarConfig, CreateSessionOptions, SessionEvent, RetryConfig, } from './types';
33
+ export { SessionState, ConnectionState, AvatarError, AvatarErrorCode, DEFAULT_RETRY_CONFIG, } from './types';
34
+ export { AvatarControlSDK } from './control-sdk';
35
+ export type { ControlSDKConfig, VisualVoiceConfig, CreateSessionResponse, InitClientResponse, } from './control-sdk';
36
+ export { AvatarRTCSDK, PeerConnectionManager, SignalingManager, DEFAULT_ICE_SERVERS, } from './rtc-sdk';
37
+ export type { RTCConfig, PeerConnectionConfig, SignalingConfig, } from './rtc-sdk';
38
+ export { chunkText, generateTurnId, } from './utils/text-chunker';
39
+ export { retryWithBackoff, waitForCondition, } from './utils/retry';
40
+ export { createLogger, parseLogLevel, } from './utils/logger';
41
+ export type { Logger, LogLevel, } from './utils/logger';
42
+ export { createAvatarError, isNetworkError, isRetryableStatusCode, shouldRetry, } from './utils/errors';
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Avatar RTC SDK - High-level WebRTC management
3
+ *
4
+ * This SDK orchestrates the PeerConnectionManager and SignalingManager to provide
5
+ * a simple interface for WebRTC connections. It handles:
6
+ * - Connection lifecycle
7
+ * - Video stream attachment
8
+ * - Event emission
9
+ * - Error handling
10
+ */
11
+ import { ConnectionState } from '../types';
12
+ import { RTCConfig } from './types';
13
+ /**
14
+ * RTC events that can be subscribed to
15
+ */
16
+ export type RTCEvent = 'connected' | 'disconnected' | 'failed' | 'track';
17
+ /**
18
+ * Avatar RTC SDK - Orchestrates WebRTC connection
19
+ */
20
+ export declare class AvatarRTCSDK {
21
+ private pcManager;
22
+ private signalingManager;
23
+ private videoElement;
24
+ private state;
25
+ private readonly logger;
26
+ private readonly iceServers;
27
+ private readonly iceTransportPolicy;
28
+ private readonly retryConfig;
29
+ private whepUrl;
30
+ private reconnectAttempts;
31
+ private isReconnecting;
32
+ private eventHandlers;
33
+ constructor(config?: RTCConfig);
34
+ /**
35
+ * Connect to WebRTC endpoint using WHEP URL with retry logic
36
+ *
37
+ * @param whepUrl - WHEP URL for WebRTC signaling
38
+ */
39
+ connect(whepUrl: string): Promise<void>;
40
+ /**
41
+ * Internal connection logic (without retry)
42
+ */
43
+ private connectInternal;
44
+ /**
45
+ * Reconnect after connection failure
46
+ */
47
+ private reconnect;
48
+ /**
49
+ * Cleanup connection resources without changing state
50
+ */
51
+ private cleanup;
52
+ /**
53
+ * Attach video element to receive avatar video
54
+ *
55
+ * @param videoElement - HTML video element to attach streams to
56
+ */
57
+ attachVideo(videoElement: HTMLVideoElement): void;
58
+ /**
59
+ * Disconnect and cleanup resources
60
+ */
61
+ disconnect(): void;
62
+ /**
63
+ * Get current connection state
64
+ */
65
+ getConnectionState(): ConnectionState;
66
+ /**
67
+ * Register event handler
68
+ *
69
+ * @param event - Event name
70
+ * @param callback - Callback function
71
+ */
72
+ on(event: RTCEvent, callback: (data?: unknown) => void): void;
73
+ /**
74
+ * Unregister event handler
75
+ *
76
+ * @param event - Event name
77
+ * @param callback - Callback function
78
+ */
79
+ off(event: RTCEvent, callback: (data?: unknown) => void): void;
80
+ /**
81
+ * Setup event handlers for peer connection
82
+ */
83
+ private setupPeerConnectionEventHandlers;
84
+ /**
85
+ * Attach media stream to video element
86
+ *
87
+ * @param stream - Media stream to attach
88
+ */
89
+ private attachStreamToVideo;
90
+ /**
91
+ * Wait for connection to be established
92
+ *
93
+ * @param timeoutMs - Timeout in milliseconds
94
+ */
95
+ private waitForConnection;
96
+ /**
97
+ * Set internal connection state
98
+ *
99
+ * @param state - New connection state
100
+ */
101
+ private setState;
102
+ /**
103
+ * Emit event to registered handlers
104
+ *
105
+ * @param event - Event name
106
+ * @param data - Event data
107
+ */
108
+ private emit;
109
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * PeerConnectionManager - Manages RTCPeerConnection lifecycle
3
+ *
4
+ * This class wraps RTCPeerConnection and provides a clean API for:
5
+ * - Creating and configuring peer connections
6
+ * - Managing transceivers (sendonly, recvonly, sendrecv)
7
+ * - Creating offers and answers
8
+ * - Setting local and remote descriptions
9
+ * - Monitoring connection state
10
+ * - Handling tracks
11
+ */
12
+ import { PeerConnectionConfig } from './types';
13
+ /**
14
+ * PeerConnectionManager - Low-level RTCPeerConnection wrapper
15
+ */
16
+ export declare class PeerConnectionManager {
17
+ private pc;
18
+ private readonly iceServers;
19
+ private readonly iceTransportPolicy;
20
+ private readonly logger;
21
+ private trackHandlers;
22
+ private connectionStateChangeHandlers;
23
+ private iceGatheringStateChangeHandlers;
24
+ constructor(config: PeerConnectionConfig);
25
+ /**
26
+ * Create the RTCPeerConnection
27
+ */
28
+ createPeerConnection(): void;
29
+ /**
30
+ * Add transceivers for audio and video
31
+ *
32
+ * @param direction - Direction of the transceivers (sendonly, recvonly, sendrecv)
33
+ */
34
+ addTransceivers(direction: RTCRtpTransceiverDirection): void;
35
+ /**
36
+ * Create an SDP offer
37
+ *
38
+ * @returns SDP offer
39
+ */
40
+ createOffer(): Promise<RTCSessionDescriptionInit>;
41
+ /**
42
+ * Create an SDP answer
43
+ *
44
+ * @returns SDP answer
45
+ */
46
+ createAnswer(): Promise<RTCSessionDescriptionInit>;
47
+ /**
48
+ * Set local description
49
+ *
50
+ * @param desc - SDP description
51
+ */
52
+ setLocalDescription(desc: RTCSessionDescriptionInit): Promise<void>;
53
+ /**
54
+ * Set remote description
55
+ *
56
+ * @param desc - SDP description
57
+ */
58
+ setRemoteDescription(desc: RTCSessionDescriptionInit): Promise<void>;
59
+ /**
60
+ * Get the peer connection (read-only)
61
+ */
62
+ getPeerConnection(): RTCPeerConnection | null;
63
+ /**
64
+ * Get current connection state
65
+ */
66
+ getConnectionState(): RTCPeerConnectionState;
67
+ /**
68
+ * Get current ICE gathering state
69
+ */
70
+ getIceGatheringState(): RTCIceGatheringState;
71
+ /**
72
+ * Get current signaling state
73
+ */
74
+ getSignalingState(): RTCSignalingState;
75
+ /**
76
+ * Register handler for track events
77
+ *
78
+ * @param callback - Callback to invoke when track is received
79
+ */
80
+ onTrack(callback: (event: RTCTrackEvent) => void): void;
81
+ /**
82
+ * Register handler for connection state changes
83
+ *
84
+ * @param callback - Callback to invoke when connection state changes
85
+ */
86
+ onConnectionStateChange(callback: (state: RTCPeerConnectionState) => void): void;
87
+ /**
88
+ * Register handler for ICE gathering state changes
89
+ *
90
+ * @param callback - Callback to invoke when ICE gathering state changes
91
+ */
92
+ onIceGatheringStateChange(callback: (state: RTCIceGatheringState) => void): void;
93
+ /**
94
+ * Close the peer connection and clean up resources
95
+ */
96
+ close(): void;
97
+ /**
98
+ * Setup event handlers for the peer connection
99
+ */
100
+ private setupEventHandlers;
101
+ /**
102
+ * Ensure peer connection exists
103
+ * @throws AvatarError if peer connection doesn't exist
104
+ */
105
+ private ensurePeerConnection;
106
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * SignalingManager - Handles SDP offer/answer exchange using WHEP protocol
3
+ *
4
+ * WHEP (WebRTC-HTTP Egress Protocol) is an HTTP-based signaling protocol
5
+ * for WebRTC streaming. This manager handles:
6
+ * - SDP offer creation
7
+ * - ICE gathering
8
+ * - HTTP-based SDP exchange
9
+ * - SDP answer processing
10
+ */
11
+ import { SignalingConfig } from './types';
12
+ import { PeerConnectionManager } from './PeerConnectionManager';
13
+ /**
14
+ * SignalingManager - Handles WHEP protocol signaling
15
+ */
16
+ export declare class SignalingManager {
17
+ private readonly whepUrl;
18
+ private readonly timeout;
19
+ private readonly retryConfig;
20
+ private readonly logger;
21
+ constructor(config: SignalingConfig);
22
+ /**
23
+ * Negotiate WebRTC connection using WHEP protocol
24
+ *
25
+ * This method orchestrates the full WHEP handshake:
26
+ * 1. Add receive-only transceivers
27
+ * 2. Create SDP offer
28
+ * 3. Wait for ICE gathering
29
+ * 4. Send offer to WHEP endpoint
30
+ * 5. Receive SDP answer
31
+ * 6. Set remote description
32
+ *
33
+ * @param pcManager - PeerConnectionManager instance
34
+ */
35
+ negotiate(pcManager: PeerConnectionManager): Promise<void>;
36
+ /**
37
+ * Wait for ICE gathering to complete
38
+ *
39
+ * @param pcManager - PeerConnectionManager instance
40
+ * @param timeoutMs - Timeout in milliseconds (default: 5000)
41
+ */
42
+ private waitForIceGathering;
43
+ /**
44
+ * Send SDP offer to WHEP endpoint and receive answer with retry logic
45
+ *
46
+ * @param offerSdp - SDP offer string
47
+ * @returns SDP answer string
48
+ */
49
+ private sendOfferToServer;
50
+ /**
51
+ * Internal method to send SDP offer (without retry)
52
+ *
53
+ * @param offerSdp - SDP offer string
54
+ * @returns SDP answer string
55
+ */
56
+ private sendOfferToServerInternal;
57
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Avatar RTC SDK exports
3
+ */
4
+ export * from './AvatarRTCSDK';
5
+ export * from './PeerConnectionManager';
6
+ export * from './SignalingManager';
7
+ export * from './types';
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Types for the Avatar RTC SDK (WebRTC)
3
+ */
4
+ import { Logger } from '../utils/logger';
5
+ import { RetryConfig } from '../types';
6
+ /**
7
+ * Configuration for the RTC SDK
8
+ */
9
+ export interface RTCConfig {
10
+ /** ICE servers for WebRTC connection */
11
+ iceServers?: RTCIceServer[];
12
+ /** ICE transport policy */
13
+ iceTransportPolicy?: 'all' | 'relay';
14
+ /** Retry configuration for connection and reconnection */
15
+ retryConfig?: RetryConfig;
16
+ /** Logger instance */
17
+ logger?: Logger;
18
+ /** Log level */
19
+ logLevel?: string;
20
+ }
21
+ /**
22
+ * Configuration for PeerConnectionManager
23
+ */
24
+ export interface PeerConnectionConfig {
25
+ /** ICE servers for WebRTC connection */
26
+ iceServers: RTCIceServer[];
27
+ /** ICE transport policy */
28
+ iceTransportPolicy?: 'all' | 'relay';
29
+ /** Logger instance */
30
+ logger?: Logger;
31
+ }
32
+ /**
33
+ * Configuration for SignalingManager
34
+ */
35
+ export interface SignalingConfig {
36
+ /** WHEP URL for signaling */
37
+ whepUrl: string;
38
+ /** Request timeout in milliseconds */
39
+ timeout?: number;
40
+ /** Retry configuration for WHEP requests */
41
+ retryConfig?: RetryConfig;
42
+ /** Logger instance */
43
+ logger?: Logger;
44
+ }
45
+ /**
46
+ * Default ICE servers (Google STUN)
47
+ */
48
+ export declare const DEFAULT_ICE_SERVERS: RTCIceServer[];