@tarunzyraclavis/zyra-twilio-wrapper 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,510 @@
1
+ import axios from "axios";
2
+ import { Device, Call } from "@twilio/voice-sdk";
3
+ import { handleAxiosError } from '../utils/errorHandler';
4
+ import {
5
+ AddParticipantPayload,
6
+ CallResponse,
7
+ Config,
8
+ GetConferencePayload,
9
+ GetConferenceResult,
10
+ GetParticipantsPayload,
11
+ GetParticipantsResult,
12
+ HoldAndAddResult,
13
+ HoldCallPayload,
14
+ HoldPayload,
15
+ RemoveParticipantPayload,
16
+ RemoveParticipantResult,
17
+ ResumeCallPayload,
18
+ TokenRequestPayload,
19
+ TokenResponse,
20
+ TwilioConference,
21
+ TwilioConferenceParticipant,
22
+ } from '../types/interface';
23
+ import { createSuccessResult, createErrorResult } from '../utils/helper'
24
+
25
+ export default class ZyraTwilioWrapper {
26
+ private readonly serverUrl: string;
27
+ private readonly identity: string;
28
+ private device: Device | null = null;
29
+ private activeConnection: Call | null = null;
30
+ private isInitialized: boolean = false;
31
+ private isInitializing: boolean = false;
32
+ public activeCallSid: string | null = null;
33
+ public conferenceName: string;
34
+ public conferenceDetail: TwilioConference | null = null;
35
+ public participants: TwilioConferenceParticipant[] = [];
36
+ public waitUrl: string = "https://api.twilio.com/cowbell.mp3";
37
+
38
+ // Optional event handlers
39
+ public onReady?: () => void;
40
+ public onIncoming?: (conn: Call) => void;
41
+ public onDisconnect?: () => void;
42
+ public onError?: (error: Error) => void;
43
+ public onConnect?: (conn: Call) => void;
44
+ public onMissedCall?: () => void;
45
+ public onAnswerOutGoing?: (conn: Call) => void;
46
+
47
+ constructor(configObj: Config) {
48
+ this.serverUrl = configObj.serverUrl;
49
+ this.identity = configObj.identity;
50
+ this.waitUrl = configObj.waitUrl || this.waitUrl;
51
+ this.conferenceName = `conf_${this.identity}`;
52
+ }
53
+
54
+ // /**
55
+ // * Initialize the Twilio device and get token
56
+ // */
57
+ /**
58
+ * Initialize the SDK. Can only be called once.
59
+ *
60
+ * @throws {Error} If already initialized or initialization fails
61
+ * @returns Promise that resolves when initialization is complete
62
+ */
63
+ public async init(): Promise<void> {
64
+ if (this.isInitialized) {
65
+ throw new Error(
66
+ "SDK is already initialized. Call destroy() first to reinitialize."
67
+ );
68
+ }
69
+
70
+ if (this.isInitializing) {
71
+ throw new Error("SDK initialization is already in progress");
72
+ }
73
+
74
+ this.isInitializing = true;
75
+
76
+ try {
77
+ // Validate configuration
78
+ if (!this.serverUrl) {
79
+ throw new Error("serverUrl is required");
80
+ }
81
+ if (!this.identity) {
82
+ throw new Error("identity is required");
83
+ }
84
+
85
+ // Generate token and create Device
86
+ const token = await this.generateToken();
87
+ this.device = new Device(token, { logLevel: 3 });
88
+
89
+ // Setup event handlers
90
+ this.setupDeviceEventHandlers();
91
+
92
+ // Register the device
93
+ await this.device.register();
94
+
95
+ this.isInitialized = true;
96
+ console.info("[init] Device registration completed");
97
+ } catch (error: unknown) {
98
+ handleAxiosError(error, this.onError, "Failed to fetch token");
99
+ throw error;
100
+ } finally {
101
+ // Reset initializing flag even if init fails
102
+ this.isInitializing = false;
103
+ }
104
+ }
105
+
106
+ // Private methods for get token for initialize the device
107
+ private async generateToken(): Promise<string> {
108
+ try {
109
+ const payload: TokenRequestPayload = {
110
+ identity: this.identity,
111
+ ttl: 3600,
112
+ incomingAllow: true,
113
+ };
114
+
115
+ const res = await axios.post<TokenResponse>(`${this.serverUrl}/voipSdk.generateToken`, payload);
116
+
117
+ const token = res.data.result.data.token;
118
+
119
+ if (!token) {
120
+ throw new Error("Token not found in server response");
121
+ }
122
+
123
+ return token;
124
+ } catch (error : unknown) {
125
+ handleAxiosError(error, this.onError, "Failed to generate Twilio token");
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ // Private methods for handling the event for device
131
+ private setupDeviceEventHandlers(): void {
132
+ if (!this.device) return;
133
+
134
+ this.device.on("registered", () => {
135
+ console.info("[Device] Registered");
136
+ this.onReady?.();
137
+ });
138
+
139
+ this.device.on("incoming", (conn: Call) => {
140
+ console.info("[Device] Incoming call detected");
141
+ conn.on("cancel", () => {
142
+ console.warn("[Device] Caller hung up before answer");
143
+ this.activeConnection = null;
144
+ this.onMissedCall?.();
145
+ });
146
+ conn.on("reject", () => {
147
+ console.warn("[Device] Call rejected");
148
+ this.activeConnection = null;
149
+ });
150
+ conn.on("accept", () => console.info("[Device] Call accepted"));
151
+ this.activeConnection = conn;
152
+ this.onIncoming?.(conn);
153
+ });
154
+
155
+ this.device.on("disconnect", () => {
156
+ console.info("[Device] Call disconnected");
157
+ this.activeConnection = null;
158
+ this.onDisconnect?.();
159
+ });
160
+
161
+ this.device.on("connect", (conn: Call) => {
162
+ console.info("[Device] Call connected");
163
+ this.activeConnection = conn;
164
+ this.onConnect?.(conn);
165
+ });
166
+
167
+ this.device.on("error", (error: Error) => {
168
+ handleAxiosError(error, this.onError, "Device encountered an error");
169
+ });
170
+ }
171
+
172
+ /**
173
+ * Check if SDK is initialized
174
+ */
175
+ get initialized(): boolean {
176
+ return this.isInitialized;
177
+ }
178
+
179
+ /**
180
+ * Destroy the SDK instance and clean up resources
181
+ */
182
+ public destroy(): void {
183
+ if (this.device) {
184
+ // Remove all event listeners
185
+ this.device.removeAllListeners();
186
+
187
+ // Optionally, explicitly handle any final error events
188
+ this.device.on("error", (error: Error) => {
189
+ handleAxiosError(error, this.onError, "Device encountered an error during destroy");
190
+ });
191
+
192
+ // When Token expires then get new and update with twilio
193
+ this.device.on('tokenWillExpire', async () => {
194
+ const token = await this.generateToken();
195
+ this.device?.updateToken(token);
196
+ });
197
+ // Shutdown device
198
+ this.device.destroy();
199
+ this.device = null;
200
+ }
201
+
202
+ // Reset state flags
203
+ this.isInitialized = false;
204
+ this.isInitializing = false;
205
+ this.activeConnection = null;
206
+
207
+ console.info("[destroy] Device destroyed and SDK state reset");
208
+ }
209
+
210
+
211
+ /**
212
+ * Make an outgoing call or add participant to an existing call
213
+ */
214
+ public async makeCall(to: string): Promise<CallResponse<Call>> {
215
+ if (!this.device) {
216
+ return createErrorResult("Device not initialized");
217
+ }
218
+
219
+ if (!to) {
220
+ console.warn("[makeCall] 'to' parameter is required");
221
+ return createErrorResult("[makeCall] 'to' parameter is required");
222
+ }
223
+
224
+ if (!this.activeConnection) {
225
+ try {
226
+ const connection = await this.device.connect({
227
+ params: { To: to, conferenceName: this.conferenceName },
228
+ });
229
+
230
+ this.activeConnection = connection;
231
+
232
+ connection.on("accept", async (conn: Call) => {
233
+ this.activeCallSid = connection?.parameters?.CallSid ?? null;
234
+ console.info(`[makeCall] Call accepted. Call SID: ${this.activeCallSid}`);
235
+ this.onAnswerOutGoing?.(conn);
236
+ await this.getConferenceId();
237
+ });
238
+
239
+ connection.on("error", (error: Error) => {
240
+ console.error("[makeCall] Connection error:", error.message);
241
+ this.onError?.(error);
242
+ });
243
+
244
+ connection.on("disconnect", () => {
245
+ console.info("[makeCall] Call disconnected.");
246
+ this.activeConnection = null;
247
+ this.onDisconnect?.();
248
+ });
249
+
250
+ console.info(`[makeCall] Outgoing call initiated to: ${to}`);
251
+ return createSuccessResult(`[makeCall] Outgoing call initiated to: ${to}`, connection);
252
+ } catch (error: unknown) {
253
+ const err = error instanceof Error ? error : new Error(String(error));
254
+ console.error("[makeCall] Failed to initiate call:", err.message);
255
+ this.onError?.(err);
256
+ return createErrorResult(`[makeCall] Failed to initiate call: ${err.message}`);
257
+ }
258
+ } else {
259
+ try {
260
+ console.info("[makeCall] Active call found. Holding and adding new participant...");
261
+ await this.holdAndAddParticipant(this.activeConnection.parameters.CallSid, to);
262
+ return createSuccessResult(`[makeCall] Outgoing participant ${to} added`, this.activeConnection);
263
+ } catch (error: unknown) {
264
+ const err = error instanceof Error ? error : new Error(String(error));
265
+ console.error("[makeCall] Failed to add participant:", err.message);
266
+ this.onError?.(err);
267
+ return createErrorResult(`[makeCall] Failed to add participant: ${err.message}`);
268
+ }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Accept incoming call
274
+ */
275
+ public acceptCall(): CallResponse<Call> {
276
+ if (!this.device || !this.activeConnection) {
277
+ const msg = !this.device
278
+ ? "Device not initialized."
279
+ : "No active call to accept.";
280
+ console.warn(`[acceptCall] ${msg}`);
281
+ return createErrorResult(`[acceptCall] ${msg}`);
282
+ }
283
+
284
+ try {
285
+ this.activeConnection.accept();
286
+ console.info("[acceptCall] Call accepted successfully.");
287
+ return createSuccessResult("Call accepted successfully.", this.activeConnection);
288
+ } catch (error: unknown) {
289
+ const err = error instanceof Error ? error : new Error(String(error));
290
+ console.error("[acceptCall] Failed:", err.message);
291
+ this.onError?.(err);
292
+ return createErrorResult(`[acceptCall] Failed: ${err.message}`);
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Hang up active call
298
+ */
299
+ public hangup(): CallResponse<Call | null> {
300
+ if (!this.device || !this.activeConnection) {
301
+ const msg = !this.device
302
+ ? "Device not initialized."
303
+ : "No active call to hang up.";
304
+ console.warn(`[hangup] ${msg}`);
305
+ return createErrorResult(`[hangup] ${msg}`);
306
+ }
307
+
308
+ try {
309
+ this.device.disconnectAll();
310
+ this.activeConnection = null;
311
+ console.info("[hangup] Call hung up successfully.");
312
+ return createSuccessResult("Call hung up successfully.", this.activeConnection);
313
+ } catch (error: unknown) {
314
+ const err = error instanceof Error ? error : new Error(String(error));
315
+ console.error("[hangup] Failed:", err.message);
316
+ this.onError?.(err);
317
+ return createErrorResult(`Failed to hang up: ${err.message}`);
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Reject incoming call
323
+ */
324
+ public rejectCall(): CallResponse<Call | null> {
325
+ if (!this.device || !this.activeConnection) {
326
+ const msg = !this.device
327
+ ? "Device not initialized."
328
+ : "No active call to reject.";
329
+ console.warn(`[rejectCall] ${msg}`);
330
+ return createErrorResult(`[rejectCall] ${msg}`);
331
+ }
332
+
333
+ try {
334
+ this.activeConnection.reject();
335
+ this.activeConnection = null;
336
+ console.info("[rejectCall] Call rejected successfully.");
337
+ return createSuccessResult("[rejectCall] Call rejected successfully.", this.activeConnection);
338
+ } catch (error: unknown) {
339
+ const err = error instanceof Error ? error : new Error(String(error));
340
+ console.error("[rejectCall] Failed:", err.message);
341
+ this.onError?.(err);
342
+ return createErrorResult(`Failed to reject call: ${err.message}`);
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Toggle mute/unmute
348
+ */
349
+ public toggleMute(mute: boolean): CallResponse<Call> {
350
+ if (!this.activeConnection) {
351
+ console.warn("[toggleMute] No active call to mute/unmute.");
352
+ return createErrorResult("[toggleMute] No active call to mute/unmute.");
353
+ }
354
+
355
+ try {
356
+ this.activeConnection.mute(mute);
357
+ console.info(`[toggleMute] Call ${mute ? "muted" : "unmuted"} successfully.`);
358
+ return createSuccessResult(`Call ${mute ? "muted" : "unmuted"} successfully.`, this.activeConnection);
359
+ } catch (error: unknown) {
360
+ const err = error instanceof Error ? error : new Error(String(error));
361
+ console.error("[toggleMute] Failed:", err.message);
362
+ this.onError?.(err);
363
+ return createErrorResult(`Failed to toggle mute: ${err.message}`);
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Hold a call
369
+ */
370
+ public async hold(callSid: string): Promise<CallResponse<Call>> {
371
+ if (!this.activeConnection) return createErrorResult("No active call to hold.");
372
+ if (!callSid) return createErrorResult("Please provide callSid.");
373
+
374
+ try {
375
+ const payload: HoldCallPayload = { callSid, conferenceName: this.conferenceName, waitUrl: this.waitUrl };
376
+ await axios.post(`${this.serverUrl}/outgoingCall.hold`, payload);
377
+ console.info("[hold] Call held successfully.");
378
+ return createSuccessResult("Call held successfully.", this.activeConnection);
379
+
380
+ } catch (error: unknown) {
381
+ handleAxiosError(error, this.onError, "Failed to hold call");
382
+ const errMessage = error instanceof Error ? error.message : String(error);
383
+ return createErrorResult(`Failed to hold call: ${errMessage}`);
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Resume a held call
389
+ */
390
+ public async resume(callSid: string): Promise<CallResponse<Call>> {
391
+ if (!this.activeConnection) return createErrorResult("No active call to resume.");
392
+ if (!callSid) return createErrorResult("Please provide callSid.");
393
+
394
+ try {
395
+ const payload: ResumeCallPayload = { callSid, conferenceName: this.conferenceName };
396
+ await axios.post(`${this.serverUrl}/outgoingCall.unhold`, payload);
397
+ console.info("[resume] Call resumed successfully.");
398
+ return createSuccessResult("Call resumed successfully.", this.activeConnection);
399
+ } catch (error: unknown) {
400
+ handleAxiosError(error, this.onError, "Failed to resume call");
401
+ const errMessage = error instanceof Error ? error.message : String(error);
402
+ return createErrorResult(`Failed to resume call: ${errMessage}`);
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Hold active call and add a new participant
408
+ */
409
+ public async holdAndAddParticipant(callSid: string, newParticipantNo: string): Promise<HoldAndAddResult | CallResponse> {
410
+ if (!this.activeConnection) return createErrorResult("No active call.");
411
+ if (!callSid) return createErrorResult("Please provide callSid.");
412
+ if (!newParticipantNo) return createErrorResult("Please provide participant number.");
413
+
414
+ try {
415
+ const holdPayload: HoldPayload = { conferenceName: this.conferenceName, callSid, waitUrl: this.waitUrl };
416
+ const holdRes = await axios.post(`${this.serverUrl}/outgoingCall.hold`, holdPayload);
417
+
418
+ const addPayload: AddParticipantPayload = { conferenceName: this.conferenceName, newParticipantNo };
419
+ const addRes = await axios.post(`${this.serverUrl}/outgoingCall.addNewCallee`, addPayload);
420
+
421
+ console.info("[holdAndAddParticipant] Call held and participant added successfully.");
422
+ return {
423
+ message: "Call held and participant added successfully.",
424
+ status: true,
425
+ holdResponse: holdRes.data,
426
+ addParticipantResponse: addRes.data,
427
+ };
428
+ } catch (error: unknown) {
429
+ handleAxiosError(error, this.onError, "Failed to hold and add participant");
430
+ const errMessage = error instanceof Error ? error.message : String(error);
431
+ return createErrorResult(`Failed to hold/add participant: ${errMessage}`);
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Fetch conference details
437
+ */
438
+ public async getConferenceId(): Promise<GetConferenceResult | CallResponse<TwilioConference>> {
439
+ if (!this.activeConnection) return createErrorResult("No active call.");
440
+
441
+ const payload: GetConferencePayload = { conferenceName: this.conferenceName };
442
+
443
+ try {
444
+ const res = await axios.post(`${this.serverUrl}/outgoingCall.getConferenceId`, payload);
445
+
446
+ if (res?.data?.result?.data) {
447
+ const confDetails: TwilioConference = {
448
+ conferenceSid: res.data.result.data.conferenceSid,
449
+ conferences: res.data.result.data.conferences,
450
+ };
451
+ this.conferenceDetail = confDetails;
452
+ console.info("[getConferenceId] Conference details fetched successfully.");
453
+ return createSuccessResult("Call resumed successfully.", confDetails);
454
+ }
455
+
456
+ console.warn("[getConferenceId] No conference data returned from server.");
457
+ return { message: "No conference data returned.", status: false };
458
+ } catch (error: unknown) {
459
+ handleAxiosError(error, this.onError, "Failed to get conference ID");
460
+ const errMessage = error instanceof Error ? error.message : String(error);
461
+ return createErrorResult(`Failed to get conference ID: ${errMessage}`);
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Get participants of a conference
467
+ */
468
+ public async getParticipants(conferenceSid: string): Promise<GetParticipantsResult | CallResponse<TwilioConferenceParticipant[]>> {
469
+ if (!this.activeConnection) return createErrorResult("No active call.");
470
+ if (!conferenceSid) return createErrorResult("Please provide conferenceSid.");
471
+
472
+ try {
473
+ const payload: GetParticipantsPayload = { conferenceSid };
474
+ const res = await axios.post(`${this.serverUrl}/outgoingCall.getParticipants`, payload);
475
+
476
+ if (res?.data?.result?.data?.participants) {
477
+ this.participants = res.data.result.data.participants;
478
+ console.info("[getParticipants] Participants fetched successfully.");
479
+ return createSuccessResult("Participants fetched successfully.", this.participants);
480
+ }
481
+
482
+ console.warn("[getParticipants] No participants returned from server.");
483
+ return { message: "No participants returned.", status: false };
484
+ } catch (error: unknown) {
485
+ handleAxiosError(error, this.onError, "Failed to get participants");
486
+ const errMessage = error instanceof Error ? error.message : String(error);
487
+ return createErrorResult(`Failed to get participants: ${errMessage}`);
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Remove a participant from a conference
493
+ */
494
+ public async removeParticipant(conferenceSid: string, callSid: string): Promise<RemoveParticipantResult | CallResponse> {
495
+ if (!this.activeConnection) return createErrorResult("No active call.");
496
+ if (!callSid) return createErrorResult("Please provide callSid.");
497
+ if (!conferenceSid) return createErrorResult("Please provide conferenceSid.");
498
+
499
+ try {
500
+ const payload: RemoveParticipantPayload = { callSid, conferenceSid };
501
+ const res = await axios.post(`${this.serverUrl}/outgoingCall.removeParticipant`, payload);
502
+ console.info("[removeParticipant] Participant removed successfully.");
503
+ return createSuccessResult("Participant removed successfully.", res.data);
504
+ } catch (error: unknown) {
505
+ handleAxiosError(error, this.onError, "Failed to remove participant");
506
+ const errMessage = error instanceof Error ? error.message : String(error);
507
+ return createErrorResult(`Failed to remove participant: ${errMessage}`);
508
+ }
509
+ }
510
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {"compilerOptions": {
2
+ "target": "ES2020",
3
+ "module": "ESNext",
4
+ "moduleResolution": "Node",
5
+ "declaration": true,
6
+ "declarationMap": true,
7
+ "outDir": "dist",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "resolveJsonModule": true
12
+ },
13
+ "include": ["src"],
14
+ "exclude": ["node_modules", "dist"]
15
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+
4
+ export default defineConfig({
5
+ entry: ["src/index.ts"],
6
+ format: ["cjs", "esm"], // ✅ build both CommonJS and ES modules
7
+ dts: true, // ✅ generate type declarations
8
+ sourcemap: true,
9
+ clean: true,
10
+ outDir: "dist",
11
+ splitting: false, // disable code splitting for CJS compat
12
+ minify: false // optional
13
+ });
14
+
15
+ // import { defineConfig } from "tsup";
16
+
17
+ // export default defineConfig({
18
+ // entry: ["src/ZyraTwilioWrapper.ts"],
19
+ // format: ["esm", "cjs"],
20
+ // dts: true, // generate .d.ts types
21
+ // sourcemap: true,
22
+ // clean: true,
23
+ // minify: false,
24
+ // external: ["@twilio/voice-sdk"],
25
+ // });