@telnyx/react-voice-commons-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/TelnyxVoiceCommons.podspec +32 -0
  2. package/ios/CallKitBridge.m +44 -0
  3. package/ios/CallKitBridge.swift +879 -0
  4. package/ios/README.md +211 -0
  5. package/ios/VoicePnBridge.m +31 -0
  6. package/ios/VoicePnBridge.swift +87 -0
  7. package/lib/callkit/callkit-coordinator.d.ts +126 -0
  8. package/lib/callkit/callkit-coordinator.js +728 -0
  9. package/lib/callkit/callkit.d.ts +49 -0
  10. package/lib/callkit/callkit.js +262 -0
  11. package/lib/callkit/index.d.ts +4 -0
  12. package/lib/callkit/index.js +15 -0
  13. package/lib/callkit/use-callkit-coordinator.d.ts +21 -0
  14. package/lib/callkit/use-callkit-coordinator.js +53 -0
  15. package/lib/callkit/use-callkit.d.ts +28 -0
  16. package/lib/callkit/use-callkit.js +279 -0
  17. package/lib/context/TelnyxVoiceContext.d.ts +18 -0
  18. package/lib/context/TelnyxVoiceContext.js +18 -0
  19. package/lib/hooks/use-callkit-coordinator.d.ts +13 -0
  20. package/lib/hooks/use-callkit-coordinator.js +48 -0
  21. package/lib/hooks/useAppReadyNotifier.d.ts +9 -0
  22. package/lib/hooks/useAppReadyNotifier.js +25 -0
  23. package/lib/hooks/useAppStateHandler.d.ts +16 -0
  24. package/lib/hooks/useAppStateHandler.js +105 -0
  25. package/lib/index.d.ts +24 -0
  26. package/lib/index.js +66 -0
  27. package/lib/internal/CallKitHandler.d.ts +17 -0
  28. package/lib/internal/CallKitHandler.js +110 -0
  29. package/lib/internal/callkit-manager.d.ts +69 -0
  30. package/lib/internal/callkit-manager.js +326 -0
  31. package/lib/internal/calls/call-state-controller.d.ts +92 -0
  32. package/lib/internal/calls/call-state-controller.js +294 -0
  33. package/lib/internal/session/session-manager.d.ts +87 -0
  34. package/lib/internal/session/session-manager.js +385 -0
  35. package/lib/internal/user-defaults-helpers.d.ts +10 -0
  36. package/lib/internal/user-defaults-helpers.js +69 -0
  37. package/lib/internal/voice-pn-bridge.d.ts +14 -0
  38. package/lib/internal/voice-pn-bridge.js +5 -0
  39. package/lib/models/call-state.d.ts +61 -0
  40. package/lib/models/call-state.js +87 -0
  41. package/lib/models/call.d.ts +145 -0
  42. package/lib/models/call.js +372 -0
  43. package/lib/models/config.d.ts +64 -0
  44. package/lib/models/config.js +92 -0
  45. package/lib/models/connection-state.d.ts +34 -0
  46. package/lib/models/connection-state.js +50 -0
  47. package/lib/telnyx-voice-app.d.ts +48 -0
  48. package/lib/telnyx-voice-app.js +486 -0
  49. package/lib/telnyx-voip-client.d.ts +184 -0
  50. package/lib/telnyx-voip-client.js +386 -0
  51. package/package.json +104 -0
  52. package/src/callkit/callkit-coordinator.ts +846 -0
  53. package/src/callkit/callkit.ts +322 -0
  54. package/src/callkit/index.ts +4 -0
  55. package/src/callkit/use-callkit.ts +345 -0
  56. package/src/context/TelnyxVoiceContext.tsx +33 -0
  57. package/src/hooks/use-callkit-coordinator.ts +60 -0
  58. package/src/hooks/useAppReadyNotifier.ts +25 -0
  59. package/src/hooks/useAppStateHandler.ts +134 -0
  60. package/src/index.ts +56 -0
  61. package/src/internal/CallKitHandler.tsx +149 -0
  62. package/src/internal/callkit-manager.ts +335 -0
  63. package/src/internal/calls/call-state-controller.ts +384 -0
  64. package/src/internal/session/session-manager.ts +467 -0
  65. package/src/internal/user-defaults-helpers.ts +58 -0
  66. package/src/internal/voice-pn-bridge.ts +18 -0
  67. package/src/models/call-state.ts +98 -0
  68. package/src/models/call.ts +388 -0
  69. package/src/models/config.ts +125 -0
  70. package/src/models/connection-state.ts +50 -0
  71. package/src/telnyx-voice-app.tsx +690 -0
  72. package/src/telnyx-voip-client.ts +475 -0
  73. package/src/types/telnyx-sdk.d.ts +79 -0
