@ipcom/asterisk-ari 0.0.6 → 0.0.8

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.
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +30,552 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
33
+ // node_modules/exponential-backoff/dist/options.js
34
+ var require_options = __commonJS({
35
+ "node_modules/exponential-backoff/dist/options.js"(exports2) {
36
+ "use strict";
37
+ var __assign = exports2 && exports2.__assign || function() {
38
+ __assign = Object.assign || function(t) {
39
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
40
+ s = arguments[i];
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
42
+ t[p] = s[p];
43
+ }
44
+ return t;
45
+ };
46
+ return __assign.apply(this, arguments);
47
+ };
48
+ Object.defineProperty(exports2, "__esModule", { value: true });
49
+ var defaultOptions = {
50
+ delayFirstAttempt: false,
51
+ jitter: "none",
52
+ maxDelay: Infinity,
53
+ numOfAttempts: 10,
54
+ retry: function() {
55
+ return true;
56
+ },
57
+ startingDelay: 100,
58
+ timeMultiple: 2
59
+ };
60
+ function getSanitizedOptions(options) {
61
+ var sanitized = __assign(__assign({}, defaultOptions), options);
62
+ if (sanitized.numOfAttempts < 1) {
63
+ sanitized.numOfAttempts = 1;
64
+ }
65
+ return sanitized;
66
+ }
67
+ exports2.getSanitizedOptions = getSanitizedOptions;
68
+ }
69
+ });
70
+
71
+ // node_modules/exponential-backoff/dist/jitter/full/full.jitter.js
72
+ var require_full_jitter = __commonJS({
73
+ "node_modules/exponential-backoff/dist/jitter/full/full.jitter.js"(exports2) {
74
+ "use strict";
75
+ Object.defineProperty(exports2, "__esModule", { value: true });
76
+ function fullJitter(delay) {
77
+ var jitteredDelay = Math.random() * delay;
78
+ return Math.round(jitteredDelay);
79
+ }
80
+ exports2.fullJitter = fullJitter;
81
+ }
82
+ });
83
+
84
+ // node_modules/exponential-backoff/dist/jitter/no/no.jitter.js
85
+ var require_no_jitter = __commonJS({
86
+ "node_modules/exponential-backoff/dist/jitter/no/no.jitter.js"(exports2) {
87
+ "use strict";
88
+ Object.defineProperty(exports2, "__esModule", { value: true });
89
+ function noJitter(delay) {
90
+ return delay;
91
+ }
92
+ exports2.noJitter = noJitter;
93
+ }
94
+ });
95
+
96
+ // node_modules/exponential-backoff/dist/jitter/jitter.factory.js
97
+ var require_jitter_factory = __commonJS({
98
+ "node_modules/exponential-backoff/dist/jitter/jitter.factory.js"(exports2) {
99
+ "use strict";
100
+ Object.defineProperty(exports2, "__esModule", { value: true });
101
+ var full_jitter_1 = require_full_jitter();
102
+ var no_jitter_1 = require_no_jitter();
103
+ function JitterFactory(options) {
104
+ switch (options.jitter) {
105
+ case "full":
106
+ return full_jitter_1.fullJitter;
107
+ case "none":
108
+ default:
109
+ return no_jitter_1.noJitter;
110
+ }
111
+ }
112
+ exports2.JitterFactory = JitterFactory;
113
+ }
114
+ });
115
+
116
+ // node_modules/exponential-backoff/dist/delay/delay.base.js
117
+ var require_delay_base = __commonJS({
118
+ "node_modules/exponential-backoff/dist/delay/delay.base.js"(exports2) {
119
+ "use strict";
120
+ Object.defineProperty(exports2, "__esModule", { value: true });
121
+ var jitter_factory_1 = require_jitter_factory();
122
+ var Delay = (
123
+ /** @class */
124
+ function() {
125
+ function Delay2(options) {
126
+ this.options = options;
127
+ this.attempt = 0;
128
+ }
129
+ Delay2.prototype.apply = function() {
130
+ var _this = this;
131
+ return new Promise(function(resolve) {
132
+ return setTimeout(resolve, _this.jitteredDelay);
133
+ });
134
+ };
135
+ Delay2.prototype.setAttemptNumber = function(attempt) {
136
+ this.attempt = attempt;
137
+ };
138
+ Object.defineProperty(Delay2.prototype, "jitteredDelay", {
139
+ get: function() {
140
+ var jitter = jitter_factory_1.JitterFactory(this.options);
141
+ return jitter(this.delay);
142
+ },
143
+ enumerable: true,
144
+ configurable: true
145
+ });
146
+ Object.defineProperty(Delay2.prototype, "delay", {
147
+ get: function() {
148
+ var constant = this.options.startingDelay;
149
+ var base = this.options.timeMultiple;
150
+ var power = this.numOfDelayedAttempts;
151
+ var delay = constant * Math.pow(base, power);
152
+ return Math.min(delay, this.options.maxDelay);
153
+ },
154
+ enumerable: true,
155
+ configurable: true
156
+ });
157
+ Object.defineProperty(Delay2.prototype, "numOfDelayedAttempts", {
158
+ get: function() {
159
+ return this.attempt;
160
+ },
161
+ enumerable: true,
162
+ configurable: true
163
+ });
164
+ return Delay2;
165
+ }()
166
+ );
167
+ exports2.Delay = Delay;
168
+ }
169
+ });
170
+
171
+ // node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js
172
+ var require_skip_first_delay = __commonJS({
173
+ "node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js"(exports2) {
174
+ "use strict";
175
+ var __extends = exports2 && exports2.__extends || /* @__PURE__ */ function() {
176
+ var extendStatics = function(d, b) {
177
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
178
+ d2.__proto__ = b2;
179
+ } || function(d2, b2) {
180
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
181
+ };
182
+ return extendStatics(d, b);
183
+ };
184
+ return function(d, b) {
185
+ extendStatics(d, b);
186
+ function __() {
187
+ this.constructor = d;
188
+ }
189
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
190
+ };
191
+ }();
192
+ var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
193
+ function adopt(value) {
194
+ return value instanceof P ? value : new P(function(resolve) {
195
+ resolve(value);
196
+ });
197
+ }
198
+ return new (P || (P = Promise))(function(resolve, reject) {
199
+ function fulfilled(value) {
200
+ try {
201
+ step(generator.next(value));
202
+ } catch (e) {
203
+ reject(e);
204
+ }
205
+ }
206
+ function rejected(value) {
207
+ try {
208
+ step(generator["throw"](value));
209
+ } catch (e) {
210
+ reject(e);
211
+ }
212
+ }
213
+ function step(result) {
214
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
215
+ }
216
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
217
+ });
218
+ };
219
+ var __generator = exports2 && exports2.__generator || function(thisArg, body) {
220
+ var _ = { label: 0, sent: function() {
221
+ if (t[0] & 1) throw t[1];
222
+ return t[1];
223
+ }, trys: [], ops: [] }, f, y, t, g;
224
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
225
+ return this;
226
+ }), g;
227
+ function verb(n) {
228
+ return function(v) {
229
+ return step([n, v]);
230
+ };
231
+ }
232
+ function step(op) {
233
+ if (f) throw new TypeError("Generator is already executing.");
234
+ while (_) try {
235
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
236
+ if (y = 0, t) op = [op[0] & 2, t.value];
237
+ switch (op[0]) {
238
+ case 0:
239
+ case 1:
240
+ t = op;
241
+ break;
242
+ case 4:
243
+ _.label++;
244
+ return { value: op[1], done: false };
245
+ case 5:
246
+ _.label++;
247
+ y = op[1];
248
+ op = [0];
249
+ continue;
250
+ case 7:
251
+ op = _.ops.pop();
252
+ _.trys.pop();
253
+ continue;
254
+ default:
255
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
256
+ _ = 0;
257
+ continue;
258
+ }
259
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
260
+ _.label = op[1];
261
+ break;
262
+ }
263
+ if (op[0] === 6 && _.label < t[1]) {
264
+ _.label = t[1];
265
+ t = op;
266
+ break;
267
+ }
268
+ if (t && _.label < t[2]) {
269
+ _.label = t[2];
270
+ _.ops.push(op);
271
+ break;
272
+ }
273
+ if (t[2]) _.ops.pop();
274
+ _.trys.pop();
275
+ continue;
276
+ }
277
+ op = body.call(thisArg, _);
278
+ } catch (e) {
279
+ op = [6, e];
280
+ y = 0;
281
+ } finally {
282
+ f = t = 0;
283
+ }
284
+ if (op[0] & 5) throw op[1];
285
+ return { value: op[0] ? op[1] : void 0, done: true };
286
+ }
287
+ };
288
+ Object.defineProperty(exports2, "__esModule", { value: true });
289
+ var delay_base_1 = require_delay_base();
290
+ var SkipFirstDelay = (
291
+ /** @class */
292
+ function(_super) {
293
+ __extends(SkipFirstDelay2, _super);
294
+ function SkipFirstDelay2() {
295
+ return _super !== null && _super.apply(this, arguments) || this;
296
+ }
297
+ SkipFirstDelay2.prototype.apply = function() {
298
+ return __awaiter(this, void 0, void 0, function() {
299
+ return __generator(this, function(_a) {
300
+ return [2, this.isFirstAttempt ? true : _super.prototype.apply.call(this)];
301
+ });
302
+ });
303
+ };
304
+ Object.defineProperty(SkipFirstDelay2.prototype, "isFirstAttempt", {
305
+ get: function() {
306
+ return this.attempt === 0;
307
+ },
308
+ enumerable: true,
309
+ configurable: true
310
+ });
311
+ Object.defineProperty(SkipFirstDelay2.prototype, "numOfDelayedAttempts", {
312
+ get: function() {
313
+ return this.attempt - 1;
314
+ },
315
+ enumerable: true,
316
+ configurable: true
317
+ });
318
+ return SkipFirstDelay2;
319
+ }(delay_base_1.Delay)
320
+ );
321
+ exports2.SkipFirstDelay = SkipFirstDelay;
322
+ }
323
+ });
324
+
325
+ // node_modules/exponential-backoff/dist/delay/always/always.delay.js
326
+ var require_always_delay = __commonJS({
327
+ "node_modules/exponential-backoff/dist/delay/always/always.delay.js"(exports2) {
328
+ "use strict";
329
+ var __extends = exports2 && exports2.__extends || /* @__PURE__ */ function() {
330
+ var extendStatics = function(d, b) {
331
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
332
+ d2.__proto__ = b2;
333
+ } || function(d2, b2) {
334
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
335
+ };
336
+ return extendStatics(d, b);
337
+ };
338
+ return function(d, b) {
339
+ extendStatics(d, b);
340
+ function __() {
341
+ this.constructor = d;
342
+ }
343
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
344
+ };
345
+ }();
346
+ Object.defineProperty(exports2, "__esModule", { value: true });
347
+ var delay_base_1 = require_delay_base();
348
+ var AlwaysDelay = (
349
+ /** @class */
350
+ function(_super) {
351
+ __extends(AlwaysDelay2, _super);
352
+ function AlwaysDelay2() {
353
+ return _super !== null && _super.apply(this, arguments) || this;
354
+ }
355
+ return AlwaysDelay2;
356
+ }(delay_base_1.Delay)
357
+ );
358
+ exports2.AlwaysDelay = AlwaysDelay;
359
+ }
360
+ });
361
+
362
+ // node_modules/exponential-backoff/dist/delay/delay.factory.js
363
+ var require_delay_factory = __commonJS({
364
+ "node_modules/exponential-backoff/dist/delay/delay.factory.js"(exports2) {
365
+ "use strict";
366
+ Object.defineProperty(exports2, "__esModule", { value: true });
367
+ var skip_first_delay_1 = require_skip_first_delay();
368
+ var always_delay_1 = require_always_delay();
369
+ function DelayFactory(options, attempt) {
370
+ var delay = initDelayClass(options);
371
+ delay.setAttemptNumber(attempt);
372
+ return delay;
373
+ }
374
+ exports2.DelayFactory = DelayFactory;
375
+ function initDelayClass(options) {
376
+ if (!options.delayFirstAttempt) {
377
+ return new skip_first_delay_1.SkipFirstDelay(options);
378
+ }
379
+ return new always_delay_1.AlwaysDelay(options);
380
+ }
381
+ }
382
+ });
383
+
384
+ // node_modules/exponential-backoff/dist/backoff.js
385
+ var require_backoff = __commonJS({
386
+ "node_modules/exponential-backoff/dist/backoff.js"(exports2) {
387
+ "use strict";
388
+ var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
389
+ function adopt(value) {
390
+ return value instanceof P ? value : new P(function(resolve) {
391
+ resolve(value);
392
+ });
393
+ }
394
+ return new (P || (P = Promise))(function(resolve, reject) {
395
+ function fulfilled(value) {
396
+ try {
397
+ step(generator.next(value));
398
+ } catch (e) {
399
+ reject(e);
400
+ }
401
+ }
402
+ function rejected(value) {
403
+ try {
404
+ step(generator["throw"](value));
405
+ } catch (e) {
406
+ reject(e);
407
+ }
408
+ }
409
+ function step(result) {
410
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
411
+ }
412
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
413
+ });
414
+ };
415
+ var __generator = exports2 && exports2.__generator || function(thisArg, body) {
416
+ var _ = { label: 0, sent: function() {
417
+ if (t[0] & 1) throw t[1];
418
+ return t[1];
419
+ }, trys: [], ops: [] }, f, y, t, g;
420
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
421
+ return this;
422
+ }), g;
423
+ function verb(n) {
424
+ return function(v) {
425
+ return step([n, v]);
426
+ };
427
+ }
428
+ function step(op) {
429
+ if (f) throw new TypeError("Generator is already executing.");
430
+ while (_) try {
431
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
432
+ if (y = 0, t) op = [op[0] & 2, t.value];
433
+ switch (op[0]) {
434
+ case 0:
435
+ case 1:
436
+ t = op;
437
+ break;
438
+ case 4:
439
+ _.label++;
440
+ return { value: op[1], done: false };
441
+ case 5:
442
+ _.label++;
443
+ y = op[1];
444
+ op = [0];
445
+ continue;
446
+ case 7:
447
+ op = _.ops.pop();
448
+ _.trys.pop();
449
+ continue;
450
+ default:
451
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
452
+ _ = 0;
453
+ continue;
454
+ }
455
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
456
+ _.label = op[1];
457
+ break;
458
+ }
459
+ if (op[0] === 6 && _.label < t[1]) {
460
+ _.label = t[1];
461
+ t = op;
462
+ break;
463
+ }
464
+ if (t && _.label < t[2]) {
465
+ _.label = t[2];
466
+ _.ops.push(op);
467
+ break;
468
+ }
469
+ if (t[2]) _.ops.pop();
470
+ _.trys.pop();
471
+ continue;
472
+ }
473
+ op = body.call(thisArg, _);
474
+ } catch (e) {
475
+ op = [6, e];
476
+ y = 0;
477
+ } finally {
478
+ f = t = 0;
479
+ }
480
+ if (op[0] & 5) throw op[1];
481
+ return { value: op[0] ? op[1] : void 0, done: true };
482
+ }
483
+ };
484
+ Object.defineProperty(exports2, "__esModule", { value: true });
485
+ var options_1 = require_options();
486
+ var delay_factory_1 = require_delay_factory();
487
+ function backOff2(request, options) {
488
+ if (options === void 0) {
489
+ options = {};
490
+ }
491
+ return __awaiter(this, void 0, void 0, function() {
492
+ var sanitizedOptions, backOff3;
493
+ return __generator(this, function(_a) {
494
+ switch (_a.label) {
495
+ case 0:
496
+ sanitizedOptions = options_1.getSanitizedOptions(options);
497
+ backOff3 = new BackOff(request, sanitizedOptions);
498
+ return [4, backOff3.execute()];
499
+ case 1:
500
+ return [2, _a.sent()];
501
+ }
502
+ });
503
+ });
504
+ }
505
+ exports2.backOff = backOff2;
506
+ var BackOff = (
507
+ /** @class */
508
+ function() {
509
+ function BackOff2(request, options) {
510
+ this.request = request;
511
+ this.options = options;
512
+ this.attemptNumber = 0;
513
+ }
514
+ BackOff2.prototype.execute = function() {
515
+ return __awaiter(this, void 0, void 0, function() {
516
+ var e_1, shouldRetry;
517
+ return __generator(this, function(_a) {
518
+ switch (_a.label) {
519
+ case 0:
520
+ if (!!this.attemptLimitReached) return [3, 7];
521
+ _a.label = 1;
522
+ case 1:
523
+ _a.trys.push([1, 4, , 6]);
524
+ return [4, this.applyDelay()];
525
+ case 2:
526
+ _a.sent();
527
+ return [4, this.request()];
528
+ case 3:
529
+ return [2, _a.sent()];
530
+ case 4:
531
+ e_1 = _a.sent();
532
+ this.attemptNumber++;
533
+ return [4, this.options.retry(e_1, this.attemptNumber)];
534
+ case 5:
535
+ shouldRetry = _a.sent();
536
+ if (!shouldRetry || this.attemptLimitReached) {
537
+ throw e_1;
538
+ }
539
+ return [3, 6];
540
+ case 6:
541
+ return [3, 0];
542
+ case 7:
543
+ throw new Error("Something went wrong.");
544
+ }
545
+ });
546
+ });
547
+ };
548
+ Object.defineProperty(BackOff2.prototype, "attemptLimitReached", {
549
+ get: function() {
550
+ return this.attemptNumber >= this.options.numOfAttempts;
551
+ },
552
+ enumerable: true,
553
+ configurable: true
554
+ });
555
+ BackOff2.prototype.applyDelay = function() {
556
+ return __awaiter(this, void 0, void 0, function() {
557
+ var delay;
558
+ return __generator(this, function(_a) {
559
+ switch (_a.label) {
560
+ case 0:
561
+ delay = delay_factory_1.DelayFactory(this.options, this.attemptNumber);
562
+ return [4, delay.apply()];
563
+ case 1:
564
+ _a.sent();
565
+ return [
566
+ 2
567
+ /*return*/
568
+ ];
569
+ }
570
+ });
571
+ });
572
+ };
573
+ return BackOff2;
574
+ }()
575
+ );
576
+ }
577
+ });
578
+
30
579
  // src/index.ts
