@ipcom/asterisk-ari 0.0.157 → 0.0.159

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.
@@ -1803,7 +1803,7 @@ var ChannelInstance = class {
1803
1803
  * Otherwise, all listeners for the given event type are removed.
1804
1804
  *
1805
1805
  * @param {T} event - The type of WebSocket event to remove listener(s) for
1806
- * @param {Function} [listener] - Optional specific listener to remove
1806
+ * @param {(data: WebSocketEvent) => void} [listener] - Optional specific listener to remove
1807
1807
  * @throws {Error} If no event type is provided
1808
1808
  */
1809
1809
  off(event, listener) {
@@ -2765,7 +2765,7 @@ var PlaybackInstance = class {
2765
2765
  * Registers an event listener for a specific WebSocket event type.
2766
2766
  *
2767
2767
  * @param {T} event - Event type to listen for
2768
- * @param {Function} listener - Callback function for the event
2768
+ * @param {(data: WebSocketEvent) => void} listener - Callback function for the event
2769
2769
  */
2770
2770
  on(event, listener) {
2771
2771
  if (!event) {
@@ -2793,7 +2793,7 @@ var PlaybackInstance = class {
2793
2793
  * Registers a one-time event listener for a specific WebSocket event type.
2794
2794
  *
2795
2795
  * @param {T} event - Event type to listen for
2796
- * @param {Function} listener - Callback function for the event
2796
+ * @param {(data: WebSocketEvent) => void} listener - Callback function for the event
2797
2797
  */
2798
2798
  once(event, listener) {
2799
2799
  if (!event) {
@@ -2823,7 +2823,7 @@ var PlaybackInstance = class {
2823
2823
  * Removes event listener(s) for a specific WebSocket event type.
2824
2824
  *
2825
2825
  * @param {T} event - Event type to remove listener(s) for
2826
- * @param {Function} [listener] - Optional specific listener to remove
2826
+ * @param {(data: WebSocketEvent) => void} [listener] - Optional specific listener to remove
2827
2827
  */
2828
2828
  off(event, listener) {
2829
2829
  if (!event) {
@@ -3004,11 +3004,11 @@ var Playbacks = class {
3004
3004
  * This method performs the following cleanup operations:
3005
3005
  * 1. Clears all pending timeouts in the event queue.
3006
3006
  * 2. Removes all playback instances.
3007
- *
3007
+ *
3008
3008
  * @remarks
3009
3009
  * This method should be called when the Playbacks instance is no longer needed
3010
3010
  * to ensure proper resource management and prevent memory leaks.
3011
- *
3011
+ *
3012
3012
  * @returns {void} This method doesn't return a value.
3013
3013
  */
3014
3014
  cleanup() {
@@ -3318,13 +3318,64 @@ var WebSocketClient = class extends import_events4.EventEmitter {
3318
3318
  (event) => queryParams.append("event", event)
3319
3319
  );
3320
3320
  this.lastWsUrl = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${normalizedHost}/ari/events?${queryParams.toString()}`;
3321
- console.log("Connecting to WebSocket...");
3322
3321
  try {
3323
3322
  await this.initializeWebSocket(this.lastWsUrl);
3324
3323
  } finally {
3325
3324
  this.isConnecting = false;
3326
3325
  }
3327
3326
  }
3327
+ /**
3328
+ * Reconecta o WebSocket com uma lista atualizada de aplicações.
3329
+ *
3330
+ * @param {string[]} newApps - Lista de aplicações para reconectar
3331
+ * @param {WebSocketEventType[]} [subscribedEvents] - Tipos de eventos para se inscrever (opcional)
3332
+ * @returns {Promise<void>} Promise resolvida quando reconectado com sucesso
3333
+ */
3334
+ async reconnectWithApps(newApps, subscribedEvents) {
3335
+ if (!newApps.length) {
3336
+ throw new Error("At least one application name is required");
3337
+ }
3338
+ const uniqueApps = Array.from(/* @__PURE__ */ new Set([...this.apps, ...newApps]));
3339
+ if (uniqueApps.length === this.apps.length && uniqueApps.every((app) => this.apps.includes(app))) {
3340
+ console.log(
3341
+ "No changes in applications list, maintaining current connection"
3342
+ );
3343
+ return;
3344
+ }
3345
+ console.log(
3346
+ `Reconnecting WebSocket with updated applications: ${uniqueApps.join(", ")}`
3347
+ );
3348
+ this.apps = uniqueApps;
3349
+ if (subscribedEvents) {
3350
+ this.subscribedEvents = subscribedEvents;
3351
+ }
3352
+ if (this.ws) {
3353
+ await new Promise((resolve) => {
3354
+ this.once("disconnected", () => resolve());
3355
+ this.close();
3356
+ });
3357
+ }
3358
+ await this.connect();
3359
+ console.log("WebSocket reconnected successfully with updated applications");
3360
+ }
3361
+ /**
3362
+ * Adiciona novas aplicações à conexão WebSocket existente.
3363
+ *
3364
+ * @param {string[]} newApps - Lista de novas aplicações para adicionar
3365
+ * @param {WebSocketEventType[]} [subscribedEvents] - Tipos de eventos para se inscrever (opcional)
3366
+ * @returns {Promise<void>} Promise resolvida quando as aplicações são adicionadas com sucesso
3367
+ */
3368
+ async addApps(newApps, subscribedEvents) {
3369
+ if (!newApps.length) {
3370
+ throw new Error("At least one application name is required");
3371
+ }
3372
+ const appsToAdd = newApps.filter((app) => !this.apps.includes(app));
3373
+ if (appsToAdd.length === 0) {
3374
+ console.log("All applications are already registered");
3375
+ return;
3376
+ }
3377
+ await this.reconnectWithApps(appsToAdd, subscribedEvents);
3378
+ }
3328
3379
  /**
3329
3380
  * Initializes a WebSocket connection with exponential backoff retry mechanism.
3330
3381
  *
@@ -3346,7 +3397,6 @@ var WebSocketClient = class extends import_events4.EventEmitter {
3346
3397
  try {
3347
3398
  this.ws = new import_ws.default(wsUrl);
3348
3399
  this.ws.once("open", () => {
3349
- console.log("WebSocket connection established successfully");
3350
3400
  this.setupHeartbeat();
3351
3401
  if (this.isReconnecting) {
3352
3402
  this.emit("reconnected", {
@@ -3597,7 +3647,6 @@ var AriClient = class {
3597
3647
  baseClient;
3598
3648
  webSocketClient;
3599
3649
  eventListeners = /* @__PURE__ */ new Map();
3600
- // Armazena os listeners para limpeza
3601
3650
  channels;
3602
3651
  endpoints;
3603
3652
  applications;
@@ -3655,16 +3704,19 @@ var AriClient = class {
3655
3704
  * @param {string[]} apps - List of application names to subscribe to
3656
3705
  * @param {WebSocketEventType[]} [subscribedEvents] - Optional list of specific event types to subscribe to
3657
3706
  * @returns {Promise<void>} Resolves when connection is established
3658
- * @throws {Error} If connection fails or if WebSocket is already connected
3707
+ * @throws {Error} If connection fails
3659
3708
  */
3660
3709
  async connectWebSocket(apps, subscribedEvents) {
3661
3710
  try {
3662
3711
  if (!apps.length) {
3663
3712
  throw new Error("At least one application name is required.");
3664
3713
  }
3665
- if (this.webSocketClient) {
3666
- await this.closeWebSocket();
3667
- await new Promise((resolve) => setTimeout(resolve, 1e3));
3714
+ if (this.webSocketClient && this.webSocketClient.isConnected()) {
3715
+ console.log(
3716
+ "WebSocket already connected. Reconnecting with updated apps..."
3717
+ );
3718
+ await this.webSocketClient.reconnectWithApps(apps, subscribedEvents);
3719
+ return;
3668
3720
  }
3669
3721
  this.webSocketClient = new WebSocketClient(
3670
3722
  this.baseClient,
@@ -3673,17 +3725,31 @@ var AriClient = class {
3673
3725
  this
3674
3726
  );
3675
3727
  await this.webSocketClient.connect();
3676
- console.log("WebSocket connection established successfully.");
3677
3728
  } catch (error) {
3678
3729
  console.error("Failed to establish WebSocket connection:", error);
3679
- this.webSocketClient = void 0;
3680
3730
  throw error;
3681
3731
  }
3682
3732
  }
3733
+ /**
3734
+ * Adds applications to the existing WebSocket connection.
3735
+ *
3736
+ * @param {string[]} apps - Additional applications to subscribe to
3737
+ * @param {WebSocketEventType[]} [subscribedEvents] - Optional list of specific event types to subscribe to
3738
+ * @returns {Promise<void>} Resolves when applications are added successfully
3739
+ * @throws {Error} If no WebSocket connection exists or if the operation fails
3740
+ */
3741
+ async addApplicationsToWebSocket(apps, subscribedEvents) {
3742
+ if (!this.webSocketClient || !this.webSocketClient.isConnected()) {
3743
+ throw new Error(
3744
+ "No active WebSocket connection. Create one first with connectWebSocket()."
3745
+ );
3746
+ }
3747
+ await this.webSocketClient.addApps(apps, subscribedEvents);
3748
+ }
3683
3749
  /**
3684
3750
  * Destroys the ARI Client instance, cleaning up all resources and removing circular references.
3685
3751
  * This method should be called when the ARI Client is no longer needed to ensure proper cleanup.
3686
- *
3752
+ *
3687
3753
  * @returns {Promise<void>} A promise that resolves when the destruction process is complete.
3688
3754
  * @throws {Error} If an error occurs during the destruction process.
3689
3755
  */
@@ -3705,6 +3771,13 @@ var AriClient = class {
3705
3771
  throw error;
3706
3772
  }
3707
3773
  }
3774
+ /**
3775
+ * Registers an event listener for WebSocket events.
3776
+ *
3777
+ * @param {T} event - The event type to listen for
3778
+ * @param {Function} listener - Callback function for handling the event
3779
+ * @throws {Error} If WebSocket is not connected
3780
+ */
3708
3781
  /**
3709
3782
  * Registers an event listener for WebSocket events.
3710
3783
  *
@@ -3749,7 +3822,10 @@ var AriClient = class {
3749
3822
  this.off(event, wrappedListener);
3750
3823
  };
3751
3824
  this.webSocketClient.once(event, wrappedListener);
3752
- this.eventListeners.set(event, [...existingListeners, wrappedListener]);
3825
+ this.eventListeners.set(event, [
3826
+ ...existingListeners,
3827
+ wrappedListener
3828
+ ]);
3753
3829
  console.log(`One-time event listener registered for ${event}`);
3754
3830
  }
3755
3831
  /**
@@ -3767,7 +3843,9 @@ var AriClient = class {
3767
3843
  const existingListeners = this.eventListeners.get(event) || [];
3768
3844
  this.eventListeners.set(
3769
3845
  event,
3770
- existingListeners.filter((l) => l !== listener)
3846
+ existingListeners.filter(
3847
+ (l) => l !== listener
3848
+ )
3771
3849
  );
3772
3850
  console.log(`Event listener removed for ${event}`);
3773
3851
  }