@ipcom/asterisk-ari 0.0.42 → 0.0.44

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/dist/esm/index.js CHANGED
@@ -572,7 +572,6 @@ var require_backoff = __commonJS({
572
572
 
573
573
  // src/ari-client/ariClient.ts
574
574
  var import_exponential_backoff = __toESM(require_backoff(), 1);
575
- import { EventEmitter as EventEmitter4 } from "events";
576
575
 
577
576
  // src/ari-client/baseClient.ts
578
577
  import axios from "axios";
@@ -837,42 +836,15 @@ var Bridges = class {
837
836
 
838
837
  // src/ari-client/resources/channels.ts
839
838
  import { EventEmitter } from "events";
839
+
840
+ // src/ari-client/utils.ts
840
841
  function toQueryParams2(options) {
841
842
  return new URLSearchParams(
842
843
  Object.entries(options).filter(([, value]) => value !== void 0).map(([key, value]) => [key, value])
843
844
  ).toString();
844
845
  }
845
- var ChannelEventEmitter = class {
846
- eventEmitter = new EventEmitter();
847
- channel;
848
- constructor(channel) {
849
- this.channel = channel;
850
- }
851
- /**
852
- * Registra um listener para um evento no canal.
853
- */
854
- on(eventType, callback) {
855
- this.eventEmitter.on(eventType, callback);
856
- }
857
- /**
858
- * Emite um evento no canal.
859
- */
860
- emit(eventType, data) {
861
- this.eventEmitter.emit(eventType, data);
862
- }
863
- /**
864
- * Remove um listener de evento do canal.
865
- */
866
- off(eventType, callback) {
867
- this.eventEmitter.off(eventType, callback);
868
- }
869
- /**
870
- * Remove todos os listeners de um evento no canal.
871
- */
872
- removeAllListeners(eventType) {
873
- this.eventEmitter.removeAllListeners(eventType);
874
- }
875
- };
846
+
847
+ // src/ari-client/resources/channels.ts
876
848
  var ChannelInstance = class extends EventEmitter {
877
849
  constructor(client, baseClient, channelId = `channel-${Date.now()}`) {
878
850
  super();
@@ -883,7 +855,6 @@ var ChannelInstance = class extends EventEmitter {
883
855
  channelData = null;
884
856
  /**
885
857
  * Getter para o ID do canal.
886
- * Sempre retorna um ID, seja o definido manualmente ou o gerado automaticamente.
887
858
  */
888
859
  get id() {
889
860
  return this.channelId;
@@ -897,7 +868,6 @@ var ChannelInstance = class extends EventEmitter {
897
868
  }
898
869
  const channel = await this.baseClient.post("/channels", data);
899
870
  this.channelData = channel;
900
- this.emit("ChannelCreated", channel, this);
901
871
  return channel;
902
872
  }
903
873
  /**
@@ -920,14 +890,9 @@ var ChannelInstance = class extends EventEmitter {
920
890
  throw new Error("O canal ainda n\xE3o foi criado.");
921
891
  }
922
892
  await this.baseClient.delete(`/channels/${this.channelData.id}`);
923
- this.emit("ChannelHungUp", this.channelData);
924
893
  }
925
894
  /**
926
- * Toca um arquivo de mídia no canal.
927
- *
928
- * @param options - Opções para o playback, incluindo mídia e idioma.
929
- * @param playback - (Opcional) Uma instância de `PlaybackInstance` para gerenciar o playback. Se não fornecido, será criada uma nova.
930
- * @returns Uma instância de `PlaybackInstance` associada ao playback.
895
+ * Reproduz mídia no canal.
931
896
  */
932
897
  async play(options, playback) {
933
898
  if (!playback) {
@@ -935,119 +900,145 @@ var ChannelInstance = class extends EventEmitter {
935
900
  }
936
901
  await this.baseClient.post(
937
902
  `/channels/${this.channelData?.id}/play/${playback.id}`,
938
- // Agora o ID é garantido
939
903
  options
940
904
  );
941
905
  return playback;
942
906
  }
943
907
  /**
944
- * Adiciona um listener para eventos de canal.
908
+ * Reproduz mídia em um canal.
945
909
  */
946
- on(event, callback) {
947
- super.on(event, callback);
948
- return this;
910
+ async playMedia(media, options) {
911
+ if (!this.channelData) {
912
+ throw new Error("O canal ainda n\xE3o foi criado.");
913
+ }
914
+ const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
915
+ return this.baseClient.post(
916
+ `/channels/${this.channelData.id}/play${queryParams}`,
917
+ { media }
918
+ );
949
919
  }
950
920
  /**
951
- * Adiciona um listener para ser chamado apenas uma vez.
921
+ * Para a reprodução de mídia.
952
922
  */
953
- once(event, callback) {
954
- super.once(event, callback);
955
- return this;
923
+ async stopPlayback(playbackId) {
924
+ if (!this.channelData?.id) {
925
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
926
+ }
927
+ await this.baseClient.delete(
928
+ `/channels/${this.channelData.id}/play/${playbackId}`
929
+ );
956
930
  }
957
931
  /**
958
- * Remove um listener específico.
932
+ * Pausa a reprodução de mídia.
959
933
  */
960
- off(event, callback) {
961
- super.off(event, callback);
962
- return this;
963
- }
964
- };
965
- var Channels = class extends EventEmitter {
966
- constructor(baseClient, client, channelId) {
967
- super();
968
- this.baseClient = baseClient;
969
- this.client = client;
970
- this.channelId = channelId;
934
+ async pausePlayback(playbackId) {
935
+ if (!this.channelData?.id) {
936
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
937
+ }
938
+ await this.baseClient.post(
939
+ `/channels/${this.channelData.id}/play/${playbackId}/pause`
940
+ );
971
941
  }
972
942
  /**
973
- * Cria uma nova instância de `ChannelInstance` sem originar um canal físico.
943
+ * Retoma a reprodução de mídia.
974
944
  */
975
- createChannelInstance(channelId) {
976
- return new ChannelInstance(this.client, this.baseClient, channelId);
945
+ async resumePlayback(playbackId) {
946
+ if (!this.channelData?.id) {
947
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
948
+ }
949
+ await this.baseClient.delete(
950
+ `/channels/${this.channelData.id}/play/${playbackId}/pause`
951
+ );
977
952
  }
978
953
  /**
979
- * Origina um canal físico diretamente, sem uma instância de `ChannelInstance`.
954
+ * Retrocede a reprodução de mídia.
980
955
  */
981
- async originate(data) {
982
- return this.baseClient.post("/channels", data);
956
+ async rewindPlayback(playbackId, skipMs) {
957
+ if (!this.channelData?.id) {
958
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
959
+ }
960
+ await this.baseClient.post(
961
+ `/channels/${this.channelData.id}/play/${playbackId}/rewind`,
962
+ { skipMs }
963
+ );
983
964
  }
984
965
  /**
985
- * Lida com eventos relacionados ao canal e os emite para listeners registrados.
966
+ * Avança a reprodução de mídia.
986
967
  */
987
- emitChannelEvent(eventType, data) {
988
- if ("channel" in data) {
989
- const channelId = data.channel?.id;
990
- if (channelId) {
991
- this.emit(`${eventType}:${channelId}`, data);
992
- }
968
+ async fastForwardPlayback(playbackId, skipMs) {
969
+ if (!this.channelData?.id) {
970
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
993
971
  }
994
- this.emit(eventType, data);
972
+ await this.baseClient.post(
973
+ `/channels/${this.channelData.id}/play/${playbackId}/forward`,
974
+ { skipMs }
975
+ );
995
976
  }
996
977
  /**
997
- * Registra um listener para eventos de canal específicos.
978
+ * Muta o canal.
998
979
  */
999
- registerChannelListener(eventType, channelId, callback) {
1000
- this.on(`${eventType}:${channelId}`, callback);
980
+ async muteChannel(direction = "both") {
981
+ if (!this.channelData?.id) {
982
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
983
+ }
984
+ await this.baseClient.post(
985
+ `/channels/${this.channelData.id}/mute?direction=${direction}`
986
+ );
1001
987
  }
1002
988
  /**
1003
- * Remove um listener específico de eventos de canal.
989
+ * Desmuta o canal.
1004
990
  */
1005
- unregisterChannelListener(eventType, channelId, callback) {
1006
- this.off(`${eventType}:${channelId}`, callback);
991
+ async unmuteChannel(direction = "both") {
992
+ if (!this.channelData?.id) {
993
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
994
+ }
995
+ await this.baseClient.delete(
996
+ `/channels/${this.channelData.id}/mute?direction=${direction}`
997
+ );
1007
998
  }
1008
999
  /**
1009
- * Verifica se um listener já está registrado para um evento de canal.
1000
+ * Coloca o canal em espera.
1010
1001
  */
1011
- isChannelListenerRegistered(eventType, channelId) {
1012
- return this.listenerCount(`${eventType}:${channelId}`) > 0;
1002
+ async holdChannel() {
1003
+ if (!this.channelData?.id) {
1004
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1005
+ }
1006
+ await this.baseClient.post(`/channels/${this.channelData.id}/hold`);
1013
1007
  }
1014
1008
  /**
1015
- * Lista todos os canais ativos.
1009
+ * Remove o canal da espera.
1016
1010
  */
1017
- async list() {
1018
- const channels = await this.baseClient.get("/channels");
1019
- if (!Array.isArray(channels)) {
1020
- throw new Error("Resposta da API /channels n\xE3o \xE9 um array.");
1011
+ async unholdChannel() {
1012
+ if (!this.channelData?.id) {
1013
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1021
1014
  }
1022
- return channels;
1015
+ await this.baseClient.delete(`/channels/${this.channelData.id}/hold`);
1023
1016
  }
1024
- /**
1025
- * Obtém detalhes de um canal específico.
1026
- */
1027
- async getDetails(channelId) {
1028
- return this.baseClient.get(`/channels/${channelId}`);
1017
+ };
1018
+ var Channels = class extends EventEmitter {
1019
+ constructor(baseClient, client) {
1020
+ super();
1021
+ this.baseClient = baseClient;
1022
+ this.client = client;
1023
+ }
1024
+ createChannelInstance(channelId) {
1025
+ return new ChannelInstance(this.client, this.baseClient, channelId);
1029
1026
  }
1030
1027
  /**
1031
- * Reproduz mídia em um canal.
1028
+ * Origina um canal físico diretamente, sem uma instância de `ChannelInstance`.
1032
1029
  */
1033
- async playMedia(channelId, media, options) {
1034
- const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
1035
- return this.baseClient.post(
1036
- `/channels/${channelId}/play${queryParams}`,
1037
- { media }
1038
- );
1030
+ async originate(data) {
1031
+ return this.baseClient.post("/channels", data);
1039
1032
  }
1040
1033
  /**
1041
- * Encerra um canal específico.
1034
+ * Lista todos os canais ativos.
1042
1035
  */
1043
- async hangup(channelId, options) {
1044
- const queryParams = new URLSearchParams({
1045
- ...options?.reason_code && { reason_code: options.reason_code },
1046
- ...options?.reason && { reason: options.reason }
1047
- });
1048
- return this.baseClient.delete(
1049
- `/channels/${channelId}?${queryParams.toString()}`
1050
- );
1036
+ async list() {
1037
+ const channels = await this.baseClient.get("/channels");
1038
+ if (!Array.isArray(channels)) {
1039
+ throw new Error("Resposta da API /channels n\xE3o \xE9 um array.");
1040
+ }
1041
+ return channels;
1051
1042
  }
1052
1043
  /**
1053
1044
  * Inicia a escuta em um canal.
@@ -1070,38 +1061,30 @@ var Channels = class extends EventEmitter {
1070
1061
  );
1071
1062
  }
1072
1063
  async createExternalMedia(options) {
1073
- const queryParams = new URLSearchParams(options);
1064
+ const queryParams = toQueryParams2(options);
1074
1065
  return this.baseClient.post(
1075
- `/channels/externalMedia?${queryParams.toString()}`
1066
+ `/channels/externalMedia?${queryParams}`
1076
1067
  );
1077
1068
  }
1078
1069
  async playWithId(channelId, playbackId, media, options) {
1079
- const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
1070
+ const queryParams = options ? `?${toQueryParams2(options)}` : "";
1080
1071
  return this.baseClient.post(
1081
1072
  `/channels/${channelId}/play/${playbackId}${queryParams}`,
1082
1073
  { media }
1083
1074
  );
1084
1075
  }
1085
1076
  async snoopChannelWithId(channelId, snoopId, options) {
1086
- const queryParams = new URLSearchParams(options);
1077
+ const queryParams = toQueryParams2(options);
1087
1078
  return this.baseClient.post(
1088
- `/channels/${channelId}/snoop/${snoopId}?${queryParams.toString()}`
1079
+ `/channels/${channelId}/snoop/${snoopId}?${queryParams}`
1089
1080
  );
1090
1081
  }
1091
1082
  async startMohWithClass(channelId, mohClass) {
1092
1083
  const queryParams = `mohClass=${encodeURIComponent(mohClass)}`;
1093
- return this.baseClient.post(
1084
+ await this.baseClient.post(
1094
1085
  `/channels/${channelId}/moh?${queryParams}`
1095
1086
  );
1096
1087
  }
1097
- /**
1098
- * Gets the value of a channel variable or function.
1099
- *
1100
- * @param channelId - The ID of the channel.
1101
- * @param variable - The name of the channel variable or function to retrieve.
1102
- * @returns A promise that resolves to the value of the variable.
1103
- * @throws Will throw an error if the variable is missing or the channel is not found.
1104
- */
1105
1088
  async getChannelVariable(channelId, variable) {
1106
1089
  if (!variable) {
1107
1090
  throw new Error("The 'variable' parameter is required.");
@@ -1110,15 +1093,6 @@ var Channels = class extends EventEmitter {
1110
1093
  `/channels/${channelId}/variable?variable=${encodeURIComponent(variable)}`
1111
1094
  );
1112
1095
  }
1113
- /**
1114
- * Sets the value of a channel variable or function.
1115
- *
1116
- * @param channelId - The ID of the channel.
1117
- * @param variable - The name of the channel variable or function to set.
1118
- * @param value - The value to set the variable to.
1119
- * @returns A promise that resolves when the variable is successfully set.
1120
- * @throws Will throw an error if the variable is missing or the channel is not found.
1121
- */
1122
1096
  async setChannelVariable(channelId, variable, value) {
1123
1097
  if (!variable) {
1124
1098
  throw new Error("The 'variable' parameter is required.");
@@ -1128,199 +1102,83 @@ var Channels = class extends EventEmitter {
1128
1102
  ...value && { value }
1129
1103
  });
1130
1104
  await this.baseClient.post(
1131
- `/channels/${channelId}/variable?${queryParams.toString()}`
1105
+ `/channels/${channelId}/variable?${queryParams}`
1132
1106
  );
1133
1107
  }
1134
- /**
1135
- * Moves the channel to another Stasis application.
1136
- */
1137
1108
  async moveToApplication(channelId, app, appArgs) {
1138
- return this.baseClient.post(`/channels/${channelId}/move`, {
1109
+ await this.baseClient.post(`/channels/${channelId}/move`, {
1139
1110
  app,
1140
1111
  appArgs
1141
1112
  });
1142
1113
  }
1143
- /**
1144
- * Continues the dialplan for a specific channel.
1145
- */
1146
1114
  async continueDialplan(channelId, context, extension, priority, label) {
1147
- return this.baseClient.post(`/channels/${channelId}/continue`, {
1115
+ await this.baseClient.post(`/channels/${channelId}/continue`, {
1148
1116
  context,
1149
1117
  extension,
1150
1118
  priority,
1151
1119
  label
1152
1120
  });
1153
1121
  }
1154
- /**
1155
- * Stops music on hold (MOH) for a channel.
1156
- */
1157
1122
  async stopMusicOnHold(channelId) {
1158
- return this.baseClient.delete(`/channels/${channelId}/moh`);
1123
+ await this.baseClient.delete(`/channels/${channelId}/moh`);
1159
1124
  }
1160
- /**
1161
- * Starts music on hold (MOH) for a channel.
1162
- */
1163
1125
  async startMusicOnHold(channelId) {
1164
- return this.baseClient.post(`/channels/${channelId}/moh`);
1165
- }
1166
- /**
1167
- * Starts playback of a media file on a channel.
1168
- */
1169
- /**
1170
- * Starts playback of a media file on a channel.
1171
- */
1172
- async startPlayback(channelId, media, options) {
1173
- const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
1174
- return this.baseClient.post(
1175
- `/channels/${channelId}/play${queryParams}`,
1176
- { media }
1177
- );
1126
+ await this.baseClient.post(`/channels/${channelId}/moh`);
1178
1127
  }
1179
- /**
1180
- * Stops playback of a media file on a channel.
1181
- */
1182
- async stopPlayback(channelId, playbackId) {
1183
- return this.baseClient.delete(
1184
- `/channels/${channelId}/play/${playbackId}`
1185
- );
1186
- }
1187
- /**
1188
- * Pauses playback of a media file on a channel.
1189
- */
1190
- async pausePlayback(channelId, playbackId) {
1191
- return this.baseClient.post(
1192
- `/channels/${channelId}/play/${playbackId}/pause`
1193
- );
1194
- }
1195
- /**
1196
- * Resumes playback of a media file on a channel.
1197
- */
1198
- async resumePlayback(channelId, playbackId) {
1199
- return this.baseClient.delete(
1200
- `/channels/${channelId}/play/${playbackId}/pause`
1201
- );
1202
- }
1203
- /**
1204
- * Rewinds playback of a media file on a channel.
1205
- */
1206
- async rewindPlayback(channelId, playbackId, skipMs) {
1207
- return this.baseClient.post(
1208
- `/channels/${channelId}/play/${playbackId}/rewind`,
1209
- { skipMs }
1210
- );
1211
- }
1212
- /**
1213
- * Fast-forwards playback of a media file on a channel.
1214
- */
1215
- async fastForwardPlayback(channelId, playbackId, skipMs) {
1216
- return this.baseClient.post(
1217
- `/channels/${channelId}/play/${playbackId}/forward`,
1218
- { skipMs }
1219
- );
1220
- }
1221
- /**
1222
- * Records audio from a channel.
1223
- */
1224
1128
  async record(channelId, options) {
1225
- const queryParams = new URLSearchParams(
1226
- Object.entries(options).filter(
1227
- ([, value]) => value !== void 0
1228
- )
1229
- );
1129
+ const queryParams = toQueryParams2(options);
1230
1130
  return this.baseClient.post(
1231
- `/channels/${channelId}/record?${queryParams.toString()}`
1131
+ `/channels/${channelId}/record?${queryParams}`
1232
1132
  );
1233
1133
  }
1234
- /**
1235
- * Dials a created channel.
1236
- */
1237
1134
  async dial(channelId, caller, timeout) {
1238
1135
  const queryParams = new URLSearchParams({
1239
1136
  ...caller && { caller },
1240
1137
  ...timeout && { timeout: timeout.toString() }
1241
1138
  });
1242
- return this.baseClient.post(
1243
- `/channels/${channelId}/dial?${queryParams.toString()}`
1139
+ await this.baseClient.post(
1140
+ `/channels/${channelId}/dial?${queryParams}`
1244
1141
  );
1245
1142
  }
1246
- /**
1247
- * Redirects the channel to a different location.
1248
- */
1249
1143
  async redirectChannel(channelId, endpoint) {
1250
- return this.baseClient.post(
1144
+ await this.baseClient.post(
1251
1145
  `/channels/${channelId}/redirect?endpoint=${encodeURIComponent(endpoint)}`
1252
1146
  );
1253
1147
  }
1254
- /**
1255
- * Answers a channel.
1256
- */
1257
1148
  async answerChannel(channelId) {
1258
- return this.baseClient.post(`/channels/${channelId}/answer`);
1149
+ await this.baseClient.post(`/channels/${channelId}/answer`);
1259
1150
  }
1260
- /**
1261
- * Sends a ringing indication to a channel.
1262
- */
1263
1151
  async ringChannel(channelId) {
1264
- return this.baseClient.post(`/channels/${channelId}/ring`);
1152
+ await this.baseClient.post(`/channels/${channelId}/ring`);
1265
1153
  }
1266
- /**
1267
- * Stops ringing indication on a channel.
1268
- */
1269
1154
  async stopRingChannel(channelId) {
1270
- return this.baseClient.delete(`/channels/${channelId}/ring`);
1155
+ await this.baseClient.delete(`/channels/${channelId}/ring`);
1271
1156
  }
1272
- /**
1273
- * Sends DTMF to a channel.
1274
- */
1275
1157
  async sendDTMF(channelId, dtmf, options) {
1276
- const queryParams = new URLSearchParams({
1277
- dtmf,
1278
- ...options?.before && { before: options.before.toString() },
1279
- ...options?.between && { between: options.between.toString() },
1280
- ...options?.duration && { duration: options.duration.toString() },
1281
- ...options?.after && { after: options.after.toString() }
1282
- });
1283
- return this.baseClient.post(
1284
- `/channels/${channelId}/dtmf?${queryParams.toString()}`
1158
+ const queryParams = toQueryParams2({ dtmf, ...options });
1159
+ await this.baseClient.post(
1160
+ `/channels/${channelId}/dtmf?${queryParams}`
1285
1161
  );
1286
1162
  }
1287
- /**
1288
- * Mutes a channel.
1289
- */
1290
1163
  async muteChannel(channelId, direction = "both") {
1291
- return this.baseClient.post(
1164
+ await this.baseClient.post(
1292
1165
  `/channels/${channelId}/mute?direction=${direction}`
1293
1166
  );
1294
1167
  }
1295
- /**
1296
- * Unmutes a channel.
1297
- */
1298
1168
  async unmuteChannel(channelId, direction = "both") {
1299
- return this.baseClient.delete(
1169
+ await this.baseClient.delete(
1300
1170
  `/channels/${channelId}/mute?direction=${direction}`
1301
1171
  );
1302
1172
  }
1303
- /**
1304
- * Puts a channel on hold.
1305
- */
1306
1173
  async holdChannel(channelId) {
1307
- return this.baseClient.post(`/channels/${channelId}/hold`);
1174
+ await this.baseClient.post(`/channels/${channelId}/hold`);
1308
1175
  }
1309
- /**
1310
- * Removes a channel from hold.
1311
- */
1312
1176
  async unholdChannel(channelId) {
1313
- return this.baseClient.delete(`/channels/${channelId}/hold`);
1177
+ await this.baseClient.delete(`/channels/${channelId}/hold`);
1314
1178
  }
1315
- /**
1316
- * Creates a channel and places it in a Stasis app without dialing it.
1317
- */
1318
1179
  async createChannel(data) {
1319
1180
  return this.baseClient.post("/channels/create", data);
1320
1181
  }
1321
- /**
1322
- * Creates a new channel with a specific ID and originates a call.
1323
- */
1324
1182
  async originateWithId(channelId, data) {
1325
1183
  return this.baseClient.post(`/channels/${channelId}`, data);
1326
1184
  }
@@ -1579,6 +1437,7 @@ var WebSocketClient = class extends EventEmitter3 {
1579
1437
  ws = null;
1580
1438
  isClosedManually = false;
1581
1439
  isReconnecting = false;
1440
+ messageListeners = [];
1582
1441
  /**
1583
1442
  * Establishes a connection to the WebSocket server.
1584
1443
  * @returns A Promise that resolves when the connection is established, or rejects if an error occurs.
@@ -1615,6 +1474,9 @@ var WebSocketClient = class extends EventEmitter3 {
1615
1474
  isConnected() {
1616
1475
  return this.ws?.readyState === WebSocket.OPEN;
1617
1476
  }
1477
+ onMessage(callback) {
1478
+ this.messageListeners.push(callback);
1479
+ }
1618
1480
  /**
1619
1481
  * Adds a listener for WebSocket events.
1620
1482
  * @param event - The event type to listen for.
@@ -1682,6 +1544,7 @@ var WebSocketClient = class extends EventEmitter3 {
1682
1544
  if (this.ws) {
1683
1545
  this.isClosedManually = true;
1684
1546
  this.ws.close();
1547
+ this.ws = null;
1685
1548
  console.log("WebSocket fechado manualmente.");
1686
1549
  }
1687
1550
  }
@@ -1703,15 +1566,14 @@ var AriClient = class {
1703
1566
  this.asterisk = new Asterisk(this.baseClient);
1704
1567
  this.bridges = new Bridges(this.baseClient);
1705
1568
  }
1569
+ eventListeners = /* @__PURE__ */ new Map();
1706
1570
  wsClient = null;
1707
- channelEmitters = /* @__PURE__ */ new Map();
1708
1571
  baseClient;
1709
1572
  isReconnecting = false;
1710
- eventEmitter = new EventEmitter4();
1711
- wsConnections = /* @__PURE__ */ new Map();
1712
1573
  isWebSocketConnectedFlag = false;
1713
1574
  webSocketReady = null;
1714
1575
  // Promise para rastrear o estado do WebSocket
1576
+ channelInstances = /* @__PURE__ */ new Map();
1715
1577
  pendingListeners = [];
1716
1578
  processPendingListeners() {
1717
1579
  if (!this.wsClient || !this.isWebSocketConnectedFlag) {
@@ -1736,6 +1598,47 @@ var AriClient = class {
1736
1598
  sounds;
1737
1599
  asterisk;
1738
1600
  bridges;
1601
+ /**
1602
+ * Registra um listener para eventos globais de WebSocket.
1603
+ */
1604
+ on(eventType, callback) {
1605
+ this.eventListeners.set(eventType, callback);
1606
+ }
1607
+ /**
1608
+ * Type guard to check if the given data object contains a valid channel property.
1609
+ * This function is used to narrow down the type of the data object and ensure it has a channel with an id.
1610
+ *
1611
+ * @param data - The object to be checked for the presence of a channel property.
1612
+ * @returns A type predicate indicating whether the data object contains a valid channel.
1613
+ * Returns true if the data object has a channel property with an id, false otherwise.
1614
+ */
1615
+ hasChannel(data) {
1616
+ return data?.channel?.id !== void 0;
1617
+ }
1618
+ // Método para criar uma instância de ChannelInstance
1619
+ createChannelInstance(channelId) {
1620
+ return this.channels.createChannelInstance(channelId);
1621
+ }
1622
+ handleWebSocketEvent(event) {
1623
+ const { type, ...data } = event;
1624
+ if (this.hasChannel(data)) {
1625
+ const channelId = data.channel.id;
1626
+ if (channelId) {
1627
+ if (!this.channelInstances.has(channelId)) {
1628
+ const channelInstance2 = this.createChannelInstance(channelId);
1629
+ this.channelInstances.set(channelId, channelInstance2);
1630
+ }
1631
+ const channelInstance = this.channelInstances.get(channelId);
1632
+ if (channelInstance) {
1633
+ data.channel = { ...data.channel, ...channelInstance };
1634
+ }
1635
+ }
1636
+ }
1637
+ const listener = this.eventListeners.get(type);
1638
+ if (listener) {
1639
+ listener(data);
1640
+ }
1641
+ }
1739
1642
  /**
1740
1643
  * Connects to the ARI WebSocket for a specific application.
1741
1644
  * This function establishes a WebSocket connection to the Asterisk ARI, sets up event listeners,
@@ -1821,18 +1724,6 @@ var AriClient = class {
1821
1724
  `WebSocket client para o app '${app}' n\xE3o est\xE1 conectado.`
1822
1725
  );
1823
1726
  }
1824
- wsClient.on("ChannelDestroyed", (data) => {
1825
- if (data.type === "ChannelDestroyed" && "channel" in data) {
1826
- console.log(`[${app}] Canal destru\xEDdo: ${data.channel.id}`);
1827
- this.removeChannel(data.channel.id);
1828
- }
1829
- });
1830
- wsClient.on("StasisEnd", (data) => {
1831
- if (data.type === "StasisEnd" && "channel" in data) {
1832
- console.log(`[${app}] StasisEnd para o canal: ${data.channel.id}`);
1833
- this.removeChannel(data.channel.id);
1834
- }
1835
- });
1836
1727
  const eventHandlers = {
1837
1728
  PlaybackStarted: (data) => {
1838
1729
  if ("playbackId" in data) {
@@ -1867,100 +1758,6 @@ var AriClient = class {
1867
1758
  }
1868
1759
  console.log(`[${app}] Todos os eventos do WebSocket foram registrados.`);
1869
1760
  }
1870
- /**
1871
- * Registra um listener para eventos globais.
1872
- * @param eventType
1873
- * @param callback - A função a ser executada quando um evento global for recebido.
1874
- */
1875
- onGlobalEvent(eventType, callback) {
1876
- this.eventEmitter.on(eventType, callback);
1877
- }
1878
- /**
1879
- * Remove um listener para eventos globais.
1880
- * @param callback - A função a ser removida dos eventos globais.
1881
- */
1882
- offGlobalEvent(callback) {
1883
- this.eventEmitter.off("globalEvent", callback);
1884
- }
1885
- /**
1886
- * Emite um evento global.
1887
- * @param data - Os dados do evento a serem emitidos.
1888
- */
1889
- emitGlobalEvent(data) {
1890
- this.eventEmitter.emit("globalEvent", data);
1891
- }
1892
- /**
1893
- * Unregisters a listener for playback events.
1894
- *
1895
- * This method removes a specific listener registered for a playback event type,
1896
- * ensuring that no further notifications are sent to the callback function.
1897
- *
1898
- * @param eventType - The type of event to stop listening for.
1899
- * @param playbackId - The unique ID of the playback associated with the listener.
1900
- * @param callback - The callback function to remove from the listener.
1901
- */
1902
- unregisterPlaybackListener(eventType, playbackId, callback) {
1903
- this.playbacks.unregisterListener(eventType, playbackId, callback);
1904
- }
1905
- registerListener(eventType, condition, callback) {
1906
- if (!this.isWebSocketConnected()) {
1907
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1908
- }
1909
- const handler = (eventData) => {
1910
- if (eventData.type === eventType && condition(eventData)) {
1911
- callback(eventData);
1912
- }
1913
- };
1914
- this.wsClient?.on(eventType, handler);
1915
- }
1916
- /**
1917
- * Registers a listener for playback events.
1918
- * The listener is triggered for events such as "PlaybackFinished".
1919
- *
1920
- * @param eventType - The type of event to listen for.
1921
- * @param playbackId - The ID of the playback to associate with this listener.
1922
- * @param callback - The callback function to execute when the event occurs.
1923
- */
1924
- registerPlaybackListener(eventType, playbackId, callback) {
1925
- if (!this.isWebSocketConnected()) {
1926
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1927
- }
1928
- console.log(
1929
- `Registrando listener para evento ${eventType} com playbackId ${playbackId}`
1930
- );
1931
- const handler = (eventData) => {
1932
- if ("playbackId" in eventData && eventData.playbackId === playbackId) {
1933
- callback(eventData);
1934
- }
1935
- };
1936
- this.wsClient?.on(eventType, handler);
1937
- }
1938
- registerChannelListener(eventType, channelId, callback) {
1939
- if (!this.isWebSocketConnected()) {
1940
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1941
- }
1942
- console.log(
1943
- `Registrando listener para evento ${eventType} com channelId ${channelId}`
1944
- );
1945
- const handler = (eventData) => {
1946
- if (eventData.type === eventType && "channel" in eventData && eventData.channel?.id === channelId) {
1947
- callback(
1948
- eventData
1949
- );
1950
- }
1951
- };
1952
- this.wsClient?.on(eventType, handler);
1953
- }
1954
- /**
1955
- * Checks if a listener is already registered for a specific event and playback.
1956
- *
1957
- * @param eventType - The type of event to check.
1958
- * @param playbackId - The playback ID associated with the listener.
1959
- * @returns True if a listener is already registered, false otherwise.
1960
- */
1961
- isPlaybackListenerRegistered(eventType, playbackId) {
1962
- return this.playbacks.isListenerRegistered(eventType, playbackId);
1963
- }
1964
1761
  /**
1965
1762
  * Ensures the ARI application is registered.
1966
1763
  *
@@ -1991,69 +1788,6 @@ var AriClient = class {
1991
1788
  isWebSocketConnected() {
1992
1789
  return this.wsClient ? this.wsClient.isConnected() : false;
1993
1790
  }
1994
- /**
1995
- * Registers a listener for WebSocket events.
1996
- *
1997
- * This function allows you to attach a callback function to a specific WebSocket event type.
1998
- * The callback will be executed whenever an event of the specified type is received.
1999
- *
2000
- * @template T - The type of WebSocket event, extending WebSocketEvent["type"].
2001
- * @param {T} event - The type of WebSocket event to listen for.
2002
- * @param {(data: Extract<WebSocketEvent, { type: T }>) => void} callback - The function to be called when the event is received.
2003
- * The callback receives the event data as its parameter.
2004
- * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
2005
- * @returns {void} This function doesn't return a value.
2006
- */
2007
- async onWebSocketEvent(event, callback) {
2008
- if (this.webSocketReady) {
2009
- console.log(`Aguardando WebSocket conectar antes de registrar: ${event}`);
2010
- await this.webSocketReady;
2011
- }
2012
- if (!this.wsClient || !this.isWebSocketConnectedFlag) {
2013
- throw new Error("WebSocket ainda n\xE3o est\xE1 conectado.");
2014
- }
2015
- console.log(`Registrando listener para evento: ${event}`);
2016
- this.wsClient.on(event, callback);
2017
- }
2018
- /**
2019
- * Removes a specific listener for WebSocket events.
2020
- *
2021
- * This function unregisters a previously registered callback function for a specific WebSocket event type.
2022
- * It's useful for removing event handlers when they are no longer needed or for cleaning up resources.
2023
- *
2024
- * @template T - The type of WebSocket event, extending WebSocketEvent["type"].
2025
- * @param {T} event - The type of WebSocket event to remove the listener from.
2026
- * @param {(data: Extract<WebSocketEvent, { type: T }>) => void} callback - The callback function to be removed.
2027
- * This should be the same function reference that was used when adding the event listener.
2028
- * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
2029
- * @returns {void} This function doesn't return a value.
2030
- */
2031
- offWebSocketEvent(event, callback) {
2032
- if (!this.wsClient) {
2033
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
2034
- }
2035
- this.wsClient.off(event, callback);
2036
- }
2037
- /**
2038
- * Removes all listeners for a specific WebSocket event type.
2039
- *
2040
- * This function removes all event listeners that have been registered for a particular
2041
- * WebSocket event type. It's useful for cleaning up event listeners when they are no
2042
- * longer needed or before re-registering new listeners.
2043
- *
2044
- * @param event - The type of WebSocket event for which all listeners should be removed.
2045
- * This should be a string identifying the event type (e.g., 'message', 'close', etc.).
2046
- *
2047
- * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
2048
- *
2049
- * @returns {void} This function doesn't return a value.
2050
- */
2051
- removeAllWebSocketListeners(event) {
2052
- if (!this.wsClient) {
2053
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
2054
- }
2055
- this.wsClient.removeAllListeners(event);
2056
- }
2057
1791
  /**
2058
1792
  * Closes the WebSocket connection and removes all associated listeners.
2059
1793
  *
@@ -2070,69 +1804,6 @@ var AriClient = class {
2070
1804
  this.wsClient = null;
2071
1805
  }
2072
1806
  }
2073
- /**
2074
- * Obtém ou cria um emissor de eventos para o canal especificado.
2075
- */
2076
- getOrCreateChannelEmitter(channel) {
2077
- if (!this.channelEmitters.has(channel.id)) {
2078
- this.channelEmitters.set(channel.id, new ChannelEventEmitter(channel));
2079
- }
2080
- return this.channelEmitters.get(channel.id);
2081
- }
2082
- handleChannelEvent(event) {
2083
- if ("channel" in event && event.channel) {
2084
- const channelEmitter = this.channelEmitters.get(event.channel.id);
2085
- if (channelEmitter) {
2086
- channelEmitter.emit(event.type, event);
2087
- } else {
2088
- console.warn(
2089
- `Nenhum listener registrado para o canal ${event.channel.id}`
2090
- );
2091
- }
2092
- }
2093
- }
2094
- registerGlobalWebSocketListener() {
2095
- this.wsClient?.on("message", (event) => {
2096
- if ("channel" in event && event.channel) {
2097
- this.handleChannelEvent(event);
2098
- } else {
2099
- this.eventEmitter.emit(event.type, event);
2100
- }
2101
- });
2102
- }
2103
- /**
2104
- * Adiciona um listener para um evento específico de canal.
2105
- */
2106
- onChannelEvent(channelId, eventType, callback) {
2107
- const channelEmitter = this.channelEmitters.get(channelId);
2108
- if (!channelEmitter) {
2109
- throw new Error(`Canal com ID ${channelId} n\xE3o encontrado.`);
2110
- }
2111
- channelEmitter.on(eventType, callback);
2112
- console.log(
2113
- `Listener registrado para o canal ${channelId} e evento ${eventType}`
2114
- );
2115
- }
2116
- removeChannel(channelId) {
2117
- const channelEmitter = this.channelEmitters.get(channelId);
2118
- if (channelEmitter) {
2119
- channelEmitter.removeAllListeners();
2120
- this.channelEmitters.delete(channelId);
2121
- console.log(`Listeners para o canal ${channelId} foram removidos.`);
2122
- } else {
2123
- console.warn(`Nenhum listener encontrado para o canal ${channelId}.`);
2124
- }
2125
- }
2126
- /**
2127
- * Remove um listener para um evento específico de canal.
2128
- */
2129
- offChannelEvent(channelId, eventType, callback) {
2130
- const channelEmitter = this.channelEmitters.get(channelId);
2131
- if (!channelEmitter) {
2132
- throw new Error(`Canal com ID ${channelId} n\xE3o encontrado.`);
2133
- }
2134
- channelEmitter.off(eventType, callback);
2135
- }
2136
1807
  /**
2137
1808
  * Retrieves a list of active channels from the Asterisk ARI.
2138
1809
  *
@@ -2150,18 +1821,6 @@ var AriClient = class {
2150
1821
  async originateChannel(data) {
2151
1822
  return this.channels.originate(data);
2152
1823
  }
2153
- /**
2154
- * Retrieves details of a specific channel.
2155
- */
2156
- async getChannelDetails(channelId) {
2157
- return this.channels.getDetails(channelId);
2158
- }
2159
- /**
2160
- * Hangs up a specific channel.
2161
- */
2162
- async hangupChannel(channelId) {
2163
- return this.channels.hangup(channelId);
2164
- }
2165
1824
  /**
2166
1825
  * Continues the dialplan for a specific channel.
2167
1826
  */
@@ -2192,12 +1851,6 @@ var AriClient = class {
2192
1851
  async getChannelVariable(channelId, variable) {
2193
1852
  return this.channels.getChannelVariable(channelId, variable);
2194
1853
  }
2195
- /**
2196
- * Plays a media file to a channel.
2197
- */
2198
- async playMediaToChannel(channelId, media, options) {
2199
- return this.channels.playMedia(channelId, media, options);
2200
- }
2201
1854
  /**
2202
1855
  * Starts music on hold for a channel.
2203
1856
  */
@@ -2210,42 +1863,6 @@ var AriClient = class {
2210
1863
  async stopChannelMusicOnHold(channelId) {
2211
1864
  return this.channels.stopMusicOnHold(channelId);
2212
1865
  }
2213
- /**
2214
- * Starts playback of a media file on a channel.
2215
- */
2216
- async startChannelPlayback(channelId, media, options) {
2217
- return this.channels.startPlayback(channelId, media, options);
2218
- }
2219
- /**
2220
- * Stops playback of a media file on a channel.
2221
- */
2222
- async stopChannelPlayback(channelId, playbackId) {
2223
- return this.channels.stopPlayback(channelId, playbackId);
2224
- }
2225
- /**
2226
- * Pauses playback of a media file on a channel.
2227
- */
2228
- async pauseChannelPlayback(channelId, playbackId) {
2229
- return this.channels.pausePlayback(channelId, playbackId);
2230
- }
2231
- /**
2232
- * Resumes playback of a media file on a channel.
2233
- */
2234
- async resumeChannelPlayback(channelId, playbackId) {
2235
- return this.channels.resumePlayback(channelId, playbackId);
2236
- }
2237
- /**
2238
- * Rewinds playback of a media file on a channel.
2239
- */
2240
- async rewindChannelPlayback(channelId, playbackId, skipMs) {
2241
- return this.channels.rewindPlayback(channelId, playbackId, skipMs);
2242
- }
2243
- /**
2244
- * Fast-forwards playback of a media file on a channel.
2245
- */
2246
- async fastForwardChannelPlayback(channelId, playbackId, skipMs) {
2247
- return this.channels.fastForwardPlayback(channelId, playbackId, skipMs);
2248
- }
2249
1866
  /**
2250
1867
  * Records audio from a channel.
2251
1868
  */
@@ -2295,12 +1912,6 @@ var AriClient = class {
2295
1912
  async redirectChannel(channelId, endpoint) {
2296
1913
  return this.channels.redirectChannel(channelId, endpoint);
2297
1914
  }
2298
- /**
2299
- * Answers a channel.
2300
- */
2301
- async answerChannel(channelId) {
2302
- return this.channels.answerChannel(channelId);
2303
- }
2304
1915
  /**
2305
1916
  * Sends a ringing indication to a channel.
2306
1917
  */
@@ -2445,18 +2056,6 @@ var AriClient = class {
2445
2056
  async createChannel(data) {
2446
2057
  return this.channels.createChannel(data);
2447
2058
  }
2448
- /**
2449
- * Hangs up a specific channel.
2450
- *
2451
- * @param channelId - The unique identifier of the channel to hang up.
2452
- * @param options - Optional parameters for the hangup operation.
2453
- * @param options.reason_code - An optional reason code for the hangup.
2454
- * @param options.reason - An optional textual reason for the hangup.
2455
- * @returns A promise that resolves when the hangup operation is complete.
2456
- */
2457
- async hangup(channelId, options) {
2458
- return this.channels.hangup(channelId, options);
2459
- }
2460
2059
  /**
2461
2060
  * Originates a new channel with a specified ID using the provided originate request data.
2462
2061
  *