@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.TelnyxVoipClient = void 0;
4
4
  exports.createTelnyxVoipClient = createTelnyxVoipClient;
5
5
  exports.createBackgroundTelnyxVoipClient = createBackgroundTelnyxVoipClient;
6
- const connection_state_1 = require("./models/connection-state");
7
- const config_1 = require("./models/config");
8
- const session_manager_1 = require("./internal/session/session-manager");
9
- const call_state_controller_1 = require("./internal/calls/call-state-controller");
6
+ const connection_state_1 = require('./models/connection-state');
7
+ const config_1 = require('./models/config');
8
+ const session_manager_1 = require('./internal/session/session-manager');
9
+ const call_state_controller_1 = require('./internal/calls/call-state-controller');
10
10
  /**
11
11
  * The main public interface for the react-voice-commons module.
12
12
  *
@@ -19,356 +19,417 @@ const call_state_controller_1 = require("./internal/calls/call-state-controller"
19
19
  * into their chosen state management solution naturally.
20
20
  */
21
21
  class TelnyxVoipClient {
22
- /**
23
- * Creates a new TelnyxVoipClient instance.
24
- *
25
- * @param options Configuration options for the client
26
- */
27
- constructor(options = {}) {
28
- this._disposed = false;
29
- this._options = {
30
- enableAppStateManagement: true,
31
- debug: false,
32
- ...options,
33
- };
34
- // Initialize core components
35
- this._sessionManager = new session_manager_1.SessionManager();
36
- this._callStateController = new call_state_controller_1.CallStateController(this._sessionManager);
37
- // Set up callback to initialize call state controller listeners when client is ready
38
- this._sessionManager.setOnClientReady(() => {
39
- console.log('🔧 TelnyxVoipClient: Client ready, initializing call state controller listeners');
40
- this._callStateController.initializeClientListeners();
41
- });
42
- if (this._options.debug) {
43
- console.log('TelnyxVoipClient initialized with options:', this._options);
44
- }
22
+ /**
23
+ * Creates a new TelnyxVoipClient instance.
24
+ *
25
+ * @param options Configuration options for the client
26
+ */
27
+ constructor(options = {}) {
28
+ this._disposed = false;
29
+ this._options = {
30
+ enableAppStateManagement: true,
31
+ debug: false,
32
+ ...options,
33
+ };
34
+ // Initialize core components
35
+ this._sessionManager = new session_manager_1.SessionManager();
36
+ this._callStateController = new call_state_controller_1.CallStateController(
37
+ this._sessionManager
38
+ );
39
+ // Set up callback to initialize call state controller listeners when client is ready
40
+ this._sessionManager.setOnClientReady(() => {
41
+ console.log(
42
+ '🔧 TelnyxVoipClient: Client ready, initializing call state controller listeners'
43
+ );
44
+ this._callStateController.initializeClientListeners();
45
+ });
46
+ if (this._options.debug) {
47
+ console.log('TelnyxVoipClient initialized with options:', this._options);
45
48
  }
46
- // ========== Observable Streams ==========
47
- /**
48
- * Stream of connection state changes.
49
- *
50
- * Emits the current status of the connection to the Telnyx backend.
51
- * Values include connecting, connected, disconnected, and error states.
52
- * Listen to this to show connection indicators in your UI.
53
- */
54
- get connectionState$() {
55
- return this._sessionManager.connectionState$;
49
+ }
50
+ // ========== Observable Streams ==========
51
+ /**
52
+ * Stream of connection state changes.
53
+ *
54
+ * Emits the current status of the connection to the Telnyx backend.
55
+ * Values include connecting, connected, disconnected, and error states.
56
+ * Listen to this to show connection indicators in your UI.
57
+ */
58
+ get connectionState$() {
59
+ return this._sessionManager.connectionState$;
60
+ }
61
+ /**
62
+ * Stream of all current calls.
63
+ *
64
+ * Emits a list of all current Call objects. Use this for applications
65
+ * that need to support multiple simultaneous calls (e.g., call waiting,
66
+ * conference calls).
67
+ */
68
+ get calls$() {
69
+ return this._callStateController.calls$;
70
+ }
71
+ /**
72
+ * Stream of the currently active call.
73
+ *
74
+ * A convenience stream that emits the currently active Call object.
75
+ * It emits null when no call is in progress. Ideal for applications
76
+ * that only handle a single call at a time.
77
+ */
78
+ get activeCall$() {
79
+ return this._callStateController.activeCall$;
80
+ }
81
+ // ========== Synchronous State Access ==========
82
+ /**
83
+ * Current connection state (synchronous access).
84
+ */
85
+ get currentConnectionState() {
86
+ return this._sessionManager.currentState;
87
+ }
88
+ /**
89
+ * Current list of calls (synchronous access).
90
+ */
91
+ get currentCalls() {
92
+ return this._callStateController.currentCalls;
93
+ }
94
+ /**
95
+ * Current active call (synchronous access).
96
+ */
97
+ get currentActiveCall() {
98
+ return this._callStateController.currentActiveCall;
99
+ }
100
+ /**
101
+ * Current session ID (UUID) for this connection.
102
+ */
103
+ get sessionId() {
104
+ return this._sessionManager.sessionId;
105
+ }
106
+ /**
107
+ * Configuration options for this client instance.
108
+ */
109
+ get options() {
110
+ return this._options;
111
+ }
112
+ // ========== Authentication Methods ==========
113
+ /**
114
+ * Connects to the Telnyx platform using credential authentication.
115
+ *
116
+ * @param config The credential configuration containing SIP username and password
117
+ * @returns A Promise that completes when the connection attempt is initiated
118
+ *
119
+ * Listen to connectionState$ to monitor the actual connection status.
120
+ * Credentials are automatically stored for future reconnection.
121
+ */
122
+ async login(config) {
123
+ this._throwIfDisposed();
124
+ const errors = (0, config_1.validateConfig)(config);
125
+ if (errors.length > 0) {
126
+ throw new Error(`Invalid configuration: ${errors.join(', ')}`);
56
127
  }
57
- /**
58
- * Stream of all current calls.
59
- *
60
- * Emits a list of all current Call objects. Use this for applications
61
- * that need to support multiple simultaneous calls (e.g., call waiting,
62
- * conference calls).
63
- */
64
- get calls$() {
65
- return this._callStateController.calls$;
128
+ if (this._options.debug) {
129
+ console.log('TelnyxVoipClient: Logging in with credentials for user:', config.sipUser);
66
130
  }
67
- /**
68
- * Stream of the currently active call.
69
- *
70
- * A convenience stream that emits the currently active Call object.
71
- * It emits null when no call is in progress. Ideal for applications
72
- * that only handle a single call at a time.
73
- */
74
- get activeCall$() {
75
- return this._callStateController.activeCall$;
131
+ // Store credentials for future reconnection
132
+ await this._storeCredentials(config);
133
+ await this._sessionManager.connectWithCredential(config);
134
+ }
135
+ /**
136
+ * Connects to the Telnyx platform using token authentication.
137
+ *
138
+ * @param config The token configuration containing the authentication token
139
+ * @returns A Promise that completes when the connection attempt is initiated
140
+ *
141
+ * Listen to connectionState$ to monitor the actual connection status.
142
+ * Token is automatically stored for future reconnection.
143
+ */
144
+ async loginWithToken(config) {
145
+ this._throwIfDisposed();
146
+ const errors = (0, config_1.validateConfig)(config);
147
+ if (errors.length > 0) {
148
+ throw new Error(`Invalid configuration: ${errors.join(', ')}`);
76
149
  }
77
- // ========== Synchronous State Access ==========
78
- /**
79
- * Current connection state (synchronous access).
80
- */
81
- get currentConnectionState() {
82
- return this._sessionManager.currentState;
150
+ if (this._options.debug) {
151
+ console.log('TelnyxVoipClient: Logging in with token');
83
152
  }
84
- /**
85
- * Current list of calls (synchronous access).
86
- */
87
- get currentCalls() {
88
- return this._callStateController.currentCalls;
153
+ // Store token for future reconnection
154
+ await this._storeToken(config);
155
+ await this._sessionManager.connectWithToken(config);
156
+ }
157
+ /**
158
+ * Disconnects from the Telnyx platform.
159
+ *
160
+ * This method terminates the connection, ends any active calls, and
161
+ * cleans up all related resources.
162
+ */
163
+ async logout() {
164
+ if (this._disposed) {
165
+ return;
89
166
  }
90
- /**
91
- * Current active call (synchronous access).
92
- */
93
- get currentActiveCall() {
94
- return this._callStateController.currentActiveCall;
167
+ if (this._options.debug) {
168
+ console.log('TelnyxVoipClient: Logging out');
95
169
  }
96
- /**
97
- * Current session ID (UUID) for this connection.
98
- */
99
- get sessionId() {
100
- return this._sessionManager.sessionId;
170
+ await this._sessionManager.disconnect();
171
+ }
172
+ /**
173
+ * Attempts to reconnect using previously stored configuration.
174
+ *
175
+ * This method is used for auto-reconnection scenarios where the app
176
+ * comes back to the foreground and needs to restore the connection.
177
+ *
178
+ * @returns Promise<boolean> - true if reconnection was successful, false otherwise
179
+ */
180
+ async loginFromStoredConfig() {
181
+ this._throwIfDisposed();
182
+ if (this._options.debug) {
183
+ console.log('TelnyxVoipClient: Attempting to login from stored config');
101
184
  }
102
- /**
103
- * Configuration options for this client instance.
104
- */
105
- get options() {
106
- return this._options;
107
- }
108
- // ========== Authentication Methods ==========
109
- /**
110
- * Connects to the Telnyx platform using credential authentication.
111
- *
112
- * @param config The credential configuration containing SIP username and password
113
- * @returns A Promise that completes when the connection attempt is initiated
114
- *
115
- * Listen to connectionState$ to monitor the actual connection status.
116
- */
117
- async login(config) {
118
- this._throwIfDisposed();
119
- const errors = (0, config_1.validateConfig)(config);
120
- if (errors.length > 0) {
121
- throw new Error(`Invalid configuration: ${errors.join(', ')}`);
122
- }
185
+ try {
186
+ // Try to retrieve stored credentials and token from AsyncStorage
187
+ const AsyncStorage = require('@react-native-async-storage/async-storage').default;
188
+ const storedUsername = await AsyncStorage.getItem('@telnyx_username');
189
+ const storedPassword = await AsyncStorage.getItem('@telnyx_password');
190
+ const storedCredentialToken = await AsyncStorage.getItem('@credential_token');
191
+ const storedPushToken = await AsyncStorage.getItem('@push_token');
192
+ // Check if we have credential-based authentication data
193
+ if (storedUsername && storedPassword) {
194
+ // Create credential config from stored data
195
+ const { createCredentialConfig } = require('./models/config');
196
+ const config = createCredentialConfig(storedUsername, storedPassword, {
197
+ pushNotificationDeviceToken: storedPushToken,
198
+ });
123
199
  if (this._options.debug) {
124
- console.log('TelnyxVoipClient: Logging in with credentials for user:', config.sipUser);
200
+ console.log(
201
+ 'TelnyxVoipClient: Reconnecting with stored credentials for user:',
202
+ storedUsername
203
+ );
125
204
  }
126
205
  await this._sessionManager.connectWithCredential(config);
127
- }
128
- /**
129
- * Connects to the Telnyx platform using token authentication.
130
- *
131
- * @param config The token configuration containing the authentication token
132
- * @returns A Promise that completes when the connection attempt is initiated
133
- *
134
- * Listen to connectionState$ to monitor the actual connection status.
135
- */
136
- async loginWithToken(config) {
137
- this._throwIfDisposed();
138
- const errors = (0, config_1.validateConfig)(config);
139
- if (errors.length > 0) {
140
- throw new Error(`Invalid configuration: ${errors.join(', ')}`);
141
- }
206
+ return true;
207
+ }
208
+ // Check if we have token-based authentication data
209
+ if (storedCredentialToken) {
210
+ // Create token config from stored data
211
+ const { createTokenConfig } = require('./models/config');
212
+ const config = createTokenConfig(storedCredentialToken, {
213
+ pushNotificationDeviceToken: storedPushToken,
214
+ });
142
215
  if (this._options.debug) {
143
- console.log('TelnyxVoipClient: Logging in with token');
216
+ console.log('TelnyxVoipClient: Reconnecting with stored token');
144
217
  }
145
218
  await this._sessionManager.connectWithToken(config);
219
+ return true;
220
+ }
221
+ // No stored authentication data found
222
+ if (this._options.debug) {
223
+ console.log('TelnyxVoipClient: No stored credentials or token found');
224
+ }
225
+ return false;
226
+ } catch (error) {
227
+ if (this._options.debug) {
228
+ console.log('TelnyxVoipClient: Failed to login from stored config:', error);
229
+ }
230
+ return false;
146
231
  }
147
- /**
148
- * Disconnects from the Telnyx platform.
149
- *
150
- * This method terminates the connection, ends any active calls, and
151
- * cleans up all related resources.
152
- */
153
- async logout() {
154
- if (this._disposed) {
155
- return;
156
- }
157
- if (this._options.debug) {
158
- console.log('TelnyxVoipClient: Logging out');
159
- }
160
- await this._sessionManager.disconnect();
232
+ }
233
+ // ========== Call Management Methods ==========
234
+ /**
235
+ * Initiates a new outgoing call.
236
+ *
237
+ * @param destination The destination number or SIP URI to call
238
+ * @param debug Optional flag to enable call quality metrics for this call
239
+ * @returns A Promise that completes with the Call object once the invitation has been sent
240
+ *
241
+ * The call's state can be monitored through the returned Call object's streams.
242
+ */
243
+ async newCall(destination, debug = false) {
244
+ this._throwIfDisposed();
245
+ if (!destination || destination.trim() === '') {
246
+ throw new Error('Destination is required');
161
247
  }
162
- /**
163
- * Attempts to reconnect using previously stored configuration.
164
- *
165
- * This method is used for auto-reconnection scenarios where the app
166
- * comes back to the foreground and needs to restore the connection.
167
- *
168
- * @returns Promise<boolean> - true if reconnection was successful, false otherwise
169
- */
170
- async loginFromStoredConfig() {
171
- this._throwIfDisposed();
172
- if (this._options.debug) {
173
- console.log('TelnyxVoipClient: Attempting to login from stored config');
174
- }
175
- try {
176
- // Try to retrieve stored credentials and token from AsyncStorage
177
- const AsyncStorage = require('@react-native-async-storage/async-storage').default;
178
- const storedUsername = await AsyncStorage.getItem('@telnyx_username');
179
- const storedPassword = await AsyncStorage.getItem('@telnyx_password');
180
- const storedCredentialToken = await AsyncStorage.getItem('@credential_token');
181
- const storedPushToken = await AsyncStorage.getItem('@push_token');
182
- // Check if we have credential-based authentication data
183
- if (storedUsername && storedPassword) {
184
- // Create credential config from stored data
185
- const { createCredentialConfig } = require('./models/config');
186
- const config = createCredentialConfig(storedUsername, storedPassword, {
187
- pushNotificationDeviceToken: storedPushToken,
188
- });
189
- if (this._options.debug) {
190
- console.log('TelnyxVoipClient: Reconnecting with stored credentials for user:', storedUsername);
191
- }
192
- await this._sessionManager.connectWithCredential(config);
193
- return true;
194
- }
195
- // Check if we have token-based authentication data
196
- if (storedCredentialToken) {
197
- // Create token config from stored data
198
- const { createTokenConfig } = require('./models/config');
199
- const config = createTokenConfig(storedCredentialToken, {
200
- pushNotificationDeviceToken: storedPushToken,
201
- });
202
- if (this._options.debug) {
203
- console.log('TelnyxVoipClient: Reconnecting with stored token');
204
- }
205
- await this._sessionManager.connectWithToken(config);
206
- return true;
207
- }
208
- // No stored authentication data found
209
- if (this._options.debug) {
210
- console.log('TelnyxVoipClient: No stored credentials or token found');
211
- }
212
- return false;
213
- }
214
- catch (error) {
215
- if (this._options.debug) {
216
- console.log('TelnyxVoipClient: Failed to login from stored config:', error);
217
- }
218
- return false;
219
- }
248
+ if (this.currentConnectionState !== connection_state_1.TelnyxConnectionState.CONNECTED) {
249
+ throw new Error(`Cannot make call when connection state is: ${this.currentConnectionState}`);
220
250
  }
221
- // ========== Call Management Methods ==========
222
- /**
223
- * Initiates a new outgoing call.
224
- *
225
- * @param destination The destination number or SIP URI to call
226
- * @param debug Optional flag to enable call quality metrics for this call
227
- * @returns A Promise that completes with the Call object once the invitation has been sent
228
- *
229
- * The call's state can be monitored through the returned Call object's streams.
230
- */
231
- async newCall(destination, debug = false) {
232
- this._throwIfDisposed();
233
- if (!destination || destination.trim() === '') {
234
- throw new Error('Destination is required');
235
- }
236
- if (this.currentConnectionState !== connection_state_1.TelnyxConnectionState.CONNECTED) {
237
- throw new Error(`Cannot make call when connection state is: ${this.currentConnectionState}`);
238
- }
239
- if (this._options.debug) {
240
- console.log('TelnyxVoipClient: Creating new call to:', destination);
241
- }
242
- return await this._callStateController.newCall(destination, undefined, undefined, debug);
251
+ if (this._options.debug) {
252
+ console.log('TelnyxVoipClient: Creating new call to:', destination);
243
253
  }
244
- // ========== Push Notification Methods ==========
245
- /**
246
- * Handle push notification payload.
247
- *
248
- * This is the unified entry point for all push notifications. It intelligently
249
- * determines whether to show a new incoming call UI or to process an already
250
- * actioned (accepted/declined) call upon app launch.
251
- *
252
- * @param payload The push notification payload
253
- */
254
- async handlePushNotification(payload) {
255
- this._throwIfDisposed();
256
- if (this._options.debug) {
257
- console.log('TelnyxVoipClient: Handling push notification:', payload);
258
- }
259
- try {
260
- // First, pass the push notification to the session manager for processing
261
- // This will set the isCallFromPush flag on the TelnyxRTC client
262
- await this._sessionManager.handlePushNotification(payload);
263
- // Connect if not already connected
264
- const currentState = this.currentConnectionState;
265
- if (currentState !== connection_state_1.TelnyxConnectionState.CONNECTED) {
266
- // Try to login from stored config - now the push flags should be set
267
- const loginSuccess = await this.loginFromStoredConfig();
268
- if (!loginSuccess) {
269
- console.warn('TelnyxVoipClient: Could not login from stored config for push notification');
270
- return;
271
- }
272
- }
273
- }
274
- catch (error) {
275
- console.error('TelnyxVoipClient: Error handling push notification:', error);
276
- throw error;
277
- }
254
+ return await this._callStateController.newCall(destination, undefined, undefined, debug);
255
+ }
256
+ // ========== Push Notification Methods ==========
257
+ /**
258
+ * Handle push notification payload.
259
+ *
260
+ * This is the unified entry point for all push notifications. It intelligently
261
+ * determines whether to show a new incoming call UI or to process an already
262
+ * actioned (accepted/declined) call upon app launch.
263
+ *
264
+ * @param payload The push notification payload
265
+ */
266
+ async handlePushNotification(payload) {
267
+ this._throwIfDisposed();
268
+ if (this._options.debug) {
269
+ console.log('TelnyxVoipClient: Handling push notification:', payload);
278
270
  }
279
- /**
280
- * Disables push notifications for the current session.
281
- *
282
- * This method sends a request to the Telnyx backend to disable push
283
- * notifications for the current registered device/session.
284
- */
285
- disablePushNotifications() {
286
- this._throwIfDisposed();
287
- if (this._options.debug) {
288
- console.log('TelnyxVoipClient: Disabling push notifications');
271
+ try {
272
+ // First, pass the push notification to the session manager for processing
273
+ // This will set the isCallFromPush flag on the TelnyxRTC client
274
+ await this._sessionManager.handlePushNotification(payload);
275
+ // Connect if not already connected
276
+ const currentState = this.currentConnectionState;
277
+ if (currentState !== connection_state_1.TelnyxConnectionState.CONNECTED) {
278
+ // Try to login from stored config - now the push flags should be set
279
+ const loginSuccess = await this.loginFromStoredConfig();
280
+ if (!loginSuccess) {
281
+ console.warn(
282
+ 'TelnyxVoipClient: Could not login from stored config for push notification'
283
+ );
284
+ return;
289
285
  }
290
- this._sessionManager.disablePushNotifications();
286
+ }
287
+ } catch (error) {
288
+ console.error('TelnyxVoipClient: Error handling push notification:', error);
289
+ throw error;
291
290
  }
292
- // ========== CallKit Integration Methods ==========
293
- /**
294
- * Set a call to connecting state (used for push notification calls when answered via CallKit)
295
- * @param callId The ID of the call to set to connecting state
296
- * @internal
297
- */
298
- setCallConnecting(callId) {
299
- this._callStateController.setCallConnecting(callId);
291
+ }
292
+ /**
293
+ * Disables push notifications for the current session.
294
+ *
295
+ * This method sends a request to the Telnyx backend to disable push
296
+ * notifications for the current registered device/session.
297
+ */
298
+ disablePushNotifications() {
299
+ this._throwIfDisposed();
300
+ if (this._options.debug) {
301
+ console.log('TelnyxVoipClient: Disabling push notifications');
300
302
  }
301
- /**
302
- * Find a call by its underlying Telnyx call object
303
- * @param telnyxCall The Telnyx call object to find
304
- * @internal
305
- */
306
- findCallByTelnyxCall(telnyxCall) {
307
- return this._callStateController.findCallByTelnyxCall(telnyxCall);
303
+ this._sessionManager.disablePushNotifications();
304
+ }
305
+ // ========== CallKit Integration Methods ==========
306
+ /**
307
+ * Set a call to connecting state (used for push notification calls when answered via CallKit)
308
+ * @param callId The ID of the call to set to connecting state
309
+ * @internal
310
+ */
311
+ setCallConnecting(callId) {
312
+ this._callStateController.setCallConnecting(callId);
313
+ }
314
+ /**
315
+ * Find a call by its underlying Telnyx call object
316
+ * @param telnyxCall The Telnyx call object to find
317
+ * @internal
318
+ */
319
+ findCallByTelnyxCall(telnyxCall) {
320
+ return this._callStateController.findCallByTelnyxCall(telnyxCall);
321
+ }
322
+ /**
323
+ * Queue an answer action for when the call invite arrives (for CallKit integration)
324
+ * This should be called when the user answers from CallKit before the socket connection is established
325
+ * @param customHeaders Optional custom headers to include with the answer
326
+ */
327
+ queueAnswerFromCallKit(customHeaders = {}) {
328
+ this._throwIfDisposed();
329
+ if (this._options.debug) {
330
+ console.log('TelnyxVoipClient: Queuing answer action from CallKit', customHeaders);
308
331
  }
309
- /**
310
- * Queue an answer action for when the call invite arrives (for CallKit integration)
311
- * This should be called when the user answers from CallKit before the socket connection is established
312
- * @param customHeaders Optional custom headers to include with the answer
313
- */
314
- queueAnswerFromCallKit(customHeaders = {}) {
315
- this._throwIfDisposed();
316
- if (this._options.debug) {
317
- console.log('TelnyxVoipClient: Queuing answer action from CallKit', customHeaders);
318
- }
319
- const telnyxClient = this._sessionManager.telnyxClient;
320
- if (telnyxClient && typeof telnyxClient.queueAnswerFromCallKit === 'function') {
321
- telnyxClient.queueAnswerFromCallKit(customHeaders);
322
- }
323
- else {
324
- console.warn('TelnyxVoipClient: TelnyxRTC client not available or method not found for queueAnswerFromCallKit');
325
- }
332
+ const telnyxClient = this._sessionManager.telnyxClient;
333
+ if (telnyxClient && typeof telnyxClient.queueAnswerFromCallKit === 'function') {
334
+ telnyxClient.queueAnswerFromCallKit(customHeaders);
335
+ } else {
336
+ console.warn(
337
+ 'TelnyxVoipClient: TelnyxRTC client not available or method not found for queueAnswerFromCallKit'
338
+ );
326
339
  }
327
- /**
328
- * Queue an end action for when the call invite arrives (for CallKit integration)
329
- * This should be called when the user ends from CallKit before the socket connection is established
330
- */
331
- queueEndFromCallKit() {
332
- this._throwIfDisposed();
333
- if (this._options.debug) {
334
- console.log('TelnyxVoipClient: Queuing end action from CallKit');
335
- }
336
- const telnyxClient = this._sessionManager.telnyxClient;
337
- if (telnyxClient && typeof telnyxClient.queueEndFromCallKit === 'function') {
338
- telnyxClient.queueEndFromCallKit();
339
- }
340
- else {
341
- console.warn('TelnyxVoipClient: TelnyxRTC client not available or method not found for queueEndFromCallKit');
342
- }
340
+ }
341
+ /**
342
+ * Queue an end action for when the call invite arrives (for CallKit integration)
343
+ * This should be called when the user ends from CallKit before the socket connection is established
344
+ */
345
+ queueEndFromCallKit() {
346
+ this._throwIfDisposed();
347
+ if (this._options.debug) {
348
+ console.log('TelnyxVoipClient: Queuing end action from CallKit');
343
349
  }
344
- // ========== Lifecycle Methods ==========
345
- /**
346
- * Dispose of the client and clean up all resources.
347
- *
348
- * After calling this method, the client instance should not be used anymore.
349
- * This is particularly important for background clients that should be
350
- * disposed after handling push notifications.
351
- */
352
- dispose() {
353
- if (this._disposed) {
354
- return;
355
- }
356
- if (this._options.debug) {
357
- console.log('TelnyxVoipClient: Disposing client');
358
- }
359
- this._disposed = true;
360
- this._callStateController.dispose();
361
- this._sessionManager.dispose();
350
+ const telnyxClient = this._sessionManager.telnyxClient;
351
+ if (telnyxClient && typeof telnyxClient.queueEndFromCallKit === 'function') {
352
+ telnyxClient.queueEndFromCallKit();
353
+ } else {
354
+ console.warn(
355
+ 'TelnyxVoipClient: TelnyxRTC client not available or method not found for queueEndFromCallKit'
356
+ );
362
357
  }
363
- // ========== Private Methods ==========
364
- /**
365
- * Throw an error if the client has been disposed
366
- */
367
- _throwIfDisposed() {
368
- if (this._disposed) {
369
- throw new Error('TelnyxVoipClient has been disposed');
370
- }
358
+ }
359
+ // ========== Lifecycle Methods ==========
360
+ /**
361
+ * Dispose of the client and clean up all resources.
362
+ *
363
+ * After calling this method, the client instance should not be used anymore.
364
+ * This is particularly important for background clients that should be
365
+ * disposed after handling push notifications.
366
+ */
367
+ dispose() {
368
+ if (this._disposed) {
369
+ return;
370
+ }
371
+ if (this._options.debug) {
372
+ console.log('TelnyxVoipClient: Disposing client');
373
+ }
374
+ this._disposed = true;
375
+ this._callStateController.dispose();
376
+ this._sessionManager.dispose();
377
+ }
378
+ // ========== Private Methods ==========
379
+ /**
380
+ * Store credential configuration for automatic reconnection
381
+ */
382
+ async _storeCredentials(config) {
383
+ try {
384
+ const AsyncStorage = require('@react-native-async-storage/async-storage').default;
385
+ await AsyncStorage.setItem('@telnyx_username', config.sipUser);
386
+ await AsyncStorage.setItem('@telnyx_password', config.sipPassword);
387
+ if (config.pushNotificationDeviceToken) {
388
+ await AsyncStorage.setItem('@push_token', config.pushNotificationDeviceToken);
389
+ }
390
+ // Clear any existing token since we're using credentials
391
+ await AsyncStorage.removeItem('@credential_token');
392
+ if (this._options.debug) {
393
+ console.log('TelnyxVoipClient: Stored credentials for user:', config.sipUser);
394
+ }
395
+ } catch (error) {
396
+ if (this._options.debug) {
397
+ console.log('TelnyxVoipClient: Failed to store credentials:', error);
398
+ }
399
+ // Don't throw here - storage failure shouldn't prevent login
400
+ }
401
+ }
402
+ /**
403
+ * Store token configuration for automatic reconnection
404
+ */
405
+ async _storeToken(config) {
406
+ try {
407
+ const AsyncStorage = require('@react-native-async-storage/async-storage').default;
408
+ await AsyncStorage.setItem('@credential_token', config.token);
409
+ if (config.pushNotificationDeviceToken) {
410
+ await AsyncStorage.setItem('@push_token', config.pushNotificationDeviceToken);
411
+ }
412
+ // Clear any existing credentials since we're using token
413
+ await AsyncStorage.removeItem('@telnyx_username');
414
+ await AsyncStorage.removeItem('@telnyx_password');
415
+ if (this._options.debug) {
416
+ console.log('TelnyxVoipClient: Stored authentication token');
417
+ }
418
+ } catch (error) {
419
+ if (this._options.debug) {
420
+ console.log('TelnyxVoipClient: Failed to store token:', error);
421
+ }
422
+ // Don't throw here - storage failure shouldn't prevent login
423
+ }
424
+ }
425
+ /**
426
+ * Throw an error if the client has been disposed
427
+ */
428
+ _throwIfDisposed() {
429
+ if (this._disposed) {
430
+ throw new Error('TelnyxVoipClient has been disposed');
371
431
  }
432
+ }
372
433
  }
373
434
  exports.TelnyxVoipClient = TelnyxVoipClient;
374
435
  // ========== Factory Functions ==========
@@ -376,11 +437,11 @@ exports.TelnyxVoipClient = TelnyxVoipClient;
376
437
  * Create a new TelnyxVoipClient instance for normal app usage
377
438
  */
378
439
  function createTelnyxVoipClient(options) {
379
- return new TelnyxVoipClient(options);
440
+ return new TelnyxVoipClient(options);
380
441
  }
381
442
  /**
382
443
  * Create a new TelnyxVoipClient instance for background push notification handling
383
444
  */
384
445
  function createBackgroundTelnyxVoipClient(options) {
385
- return new TelnyxVoipClient(options);
446
+ return new TelnyxVoipClient(options);
386
447
  }