31
580
  var src_exports = {};
32
581
  __export(src_exports, {
@@ -35,6 +584,9 @@ __export(src_exports, {
35
584
  });
36
585
  module.exports = __toCommonJS(src_exports);
37
586
 
587
+ // src/ari-client/ariClient.ts
588
+ var import_exponential_backoff = __toESM(require_backoff(), 1);
589
+
38
590
  // src/ari-client/baseClient.ts
39
591
  var import_axios = __toESM(require("axios"), 1);
40
592
  var BaseClient = class {
@@ -162,94 +714,105 @@ var WebSocketClient = class {
162
714
 
163
715
  // src/ari-client/ariClient.ts
164
716
  var AriClient = class {
165
- // Adicionado
166
717
  /**
167
718
  * Initializes a new instance of the AriClient class.
168
719
  *
169
720
  * This constructor sets up the necessary configurations for connecting to an Asterisk ARI server,
170
- * including WebSocket and HTTP connections. It also initializes the channels resource.
721
+ * including HTTP connections. WebSocket connections are handled dynamically per application.
171
722
  *
172
723
  * @param config - The configuration object for the ARI client.
173
- * @param config.host - The hostname or IP address of the Asterisk server.
174
- * @param config.port - The port number on which the Asterisk ARI is listening.
175
- * @param config.username - The username for authentication with the Asterisk ARI.
176
- * @param config.password - The password for authentication with the Asterisk ARI.
177
- * @param config.secure - Optional. If true, uses secure protocols (WSS/HTTPS). Defaults to false.
178
724
  */
179
725
  constructor(config) {
180
726
  this.config = config;
181
- const protocol = config.secure ? "wss" : "ws";
182
727
  const httpProtocol = config.secure ? "https" : "http";
183
- const encodedUsername = encodeURIComponent(config.username);
184
- const encodedPassword = encodeURIComponent(config.password);
185
728
  const normalizedHost = config.host.replace(/^https?:\/\//, "");
186
- const wsUrl = `${protocol}://${encodedUsername}:${encodedPassword}@${normalizedHost}:${config.port}/ari/events?app=${config.app}`;
187
729
  const baseUrl = `${httpProtocol}://${normalizedHost}:${config.port}/ari`;
188
- console.log({ wsUrl, baseUrl });
189
- this.wsClient = new WebSocketClient(wsUrl);
190
730
  this.baseClient = new BaseClient(baseUrl, config.username, config.password);
191
731
  this.channels = new Channels(this.baseClient);
192
732
  }
193
- wsClient;
733
+ wsClient = null;
194
734
  baseClient;
195
735
  channels;
196
736
  /**
197
- * Conecta ao WebSocket do ARI.
198
- * @returns {Promise<void>} Retorna uma promise resolvida ao conectar com sucesso.
737
+ * Connects to the ARI WebSocket for a specific application.
738
+ *
739
+ * @param app - The application name to connect to.
740
+ * @returns {Promise<void>} Resolves when the WebSocket connects successfully.
199
741
  */
200
- async connectWebSocket() {
742
+ async connectWebSocket(app) {
743
+ if (!app) {
744
+ throw new Error(
745
+ "The 'app' parameter is required to connect to the WebSocket."
746
+ );
747
+ }
748
+ const protocol = this.config.secure ? "wss" : "ws";
749
+ const wsUrl = `${protocol}://${encodeURIComponent(this.config.username)}:${encodeURIComponent(this.config.password)}@${this.config.host}:${this.config.port}/ari/events?app=${app}`;
750
+ this.wsClient = new WebSocketClient(wsUrl);
751
+ const backoffOptions = {
752
+ delayFirstAttempt: false,
753
+ startingDelay: 1e3,
754
+ timeMultiple: 2,
755
+ maxDelay: 3e4,
756
+ // Máximo de 30 segundos entre tentativas
757
+ numOfAttempts: 10,
758
+ // Até 10 tentativas
759
+ jitter: "full",
760
+ // Adiciona variabilidade ao intervalo
761
+ retry: (error, attemptNumber) => {
762
+ console.warn(`Tentativa ${attemptNumber} falhou: ${error.message}`);
763
+ return true;
764
+ }
765
+ };
201
766
  try {
202
- await this.wsClient.connect();
203
- console.log("WebSocket conectado com sucesso!");
767
+ await (0, import_exponential_backoff.backOff)(async () => {
768
+ if (this.wsClient) {
769
+ await this.wsClient.connect();
770
+ console.log(`WebSocket connected for app: ${app}`);
771
+ } else {
772
+ throw new Error("WebSocketClient instance is null.");
773
+ }
774
+ }, backoffOptions);
204
775
  } catch (err) {
205
- console.error("Erro ao conectar ao WebSocket:", err);
776
+ console.error(
777
+ "Failed to connect to WebSocket after multiple attempts:",
778
+ err
779
+ );
206
780
  throw err;
207
781
  }
208
782
  }
209
783
  /**
210
- * Checks if the WebSocket connection is currently active.
211
- *
212
- * This method provides a way to determine the current state of the WebSocket connection
213
- * to the Asterisk ARI server.
784
+ * Checks if the WebSocket connection is active.
214
785
  *
215
- * @returns {boolean} Returns true if the WebSocket is connected, false otherwise.
786
+ * @returns {boolean} True if connected, false otherwise.
216
787
  */
217
788
  isWebSocketConnected() {
218
- return this.wsClient.isConnected();
789
+ return this.wsClient ? this.wsClient.isConnected() : false;
219
790
  }
220
791
  /**
221
- * Registers a callback function for a specific WebSocket event.
792
+ * Registers a callback for a specific WebSocket event.
222
793
  *
223
- * This method allows you to attach event listeners to WebSocket events
224
- * from the Asterisk ARI server. When the specified event occurs, the
225
- * provided callback function will be executed.
226
- *
227
- * @param event - The name of the WebSocket event to listen for.
228
- * @param callback - The function to be called when the event occurs.
229
- * It receives the event data as its parameter.
230
- * @returns void
794
+ * @param event - The WebSocket event to listen for.
795
+ * @param callback - The callback function to execute when the event occurs.
231
796
  */
232
797
  onWebSocketEvent(event, callback) {
798
+ if (!this.wsClient) {
799
+ throw new Error("WebSocket is not connected.");
800
+ }
233
801
  this.wsClient.on(event, callback);
234
802
  }
235
803
  /**
236
- * Closes the WebSocket connection to the Asterisk ARI server.
237
- *
238
- * This method terminates the existing WebSocket connection, if one is active.
239
- * It's useful for cleaning up resources when the connection is no longer needed.
804
+ * Closes the WebSocket connection.
240
805
  */
241
806
  closeWebSocket() {
242
- this.wsClient.close();
807
+ if (this.wsClient) {
808
+ this.wsClient.close();
809
+ this.wsClient = null;
810
+ }
243
811
  }
244
812
  /**
245
- * Retrieves a list of all active channels from the Asterisk ARI server.
813
+ * Retrieves a list of active channels from the Asterisk ARI.
246
814
  *
247
- * This method makes an asynchronous GET request to the '/channels' endpoint
248
- * of the Asterisk ARI.
249
- *
250
- * @returns {Promise<any>} A promise that resolves with the list of active channels.
251
- * The exact structure of the returned data depends on the
252
- * Asterisk ARI specification.
815
+ * @returns {Promise<any>} A promise resolving to the list of active channels.
253
816
  */
254
817
  async listChannels() {
255
818
  return this.baseClient.get("/channels");
@@ -257,15 +820,8 @@ var AriClient = class {
257
820
  /**
258
821
  * Initiates a new channel on the Asterisk server.
259
822
  *
260
- * This method makes an asynchronous POST request to the '/channels' endpoint
261
- * of the Asterisk ARI to create a new channel with the specified parameters.
262
- *
263
- * @param {any} data - An object containing the parameters for the new channel.
264
- * The structure of this object should conform to the
265
- * Asterisk ARI specification for channel origination.
266
- * @returns {Promise<any>} A promise that resolves with the response from the
267
- * Asterisk server, typically containing details of
268
- * the newly created channel.
823
+ * @param data - The parameters for creating the new channel.
824
+ * @returns {Promise<any>} A promise resolving to the new channel's details.
269
825
  */
270
826
  async originateChannel(data) {
271
827
  return this.baseClient.post("/channels", data);