@telnyx/react-voice-commons-sdk 0.1.0 → 0.1.2

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