@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,690 @@
1
+ import React, { useEffect, useRef, useState, useCallback } from 'react';
2
+ import { AppState, AppStateStatus, Platform } from 'react-native';
3
+ import { TelnyxVoipClient, createBackgroundTelnyxVoipClient } from './telnyx-voip-client';
4
+ import { TelnyxConnectionState } from './models/connection-state';
5
+ import { Call } from './models/call';
6
+ import { TelnyxVoiceProvider } from './context/TelnyxVoiceContext';
7
+
8
+ /**
9
+ * Configuration options for TelnyxVoiceApp
10
+ */
11
+ export interface TelnyxVoiceAppOptions {
12
+ /** The TelnyxVoipClient instance to manage */
13
+ voipClient: TelnyxVoipClient;
14
+
15
+ /** Optional callback when push notification processing starts */
16
+ onPushNotificationProcessingStarted?: () => void;
17
+
18
+ /** Optional callback when push notification processing completes */
19
+ onPushNotificationProcessingCompleted?: () => void;
20
+
21
+ /** Optional callback for additional background/foreground handling */
22
+ onAppStateChanged?: (state: AppStateStatus) => void;
23
+
24
+ /** Whether to enable automatic login/reconnection (default: true) */
25
+ enableAutoReconnect?: boolean;
26
+
27
+ /** Whether to skip web platform for background detection (default: true) */
28
+ skipWebBackgroundDetection?: boolean;
29
+
30
+ /** Enable debug logging */
31
+ debug?: boolean;
32
+ }
33
+
34
+ /**
35
+ * Props for the TelnyxVoiceApp component
36
+ */
37
+ export interface TelnyxVoiceAppProps extends TelnyxVoiceAppOptions {
38
+ /** The child components to render */
39
+ children: React.ReactNode;
40
+ }
41
+
42
+ /**
43
+ * Interface for the TelnyxVoiceApp component with static methods
44
+ */
45
+ export interface TelnyxVoiceAppComponent extends React.FC<TelnyxVoiceAppProps> {
46
+ initializeAndCreate: (options: {
47
+ voipClient: TelnyxVoipClient;
48
+ children: React.ReactNode;
49
+ backgroundMessageHandler?: (message: any) => Promise<void>;
50
+ onPushNotificationProcessingStarted?: () => void;
51
+ onPushNotificationProcessingCompleted?: () => void;
52
+ onAppStateChanged?: (state: AppStateStatus) => void;
53
+ enableAutoReconnect?: boolean;
54
+ skipWebBackgroundDetection?: boolean;
55
+ debug?: boolean;
56
+ }) => Promise<React.ComponentType>;
57
+
58
+ handleBackgroundPush: (message: any) => Promise<void>;
59
+ }
60
+
61
+ /**
62
+ * A comprehensive wrapper component that handles all Telnyx SDK lifecycle management.
63
+ *
64
+ * This component automatically handles:
65
+ * - Push notification initialization from terminated state
66
+ * - Background/foreground lifecycle detection and auto-reconnection
67
+ * - Login state management with automatic reconnection
68
+ * - CallKit integration preparation
69
+ *
70
+ * Simply wrap your main app component with this to get full Telnyx functionality:
71
+ * ```tsx
72
+ * <TelnyxVoiceApp voipClient={myVoipClient}>
73
+ * <MyApp />
74
+ * </TelnyxVoiceApp>
75
+ * ```
76
+ */
77
+ const TelnyxVoiceAppComponent: React.FC<TelnyxVoiceAppProps> = ({
78
+ voipClient,
79
+ children,
80
+ onPushNotificationProcessingStarted,
81
+ onPushNotificationProcessingCompleted,
82
+ onAppStateChanged,
83
+ enableAutoReconnect = true,
84
+ skipWebBackgroundDetection = true,
85
+ debug = false,
86
+ }) => {
87
+ // State management
88
+ const [processingPushOnLaunch, setProcessingPushOnLaunch] = useState(false);
89
+ const [isHandlingForegroundCall, setIsHandlingForegroundCall] = useState(false);
90
+ const [currentConnectionState, setCurrentConnectionState] = useState<TelnyxConnectionState>(
91
+ voipClient.currentConnectionState
92
+ );
93
+
94
+ // Refs for tracking state
95
+ const appStateRef = useRef<AppStateStatus>(AppState.currentState);
96
+ const backgroundDetectorIgnore = useRef(false);
97
+
98
+ // Static background client instance for singleton pattern
99
+ const backgroundClientRef = useRef<TelnyxVoipClient | null>(null);
100
+
101
+ const log = useCallback(
102
+ (message: string, ...args: any[]) => {
103
+ if (debug) {
104
+ console.log(`[TelnyxVoiceApp] ${message}`, ...args);
105
+ }
106
+ },
107
+ [debug]
108
+ );
109
+
110
+ // Handle app state changes
111
+ const handleAppStateChange = useCallback(
112
+ async (nextAppState: AppStateStatus) => {
113
+ const previousAppState = appStateRef.current;
114
+ appStateRef.current = nextAppState;
115
+
116
+ log(`App state changed from ${previousAppState} to ${nextAppState}`);
117
+ log(`Background detector ignore flag: ${backgroundDetectorIgnore.current}`);
118
+ log(`Handling foreground call: ${isHandlingForegroundCall}`);
119
+
120
+ // Call optional user callback first
121
+ onAppStateChanged?.(nextAppState);
122
+
123
+ // Only handle background disconnection when actually transitioning from active to background
124
+ // Don't disconnect on background-to-background transitions (e.g., during CallKit operations)
125
+ if (
126
+ (nextAppState === 'background' || nextAppState === 'inactive') &&
127
+ previousAppState === 'active'
128
+ ) {
129
+ log(
130
+ `App transitioned from ${previousAppState} to ${nextAppState} - handling backgrounding`
131
+ );
132
+ await handleAppBackgrounded();
133
+ } else if (nextAppState === 'background' || nextAppState === 'inactive') {
134
+ log(
135
+ `App state is ${nextAppState} but was already ${previousAppState} - skipping background handling`
136
+ );
137
+ }
138
+
139
+ // Always check for push notifications when app becomes active (regardless of auto-reconnect setting)
140
+ if (nextAppState === 'active' && previousAppState !== 'active') {
141
+ log('App became active - checking for push notifications');
142
+ await checkForInitialPushNotification(true); // Pass true for fromAppResume
143
+ }
144
+
145
+ // Only handle auto-reconnection if auto-reconnect is enabled
146
+ if (enableAutoReconnect && nextAppState === 'active' && previousAppState !== 'active') {
147
+ await handleAppResumed();
148
+ }
149
+ },
150
+ [enableAutoReconnect, onAppStateChanged, isHandlingForegroundCall, log]
151
+ );
152
+
153
+ // Handle app going to background - disconnect like the old implementation
154
+ const handleAppBackgrounded = useCallback(async () => {
155
+ // Check if we should ignore background detection (e.g., during active calls)
156
+ if (backgroundDetectorIgnore.current || isHandlingForegroundCall) {
157
+ log(
158
+ 'Background detector ignore flag set or handling foreground call - skipping disconnection'
159
+ );
160
+ return;
161
+ }
162
+
163
+ // Check if there are any active calls that should prevent disconnection
164
+ const activeCalls = voipClient.currentCalls;
165
+ const hasOngoingCall =
166
+ activeCalls.length > 0 &&
167
+ activeCalls.some(
168
+ (call) =>
169
+ call.currentState === 'ACTIVE' ||
170
+ call.currentState === 'HELD' ||
171
+ call.currentState === 'RINGING' ||
172
+ call.currentState === 'CONNECTING'
173
+ );
174
+
175
+ // Also check if there's an incoming call from push notification being processed
176
+ let isCallFromPush = false;
177
+ if (Platform.OS === 'ios') {
178
+ try {
179
+ const { callKitCoordinator } = require('./callkit/callkit-coordinator');
180
+ isCallFromPush = callKitCoordinator.getIsCallFromPush();
181
+ } catch (e) {
182
+ log('Error checking isCallFromPush:', e);
183
+ }
184
+ }
185
+
186
+ if (hasOngoingCall || isCallFromPush) {
187
+ log('Active calls or push call detected - skipping background disconnection', {
188
+ callCount: activeCalls.length,
189
+ hasOngoingCall,
190
+ isCallFromPush,
191
+ callStates: activeCalls.map((call) => ({
192
+ callId: call.callId,
193
+ currentState: call.currentState,
194
+ destination: call.destination,
195
+ })),
196
+ });
197
+ return;
198
+ }
199
+
200
+ log('App backgrounded - disconnecting (matching old BackgroundDetector behavior)');
201
+
202
+ try {
203
+ // Always disconnect when backgrounded (matches old implementation)
204
+ await voipClient.logout();
205
+ log('Successfully disconnected on background');
206
+ } catch (e) {
207
+ log('Error disconnecting on background:', e);
208
+ }
209
+ }, [voipClient, isHandlingForegroundCall, log]);
210
+
211
+ // Handle app resuming from background
212
+ const handleAppResumed = useCallback(async () => {
213
+ log('App resumed - checking reconnection needs');
214
+
215
+ // IMPORTANT: Check for push notifications first when resuming from background
216
+ // This handles the case where the user accepted a call while the app was backgrounded
217
+ await checkForInitialPushNotification(true); // Pass true for fromAppResume
218
+
219
+ // If we're ignoring (e.g., from push call) or handling foreground call, don't auto-reconnect
220
+ if (backgroundDetectorIgnore.current || isHandlingForegroundCall) {
221
+ log(
222
+ 'Background detector ignore flag set or handling foreground call - skipping reconnection'
223
+ );
224
+ return;
225
+ }
226
+
227
+ // iOS-specific: If push notification handling just initiated a connection,
228
+ // skip auto-reconnection to prevent double login
229
+ if (Platform.OS === 'ios') {
230
+ // Check if connection state changed after push processing
231
+ const connectionStateAfterPush = voipClient.currentConnectionState;
232
+ if (
233
+ connectionStateAfterPush === TelnyxConnectionState.CONNECTING ||
234
+ connectionStateAfterPush === TelnyxConnectionState.CONNECTED
235
+ ) {
236
+ log(
237
+ `iOS: Push handling initiated connection (${connectionStateAfterPush}), skipping auto-reconnection`
238
+ );
239
+ return;
240
+ }
241
+ }
242
+
243
+ // Check current connection state and reconnect if needed
244
+ const currentState = voipClient.currentConnectionState;
245
+ log(`Current connection state: ${currentState}`);
246
+
247
+ // If we're not connected and have stored credentials, attempt reconnection
248
+ if (currentState !== TelnyxConnectionState.CONNECTED) {
249
+ await attemptAutoReconnection();
250
+ }
251
+ }, [voipClient, isHandlingForegroundCall, log]);
252
+
253
+ // Attempt to reconnect using stored credentials
254
+ const attemptAutoReconnection = useCallback(async () => {
255
+ try {
256
+ log('Attempting auto-reconnection...');
257
+
258
+ // Try to get stored config and reconnect
259
+ const success = await voipClient.loginFromStoredConfig();
260
+ log(`Auto-reconnection ${success ? 'successful' : 'failed'}`);
261
+
262
+ // If auto-reconnection fails, redirect to login screen
263
+ if (!success) {
264
+ log('Auto-reconnection failed - redirecting to login screen');
265
+ // Import router dynamically to avoid circular dependency issues
266
+ const { router } = require('expo-router');
267
+
268
+ // Small delay to ensure state is settled
269
+ setTimeout(() => {
270
+ router.replace('/');
271
+ }, 100);
272
+ }
273
+ } catch (e) {
274
+ log('Auto-reconnection error:', e);
275
+
276
+ // On error, also redirect to login
277
+ log('Auto-reconnection error - redirecting to login screen');
278
+ const { router } = require('expo-router');
279
+ setTimeout(() => {
280
+ router.replace('/');
281
+ }, 100);
282
+ }
283
+ }, [voipClient, log]);
284
+
285
+ // Check for initial push notification when app launches
286
+ const checkForInitialPushNotification = useCallback(
287
+ async (fromAppResume: boolean = false) => {
288
+ log(`checkForInitialPushNotification called${fromAppResume ? ' (from app resume)' : ''}`);
289
+
290
+ if (processingPushOnLaunch && !fromAppResume) {
291
+ log('Already processing push, returning early');
292
+ return;
293
+ }
294
+
295
+ // Only set the flag if this is not from app resume to allow resume processing
296
+ if (!fromAppResume) {
297
+ setProcessingPushOnLaunch(true);
298
+ }
299
+ onPushNotificationProcessingStarted?.();
300
+
301
+ try {
302
+ let pushData: Record<string, any> | null = null;
303
+
304
+ // Try to get push data from the native layer using our VoicePnBridge
305
+ try {
306
+ // Import the native bridge module dynamically
307
+ const { NativeModules } = require('react-native');
308
+ const VoicePnBridge = NativeModules.VoicePnBridge;
309
+
310
+ if (VoicePnBridge) {
311
+ log('Checking for pending push actions via VoicePnBridge');
312
+ const pendingAction = await VoicePnBridge.getPendingPushAction();
313
+ log('Raw pending action response:', pendingAction);
314
+
315
+ if (pendingAction && pendingAction.action != null && pendingAction.metadata != null) {
316
+ log('Found pending push action:', pendingAction);
317
+
318
+ // Parse the metadata if it's a string
319
+ let metadata = pendingAction.metadata;
320
+ if (typeof metadata === 'string') {
321
+ try {
322
+ // First try parsing as JSON
323
+ metadata = JSON.parse(metadata);
324
+ log('Parsed metadata as JSON:', metadata);
325
+ } catch (e) {
326
+ // If JSON parsing fails, try parsing Android key-value format
327
+ // Format: "{call_id=value, action=value}"
328
+ log('JSON parse failed, trying Android key-value format');
329
+ try {
330
+ const cleanedString = metadata.replace(/[{}]/g, '').trim();
331
+ const pairs = cleanedString.split(',').map((pair) => pair.trim());
332
+ const parsed: Record<string, any> = {};
333
+
334
+ for (const pair of pairs) {
335
+ const [key, value] = pair.split('=').map((s) => s.trim());
336
+ if (key && value) {
337
+ parsed[key] = value;
338
+ }
339
+ }
340
+
341
+ metadata = parsed;
342
+ log('Parsed metadata as Android key-value format:', metadata);
343
+ } catch (parseError) {
344
+ log('Failed to parse metadata in any format, using as-is:', parseError);
345
+ }
346
+ }
347
+ }
348
+
349
+ // Create push data structure that matches what the VoIP client expects
350
+ pushData = {
351
+ action: pendingAction.action,
352
+ metadata: metadata,
353
+ from_notification: true,
354
+ };
355
+
356
+ // Clear the pending action so it doesn't get processed again
357
+ await VoicePnBridge.clearPendingPushAction();
358
+ log('Cleared pending push action after retrieval');
359
+ } else {
360
+ log('No pending push actions found');
361
+ }
362
+ } else {
363
+ log('VoicePnBridge not available - this is expected on iOS');
364
+ }
365
+ } catch (bridgeError) {
366
+ log('Error accessing VoicePnBridge:', bridgeError);
367
+ }
368
+
369
+ // Process the push notification if found
370
+ if (pushData) {
371
+ log('Processing initial push notification...');
372
+
373
+ // Check if we're already connected and handling a push - prevent duplicate processing
374
+ const isConnected = voipClient.currentConnectionState === TelnyxConnectionState.CONNECTED;
375
+ if (isConnected) {
376
+ log('SKIPPING - Already connected, preventing duplicate processing');
377
+ // Clear the stored data since we're already handling it
378
+ // TODO: Implement clearPushMetaData
379
+ return;
380
+ }
381
+
382
+ // Set flags to prevent auto-reconnection during push call
383
+ setIsHandlingForegroundCall(true);
384
+ backgroundDetectorIgnore.current = true;
385
+ log(`Background detector ignore set to: true at ${new Date().toISOString()}`);
386
+ log(`Foreground call handling flag set to: true at ${new Date().toISOString()}`);
387
+
388
+ // Dispose any existing background client to prevent conflicts
389
+ disposeBackgroundClient();
390
+
391
+ // Handle the push notification using platform-specific approach
392
+ if (Platform.OS === 'ios') {
393
+ // On iOS, coordinate with CallKit by notifying the coordinator about the push
394
+ const { callKitCoordinator } = require('./callkit/callkit-coordinator');
395
+
396
+ // Extract call_id from nested metadata structure to use as CallKit UUID
397
+ const callId = pushData.metadata?.metadata?.call_id;
398
+ if (callId) {
399
+ log('Notifying CallKit coordinator about push notification:', callId);
400
+ await callKitCoordinator.handleCallKitPushReceived(callId, {
401
+ callData: { source: 'push_notification' },
402
+ pushData: pushData,
403
+ });
404
+ } else {
405
+ log('No call_id found in push data, falling back to direct handling');
406
+ await voipClient.handlePushNotification(pushData);
407
+ }
408
+ } else {
409
+ // On other platforms, handle push notification directly
410
+ await voipClient.handlePushNotification(pushData);
411
+ }
412
+
413
+ log('Initial push notification processed');
414
+ log('Cleared stored push data to prevent duplicate processing');
415
+
416
+ // Note: isHandlingForegroundCall will be reset when calls.length becomes 0
417
+ // This prevents premature disconnection during CallKit answer flow
418
+ } else {
419
+ log('No initial push data found');
420
+ }
421
+ } catch (e) {
422
+ log('Error processing initial push notification:', e);
423
+ // Reset flags on error
424
+ setIsHandlingForegroundCall(false);
425
+ } finally {
426
+ // Always reset the processing flag - it should not remain stuck
427
+ setProcessingPushOnLaunch(false);
428
+ onPushNotificationProcessingCompleted?.();
429
+ }
430
+ },
431
+ [
432
+ processingPushOnLaunch,
433
+ voipClient,
434
+ onPushNotificationProcessingStarted,
435
+ onPushNotificationProcessingCompleted,
436
+ log,
437
+ ]
438
+ );
439
+
440
+ // Dispose background client instance when no longer needed
441
+ const disposeBackgroundClient = useCallback(() => {
442
+ if (backgroundClientRef.current) {
443
+ log('Disposing background client instance');
444
+ backgroundClientRef.current.dispose();
445
+ backgroundClientRef.current = null;
446
+ }
447
+ }, [log]);
448
+
449
+ // Create background client for push notification handling
450
+ const createBackgroundClient = useCallback((): TelnyxVoipClient => {
451
+ log('Creating background client instance');
452
+
453
+ const backgroundClient = createBackgroundTelnyxVoipClient({
454
+ debug,
455
+ });
456
+
457
+ return backgroundClient;
458
+ }, [debug, log]);
459
+
460
+ // Setup effect
461
+ useEffect(() => {
462
+ // Listen to connection state changes
463
+ const connectionStateSubscription = voipClient.connectionState$.subscribe((state) => {
464
+ setCurrentConnectionState(state);
465
+
466
+ // Just log connection changes, let the app handle navigation
467
+ log(`Connection state changed to: ${state}`);
468
+ });
469
+
470
+ // Listen to call changes to reset flags when no active calls
471
+ const callsSubscription = voipClient.calls$.subscribe((calls) => {
472
+ // Check if we should reset flags - only reset if:
473
+ // 1. No active WebRTC calls AND
474
+ // 2. No CallKit operations in progress (to prevent disconnection during CallKit answer flow)
475
+ const hasActiveWebRTCCalls = calls.length > 0;
476
+ let hasCallKitProcessing = false;
477
+
478
+ // Check CallKit processing calls only on iOS
479
+ if (Platform.OS === 'ios') {
480
+ try {
481
+ const { callKitCoordinator } = require('./callkit/callkit-coordinator');
482
+ hasCallKitProcessing = callKitCoordinator.hasProcessingCalls();
483
+ log(`CallKit processing check: hasProcessingCalls=${hasCallKitProcessing}`);
484
+ } catch (e) {
485
+ log('Error checking CallKit processing calls:', e);
486
+ }
487
+ }
488
+
489
+ log(
490
+ `Flag reset check: WebRTC calls=${calls.length}, CallKit processing=${hasCallKitProcessing}, isHandlingForegroundCall=${isHandlingForegroundCall}, backgroundDetectorIgnore=${backgroundDetectorIgnore.current}`
491
+ );
492
+
493
+ if (
494
+ !hasActiveWebRTCCalls &&
495
+ !hasCallKitProcessing &&
496
+ (isHandlingForegroundCall || backgroundDetectorIgnore.current)
497
+ ) {
498
+ log(
499
+ `No active calls and no CallKit processing - resetting ignore flags at ${new Date().toISOString()}`
500
+ );
501
+ setIsHandlingForegroundCall(false);
502
+ backgroundDetectorIgnore.current = false;
503
+ } else if (!hasActiveWebRTCCalls && hasCallKitProcessing) {
504
+ log(
505
+ `No WebRTC calls but CallKit operations in progress - keeping ignore flags active at ${new Date().toISOString()}`
506
+ );
507
+ } else if (hasActiveWebRTCCalls) {
508
+ log(`WebRTC calls active - keeping ignore flags active at ${new Date().toISOString()}`);
509
+ }
510
+
511
+ // Also reset processingPushOnLaunch if no calls are active
512
+ // This ensures the flag doesn't get stuck after call ends
513
+ if (calls.length === 0 && processingPushOnLaunch) {
514
+ log('No active calls - resetting processing push flag');
515
+ setProcessingPushOnLaunch(false);
516
+ }
517
+ });
518
+
519
+ // Add app state listener if not skipping web background detection or not on web
520
+ // AND if app state management is enabled in the client options
521
+ let appStateSubscription: any = null;
522
+ if (
523
+ (!skipWebBackgroundDetection || Platform.OS !== 'web') &&
524
+ voipClient.options.enableAppStateManagement
525
+ ) {
526
+ appStateSubscription = AppState.addEventListener('change', handleAppStateChange);
527
+ }
528
+
529
+ // Handle initial push notification if app was launched from terminated state
530
+ // Only check if we're not already processing to prevent infinite loops
531
+ const timeoutId = setTimeout(() => {
532
+ if (!processingPushOnLaunch) {
533
+ checkForInitialPushNotification();
534
+ }
535
+ }, 100);
536
+
537
+ // Cleanup function
538
+ return () => {
539
+ connectionStateSubscription.unsubscribe();
540
+ callsSubscription.unsubscribe();
541
+ if (appStateSubscription) {
542
+ appStateSubscription.remove();
543
+ }
544
+ clearTimeout(timeoutId);
545
+ // Clean up background client instance
546
+ disposeBackgroundClient();
547
+ };
548
+ }, [
549
+ voipClient,
550
+ handleAppStateChange,
551
+ disposeBackgroundClient,
552
+ skipWebBackgroundDetection,
553
+ isHandlingForegroundCall,
554
+ log,
555
+ ]);
556
+
557
+ // Simply return the children wrapped in context provider - all lifecycle management is handled internally
558
+ return <TelnyxVoiceProvider voipClient={voipClient}>{children}</TelnyxVoiceProvider>;
559
+ };
560
+
561
+ /**
562
+ * Static factory method that handles all common SDK initialization boilerplate.
563
+ *
564
+ * This is the recommended way to initialize the Telnyx Voice SDK in your app.
565
+ * It ensures that push notifications, background handlers, and other dependencies are
566
+ * set up correctly before the app runs.
567
+ *
568
+ * This method:
569
+ * - Initializes push notification handling
570
+ * - Registers the background push notification handler
571
+ * - Returns a fully configured TelnyxVoiceApp component to be used in your app
572
+ *
573
+ * ## Usage:
574
+ * ```tsx
575
+ * const App = TelnyxVoiceApp.initializeAndCreate({
576
+ * voipClient: myVoipClient,
577
+ * backgroundHandler: backgroundHandler,
578
+ * children: <MyApp />,
579
+ * });
580
+ * ```
581
+ */
582
+ const initializeAndCreate = async (options: {
583
+ /** The TelnyxVoipClient instance that will be managed by this component */
584
+ voipClient: TelnyxVoipClient;
585
+
586
+ /** The main component of your application */
587
+ children: React.ReactNode;
588
+
589
+ /** The function that will handle background push notifications */
590
+ backgroundMessageHandler?: (message: any) => Promise<void>;
591
+
592
+ /** Optional callback when push notification processing starts */
593
+ onPushNotificationProcessingStarted?: () => void;
594
+
595
+ /** Optional callback when push notification processing completes */
596
+ onPushNotificationProcessingCompleted?: () => void;
597
+
598
+ /** Optional callback for app state changes */
599
+ onAppStateChanged?: (state: AppStateStatus) => void;
600
+
601
+ /** Whether to enable automatic reconnection (default: true) */
602
+ enableAutoReconnect?: boolean;
603
+
604
+ /** Whether to skip web background detection (default: true) */
605
+ skipWebBackgroundDetection?: boolean;
606
+
607
+ /** Enable debug logging */
608
+ debug?: boolean;
609
+ }): Promise<React.ComponentType> => {
610
+ const {
611
+ voipClient,
612
+ children,
613
+ backgroundMessageHandler,
614
+ onPushNotificationProcessingStarted,
615
+ onPushNotificationProcessingCompleted,
616
+ onAppStateChanged,
617
+ enableAutoReconnect = true,
618
+ skipWebBackgroundDetection = true,
619
+ debug = false,
620
+ } = options;
621
+
622
+ // Initialize push notification handling for Android
623
+ if (Platform.OS === 'android') {
624
+ // TODO: Initialize Firebase or other push notification service
625
+ if (debug) {
626
+ console.log('[TelnyxVoiceApp] Android push notification initialization needed');
627
+ }
628
+ }
629
+
630
+ // Register background message handler if provided
631
+ if (backgroundMessageHandler) {
632
+ // TODO: Register the background message handler with the push notification service
633
+ if (debug) {
634
+ console.log('[TelnyxVoiceApp] Background message handler registration needed');
635
+ }
636
+ }
637
+
638
+ if (debug) {
639
+ console.log('[TelnyxVoiceApp] SDK initialization complete');
640
+ }
641
+
642
+ // Return a component that renders TelnyxVoiceApp with the provided options
643
+ return () => (
644
+ <TelnyxVoiceApp
645
+ voipClient={voipClient}
646
+ onPushNotificationProcessingStarted={onPushNotificationProcessingStarted}
647
+ onPushNotificationProcessingCompleted={onPushNotificationProcessingCompleted}
648
+ onAppStateChanged={onAppStateChanged}
649
+ enableAutoReconnect={enableAutoReconnect}
650
+ skipWebBackgroundDetection={skipWebBackgroundDetection}
651
+ debug={debug}
652
+ >
653
+ {children}
654
+ </TelnyxVoiceApp>
655
+ );
656
+ };
657
+
658
+ /**
659
+ * Handles background push notifications in the background isolate.
660
+ * This should be called from your background message handler.
661
+ */
662
+ const handleBackgroundPush = async (message: any): Promise<void> => {
663
+ console.log('[TelnyxVoiceApp] Background push received:', message);
664
+
665
+ try {
666
+ // TODO: Initialize push notification service in isolate if needed
667
+
668
+ // Use singleton pattern for background client to prevent multiple instances
669
+ let backgroundClient = createBackgroundTelnyxVoipClient({
670
+ debug: true,
671
+ });
672
+
673
+ await backgroundClient.handlePushNotification(message);
674
+
675
+ console.log('[TelnyxVoiceApp] Background push processed successfully');
676
+
677
+ // Clean up the background client
678
+ backgroundClient.dispose();
679
+ } catch (e) {
680
+ console.log('[TelnyxVoiceApp] Error processing background push:', e);
681
+ }
682
+ };
683
+
684
+ // Create the component with static methods
685
+ export const TelnyxVoiceApp: TelnyxVoiceAppComponent = Object.assign(TelnyxVoiceAppComponent, {
686
+ initializeAndCreate,
687
+ handleBackgroundPush,
688
+ });
689
+
690
+ export default TelnyxVoiceApp;