@@ -0,0 +1,475 @@
1
+ import { Observable } from 'rxjs';
2
+ import { TelnyxConnectionState } from './models/connection-state';
3
+ import { Call } from './models/call';
4
+ import { Config, CredentialConfig, TokenConfig, validateConfig } from './models/config';
5
+ import { SessionManager } from './internal/session/session-manager';
6
+ import { CallStateController } from './internal/calls/call-state-controller';
7
+
8
+ /**
9
+ * Configuration options for TelnyxVoipClient
10
+ */
11
+ export interface TelnyxVoipClientOptions {
12
+ /** Enable automatic app state management (background/foreground behavior) - default: true */
13
+ enableAppStateManagement?: boolean;
14
+
15
+ /** Enable debug logging */
16
+ debug?: boolean;
17
+ }
18
+
19
+ /**
20
+ * The main public interface for the react-voice-commons module.
21
+ *
22
+ * This class serves as the Façade for the entire module, providing a simplified
23
+ * API that completely hides the underlying complexity. It is the sole entry point
24
+ * for developers using the react-voice-commons package.
25
+ *
26
+ * The TelnyxVoipClient is designed to be state-management agnostic, exposing
27
+ * all observable state via RxJS streams. This allows developers to integrate it
28
+ * into their chosen state management solution naturally.
29
+ */
30
+ export class TelnyxVoipClient {
31
+ private readonly _sessionManager: SessionManager;
32
+ private readonly _callStateController: CallStateController;
33
+ private readonly _options: Required<TelnyxVoipClientOptions>;
34
+ private _disposed = false;
35
+
36
+ /**
37
+ * Creates a new TelnyxVoipClient instance.
38
+ *
39
+ * @param options Configuration options for the client
40
+ */
41
+ constructor(options: TelnyxVoipClientOptions = {}) {
42
+ this._options = {
43
+ enableAppStateManagement: true,
44
+ debug: false,
45
+ ...options,
46
+ };
47
+
48
+ // Initialize core components
49
+ this._sessionManager = new SessionManager();
50
+ this._callStateController = new CallStateController(this._sessionManager);
51
+
52
+ // Set up callback to initialize call state controller listeners when client is ready
53
+ this._sessionManager.setOnClientReady(() => {
54
+ console.log(
55
+ '🔧 TelnyxVoipClient: Client ready, initializing call state controller listeners'
56
+ );
57
+ this._callStateController.initializeClientListeners();
58
+ });
59
+
60
+ if (this._options.debug) {
61
+ console.log('TelnyxVoipClient initialized with options:', this._options);
62
+ }
63
+ }
64
+
65
+ // ========== Observable Streams ==========
66
+
67
+ /**
68
+ * Stream of connection state changes.
69
+ *
70
+ * Emits the current status of the connection to the Telnyx backend.
71
+ * Values include connecting, connected, disconnected, and error states.
72
+ * Listen to this to show connection indicators in your UI.
73
+ */
74
+ get connectionState$(): Observable<TelnyxConnectionState> {
75
+ return this._sessionManager.connectionState$;
76
+ }
77
+
78
+ /**
79
+ * Stream of all current calls.
80
+ *
81
+ * Emits a list of all current Call objects. Use this for applications
82
+ * that need to support multiple simultaneous calls (e.g., call waiting,
83
+ * conference calls).
84
+ */
85
+ get calls$(): Observable<Call[]> {
86
+ return this._callStateController.calls$;
87
+ }
88
+
89
+ /**
90
+ * Stream of the currently active call.
91
+ *
92
+ * A convenience stream that emits the currently active Call object.
93
+ * It emits null when no call is in progress. Ideal for applications
94
+ * that only handle a single call at a time.
95
+ */
96
+ get activeCall$(): Observable<Call | null> {
97
+ return this._callStateController.activeCall$;
98
+ }
99
+
100
+ // ========== Synchronous State Access ==========
101
+
102
+ /**
103
+ * Current connection state (synchronous access).
104
+ */
105
+ get currentConnectionState(): TelnyxConnectionState {
106
+ return this._sessionManager.currentState;
107
+ }
108
+
109
+ /**
110
+ * Current list of calls (synchronous access).
111
+ */
112
+ get currentCalls(): Call[] {
113
+ return this._callStateController.currentCalls;
114
+ }
115
+
116
+ /**
117
+ * Current active call (synchronous access).
118
+ */
119
+ get currentActiveCall(): Call | null {
120
+ return this._callStateController.currentActiveCall;
121
+ }
122
+
123
+ /**
124
+ * Current session ID (UUID) for this connection.
125
+ */
126
+ get sessionId(): string {
127
+ return this._sessionManager.sessionId;
128
+ }
129
+
130
+ /**
131
+ * Configuration options for this client instance.
132
+ */
133
+ get options(): Required<TelnyxVoipClientOptions> {
134
+ return this._options;
135
+ }
136
+
137
+ // ========== Authentication Methods ==========
138
+
139
+ /**
140
+ * Connects to the Telnyx platform using credential authentication.
141
+ *
142
+ * @param config The credential configuration containing SIP username and password
143
+ * @returns A Promise that completes when the connection attempt is initiated
144
+ *
145
+ * Listen to connectionState$ to monitor the actual connection status.
146
+ */
147
+ async login(config: CredentialConfig): Promise<void> {
148
+ this._throwIfDisposed();
149
+
150
+ const errors = validateConfig(config);
151
+ if (errors.length > 0) {
152
+ throw new Error(`Invalid configuration: ${errors.join(', ')}`);
153
+ }
154
+
155
+ if (this._options.debug) {
156
+ console.log('TelnyxVoipClient: Logging in with credentials for user:', config.sipUser);
157
+ }
158
+
159
+ await this._sessionManager.connectWithCredential(config);
160
+ }
161
+
162
+ /**
163
+ * Connects to the Telnyx platform using token authentication.
164
+ *
165
+ * @param config The token configuration containing the authentication token
166
+ * @returns A Promise that completes when the connection attempt is initiated
167
+ *
168
+ * Listen to connectionState$ to monitor the actual connection status.
169
+ */
170
+ async loginWithToken(config: TokenConfig): Promise<void> {
171
+ this._throwIfDisposed();
172
+
173
+ const errors = validateConfig(config);
174
+ if (errors.length > 0) {
175
+ throw new Error(`Invalid configuration: ${errors.join(', ')}`);
176
+ }
177
+
178
+ if (this._options.debug) {
179
+ console.log('TelnyxVoipClient: Logging in with token');
180
+ }
181
+
182
+ await this._sessionManager.connectWithToken(config);
183
+ }
184
+
185
+ /**
186
+ * Disconnects from the Telnyx platform.
187
+ *
188
+ * This method terminates the connection, ends any active calls, and
189
+ * cleans up all related resources.
190
+ */
191
+ async logout(): Promise<void> {
192
+ if (this._disposed) {
193
+ return;
194
+ }
195
+
196
+ if (this._options.debug) {
197
+ console.log('TelnyxVoipClient: Logging out');
198
+ }
199
+
200
+ await this._sessionManager.disconnect();
201
+ }
202
+
203
+ /**
204
+ * Attempts to reconnect using previously stored configuration.
205
+ *
206
+ * This method is used for auto-reconnection scenarios where the app
207
+ * comes back to the foreground and needs to restore the connection.
208
+ *
209
+ * @returns Promise<boolean> - true if reconnection was successful, false otherwise
210
+ */
211
+ async loginFromStoredConfig(): Promise<boolean> {
212
+ this._throwIfDisposed();
213
+
214
+ if (this._options.debug) {
215
+ console.log('TelnyxVoipClient: Attempting to login from stored config');
216
+ }
217
+
218
+ try {
219
+ // Try to retrieve stored credentials and token from AsyncStorage
220
+ const AsyncStorage = require('@react-native-async-storage/async-storage').default;
221
+
222
+ const storedUsername = await AsyncStorage.getItem('@telnyx_username');
223
+ const storedPassword = await AsyncStorage.getItem('@telnyx_password');
224
+ const storedCredentialToken = await AsyncStorage.getItem('@credential_token');
225
+ const storedPushToken = await AsyncStorage.getItem('@push_token');
226
+
227
+ // Check if we have credential-based authentication data
228
+ if (storedUsername && storedPassword) {
229
+ // Create credential config from stored data
230
+ const { createCredentialConfig } = require('./models/config');
231
+ const config = createCredentialConfig(storedUsername, storedPassword, {
232
+ pushNotificationDeviceToken: storedPushToken,
233
+ });
234
+
235
+ if (this._options.debug) {
236
+ console.log(
237
+ 'TelnyxVoipClient: Reconnecting with stored credentials for user:',
238
+ storedUsername
239
+ );
240
+ }
241
+
242
+ await this._sessionManager.connectWithCredential(config);
243
+ return true;
244
+ }
245
+
246
+ // Check if we have token-based authentication data
247
+ if (storedCredentialToken) {
248
+ // Create token config from stored data
249
+ const { createTokenConfig } = require('./models/config');
250
+ const config = createTokenConfig(storedCredentialToken, {
251
+ pushNotificationDeviceToken: storedPushToken,
252
+ });
253
+
254
+ if (this._options.debug) {
255
+ console.log('TelnyxVoipClient: Reconnecting with stored token');
256
+ }
257
+
258
+ await this._sessionManager.connectWithToken(config);
259
+ return true;
260
+ }
261
+
262
+ // No stored authentication data found
263
+ if (this._options.debug) {
264
+ console.log('TelnyxVoipClient: No stored credentials or token found');
265
+ }
266
+ return false;
267
+ } catch (error) {
268
+ if (this._options.debug) {
269
+ console.log('TelnyxVoipClient: Failed to login from stored config:', error);
270
+ }
271
+ return false;
272
+ }
273
+ }
274
+
275
+ // ========== Call Management Methods ==========
276
+
277
+ /**
278
+ * Initiates a new outgoing call.
279
+ *
280
+ * @param destination The destination number or SIP URI to call
281
+ * @param debug Optional flag to enable call quality metrics for this call
282
+ * @returns A Promise that completes with the Call object once the invitation has been sent
283
+ *
284
+ * The call's state can be monitored through the returned Call object's streams.
285
+ */
286
+ async newCall(destination: string, debug: boolean = false): Promise<Call> {
287
+ this._throwIfDisposed();
288
+
289
+ if (!destination || destination.trim() === '') {
290
+ throw new Error('Destination is required');
291
+ }
292
+
293
+ if (this.currentConnectionState !== TelnyxConnectionState.CONNECTED) {
294
+ throw new Error(`Cannot make call when connection state is: ${this.currentConnectionState}`);
295
+ }
296
+
297
+ if (this._options.debug) {
298
+ console.log('TelnyxVoipClient: Creating new call to:', destination);
299
+ }
300
+
301
+ return await this._callStateController.newCall(destination, undefined, undefined, debug);
302
+ }
303
+
304
+ // ========== Push Notification Methods ==========
305
+
306
+ /**
307
+ * Handle push notification payload.
308
+ *
309
+ * This is the unified entry point for all push notifications. It intelligently
310
+ * determines whether to show a new incoming call UI or to process an already
311
+ * actioned (accepted/declined) call upon app launch.
312
+ *
313
+ * @param payload The push notification payload
314
+ */
315
+ async handlePushNotification(payload: Record<string, any>): Promise<void> {
316
+ this._throwIfDisposed();
317
+
318
+ if (this._options.debug) {
319
+ console.log('TelnyxVoipClient: Handling push notification:', payload);
320
+ }
321
+
322
+ try {
323
+ // First, pass the push notification to the session manager for processing
324
+ // This will set the isCallFromPush flag on the TelnyxRTC client
325
+ await this._sessionManager.handlePushNotification(payload);
326
+
327
+ // Connect if not already connected
328
+ const currentState = this.currentConnectionState;
329
+ if (currentState !== TelnyxConnectionState.CONNECTED) {
330
+ // Try to login from stored config - now the push flags should be set
331
+ const loginSuccess = await this.loginFromStoredConfig();
332
+ if (!loginSuccess) {
333
+ console.warn(
334
+ 'TelnyxVoipClient: Could not login from stored config for push notification'
335
+ );
336
+ return;
337
+ }
338
+ }
339
+ } catch (error) {
340
+ console.error('TelnyxVoipClient: Error handling push notification:', error);
341
+ throw error;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Disables push notifications for the current session.
347
+ *
348
+ * This method sends a request to the Telnyx backend to disable push
349
+ * notifications for the current registered device/session.
350
+ */
351
+ disablePushNotifications(): void {
352
+ this._throwIfDisposed();
353
+
354
+ if (this._options.debug) {
355
+ console.log('TelnyxVoipClient: Disabling push notifications');
356
+ }
357
+
358
+ this._sessionManager.disablePushNotifications();
359
+ }
360
+
361
+ // ========== CallKit Integration Methods ==========
362
+
363
+ /**
364
+ * Set a call to connecting state (used for push notification calls when answered via CallKit)
365
+ * @param callId The ID of the call to set to connecting state
366
+ * @internal
367
+ */
368
+ setCallConnecting(callId: string): void {
369
+ this._callStateController.setCallConnecting(callId);
370
+ }
371
+
372
+ /**
373
+ * Find a call by its underlying Telnyx call object
374
+ * @param telnyxCall The Telnyx call object to find
375
+ * @internal
376
+ */
377
+ findCallByTelnyxCall(telnyxCall: any): Call | null {
378
+ return this._callStateController.findCallByTelnyxCall(telnyxCall);
379
+ }
380
+
381
+ /**
382
+ * Queue an answer action for when the call invite arrives (for CallKit integration)
383
+ * This should be called when the user answers from CallKit before the socket connection is established
384
+ * @param customHeaders Optional custom headers to include with the answer
385
+ */
386
+ queueAnswerFromCallKit(customHeaders: Record<string, string> = {}): void {
387
+ this._throwIfDisposed();
388
+
389
+ if (this._options.debug) {
390
+ console.log('TelnyxVoipClient: Queuing answer action from CallKit', customHeaders);
391
+ }
392
+
393
+ const telnyxClient = this._sessionManager.telnyxClient;
394
+ if (telnyxClient && typeof (telnyxClient as any).queueAnswerFromCallKit === 'function') {
395
+ (telnyxClient as any).queueAnswerFromCallKit(customHeaders);
396
+ } else {
397
+ console.warn(
398
+ 'TelnyxVoipClient: TelnyxRTC client not available or method not found for queueAnswerFromCallKit'
399
+ );
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Queue an end action for when the call invite arrives (for CallKit integration)
405
+ * This should be called when the user ends from CallKit before the socket connection is established
406
+ */
407
+ queueEndFromCallKit(): void {
408
+ this._throwIfDisposed();
409
+
410
+ if (this._options.debug) {
411
+ console.log('TelnyxVoipClient: Queuing end action from CallKit');
412
+ }
413
+
414
+ const telnyxClient = this._sessionManager.telnyxClient;
415
+ if (telnyxClient && typeof (telnyxClient as any).queueEndFromCallKit === 'function') {
416
+ (telnyxClient as any).queueEndFromCallKit();
417
+ } else {
418
+ console.warn(
419
+ 'TelnyxVoipClient: TelnyxRTC client not available or method not found for queueEndFromCallKit'
420
+ );
421
+ }
422
+ }
423
+
424
+ // ========== Lifecycle Methods ==========
425
+
426
+ /**
427
+ * Dispose of the client and clean up all resources.
428
+ *
429
+ * After calling this method, the client instance should not be used anymore.
430
+ * This is particularly important for background clients that should be
431
+ * disposed after handling push notifications.
432
+ */
433
+ dispose(): void {
434
+ if (this._disposed) {
435
+ return;
436
+ }
437
+
438
+ if (this._options.debug) {
439
+ console.log('TelnyxVoipClient: Disposing client');
440
+ }
441
+
442
+ this._disposed = true;
443
+ this._callStateController.dispose();
444
+ this._sessionManager.dispose();
445
+ }
446
+
447
+ // ========== Private Methods ==========
448
+
449
+ /**
450
+ * Throw an error if the client has been disposed
451
+ */
452
+ private _throwIfDisposed(): void {
453
+ if (this._disposed) {
454
+ throw new Error('TelnyxVoipClient has been disposed');
455
+ }
456
+ }
457
+ }
458
+
459
+ // ========== Factory Functions ==========
460
+
461
+ /**
462
+ * Create a new TelnyxVoipClient instance for normal app usage
463
+ */
464
+ export function createTelnyxVoipClient(options?: TelnyxVoipClientOptions): TelnyxVoipClient {
465
+ return new TelnyxVoipClient(options);
466
+ }
467
+
468
+ /**
469
+ * Create a new TelnyxVoipClient instance for background push notification handling
470
+ */
471
+ export function createBackgroundTelnyxVoipClient(
472
+ options?: TelnyxVoipClientOptions
473
+ ): TelnyxVoipClient {
474
+ return new TelnyxVoipClient(options);
475
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Type definitions for Telnyx React Native Voice SDK
3
+ * This file provides type definitions without importing the actual SDK
4
+ */
5
+
6
+ declare module '@telnyx/react-native-voice-sdk' {
7
+ import { EventEmitter } from 'eventemitter3';
8
+
9
+ export interface CallOptions {
10
+ callerIdName?: string;
11
+ callerIdNumber?: string;
12
+ customHeaders?: Record<string, string>;
13
+ clientState?: string;
14
+ destinationNumber?: string;
15
+ audio?: boolean;
16
+ video?: boolean;
17
+ }
18
+
19
+ export interface ClientOptions {
20
+ login?: string;
21
+ password?: string;
22
+ token?: string;
23
+ login_token?: string;
24
+ ringtoneFile?: string;
25
+ ringbackFile?: string;
26
+ debug?: boolean;
27
+ logLevel?: string;
28
+ pushNotificationDeviceToken?: string;
29
+ }
30
+
31
+ export enum CallState {
32
+ NEW = 'new',
33
+ CONNECTING = 'connecting',
34
+ RINGING = 'ringing',
35
+ ACTIVE = 'active',
36
+ HELD = 'held',
37
+ HANGUP = 'hangup',
38
+ DESTROY = 'destroy',
39
+ PURGE = 'purge',
40
+ }
41
+
42
+ export class Call extends EventEmitter {
43
+ callId: string;
44
+ state: CallState;
45
+ direction: 'inbound' | 'outbound';
46
+ remoteCallerIdName?: string;
47
+ remoteCallerIdNumber?: string;
48
+ localCallerIdName?: string;
49
+ localCallerIdNumber?: string;
50
+
51
+ constructor(options: any);
52
+
53
+ answer(): Promise<void>;
54
+ hangup(): Promise<void>;
55
+ hold(): Promise<void>;
56
+ unhold(): Promise<void>;
57
+ mute(): Promise<void>;
58
+ unmute(): Promise<void>;
59
+ dtmf(digits: string): Promise<void>;
60
+
61
+ on(event: string, listener: (...args: any[]) => void): this;
62
+ off(event: string, listener: (...args: any[]) => void): this;
63
+ emit(event: string, ...args: any[]): boolean;
64
+ }
65
+
66
+ export class TelnyxRTC extends EventEmitter {
67
+ constructor(options: ClientOptions);
68
+
69
+ connect(): Promise<void>;
70
+ disconnect(): void;
71
+ newCall(options: CallOptions): Promise<Call>;
72
+
73
+ on(event: string, listener: (...args: any[]) => void): this;
74
+ off(event: string, listener: (...args: any[]) => void): this;
75
+ emit(event: string, ...args: any[]): boolean;
76
+ }
77
+
78
+ export { TelnyxRTC as default };
79
+ }