@ipcom/asterisk-ari 0.0.42 → 0.0.43

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.
@@ -593,7 +593,6 @@ __export(src_exports, {
593
593
  module.exports = __toCommonJS(src_exports);
594
594
 
595
595
  // src/ari-client/ariClient.ts
596
- var import_events4 = require("events");
597
596
  var import_exponential_backoff = __toESM(require_backoff(), 1);
598
597
 
599
598
  // src/ari-client/baseClient.ts
@@ -859,42 +858,15 @@ var Bridges = class {
859
858
 
860
859
  // src/ari-client/resources/channels.ts
861
860
  var import_events = require("events");
861
+
862
+ // src/ari-client/utils.ts
862
863
  function toQueryParams2(options) {
863
864
  return new URLSearchParams(
864
865
  Object.entries(options).filter(([, value]) => value !== void 0).map(([key, value]) => [key, value])
865
866
  ).toString();
866
867
  }
867
- var ChannelEventEmitter = class {
868
- eventEmitter = new import_events.EventEmitter();
869
- channel;
870
- constructor(channel) {
871
- this.channel = channel;
872
- }
873
- /**
874
- * Registra um listener para um evento no canal.
875
- */
876
- on(eventType, callback) {
877
- this.eventEmitter.on(eventType, callback);
878
- }
879
- /**
880
- * Emite um evento no canal.
881
- */
882
- emit(eventType, data) {
883
- this.eventEmitter.emit(eventType, data);
884
- }
885
- /**
886
- * Remove um listener de evento do canal.
887
- */
888
- off(eventType, callback) {
889
- this.eventEmitter.off(eventType, callback);
890
- }
891
- /**
892
- * Remove todos os listeners de um evento no canal.
893
- */
894
- removeAllListeners(eventType) {
895
- this.eventEmitter.removeAllListeners(eventType);
896
- }
897
- };
868
+
869
+ // src/ari-client/resources/channels.ts
898
870
  var ChannelInstance = class extends import_events.EventEmitter {
899
871
  constructor(client, baseClient, channelId = `channel-${Date.now()}`) {
900
872
  super();
@@ -905,7 +877,6 @@ var ChannelInstance = class extends import_events.EventEmitter {
905
877
  channelData = null;
906
878
  /**
907
879
  * Getter para o ID do canal.
908
- * Sempre retorna um ID, seja o definido manualmente ou o gerado automaticamente.
909
880
  */
910
881
  get id() {
911
882
  return this.channelId;
@@ -919,7 +890,6 @@ var ChannelInstance = class extends import_events.EventEmitter {
919
890
  }
920
891
  const channel = await this.baseClient.post("/channels", data);
921
892
  this.channelData = channel;
922
- this.emit("ChannelCreated", channel, this);
923
893
  return channel;
924
894
  }
925
895
  /**
@@ -942,14 +912,9 @@ var ChannelInstance = class extends import_events.EventEmitter {
942
912
  throw new Error("O canal ainda n\xE3o foi criado.");
943
913
  }
944
914
  await this.baseClient.delete(`/channels/${this.channelData.id}`);
945
- this.emit("ChannelHungUp", this.channelData);
946
915
  }
947
916
  /**
948
- * Toca um arquivo de mídia no canal.
949
- *
950
- * @param options - Opções para o playback, incluindo mídia e idioma.
951
- * @param playback - (Opcional) Uma instância de `PlaybackInstance` para gerenciar o playback. Se não fornecido, será criada uma nova.
952
- * @returns Uma instância de `PlaybackInstance` associada ao playback.
917
+ * Reproduz mídia no canal.
953
918
  */
954
919
  async play(options, playback) {
955
920
  if (!playback) {
@@ -957,119 +922,145 @@ var ChannelInstance = class extends import_events.EventEmitter {
957
922
  }
958
923
  await this.baseClient.post(
959
924
  `/channels/${this.channelData?.id}/play/${playback.id}`,
960
- // Agora o ID é garantido
961
925
  options
962
926
  );
963
927
  return playback;
964
928
  }
965
929
  /**
966
- * Adiciona um listener para eventos de canal.
930
+ * Reproduz mídia em um canal.
967
931
  */
968
- on(event, callback) {
969
- super.on(event, callback);
970
- return this;
932
+ async playMedia(media, options) {
933
+ if (!this.channelData) {
934
+ throw new Error("O canal ainda n\xE3o foi criado.");
935
+ }
936
+ const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
937
+ return this.baseClient.post(
938
+ `/channels/${this.channelData.id}/play${queryParams}`,
939
+ { media }
940
+ );
971
941
  }
972
942
  /**
973
- * Adiciona um listener para ser chamado apenas uma vez.
943
+ * Para a reprodução de mídia.
974
944
  */
975
- once(event, callback) {
976
- super.once(event, callback);
977
- return this;
945
+ async stopPlayback(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}`
951
+ );
978
952
  }
979
953
  /**
980
- * Remove um listener específico.
954
+ * Pausa a reprodução de mídia.
981
955
  */
982
- off(event, callback) {
983
- super.off(event, callback);
984
- return this;
985
- }
986
- };
987
- var Channels = class extends import_events.EventEmitter {
988
- constructor(baseClient, client, channelId) {
989
- super();
990
- this.baseClient = baseClient;
991
- this.client = client;
992
- this.channelId = channelId;
956
+ async pausePlayback(playbackId) {
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}/pause`
962
+ );
993
963
  }
994
964
  /**
995
- * Cria uma nova instância de `ChannelInstance` sem originar um canal físico.
965
+ * Retoma a reprodução de mídia.
996
966
  */
997
- createChannelInstance(channelId) {
998
- return new ChannelInstance(this.client, this.baseClient, channelId);
967
+ async resumePlayback(playbackId) {
968
+ if (!this.channelData?.id) {
969
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
970
+ }
971
+ await this.baseClient.delete(
972
+ `/channels/${this.channelData.id}/play/${playbackId}/pause`
973
+ );
999
974
  }
1000
975
  /**
1001
- * Origina um canal físico diretamente, sem uma instância de `ChannelInstance`.
976
+ * Retrocede a reprodução de mídia.
1002
977
  */
1003
- async originate(data) {
1004
- return this.baseClient.post("/channels", data);
978
+ async rewindPlayback(playbackId, skipMs) {
979
+ if (!this.channelData?.id) {
980
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
981
+ }
982
+ await this.baseClient.post(
983
+ `/channels/${this.channelData.id}/play/${playbackId}/rewind`,
984
+ { skipMs }
985
+ );
1005
986
  }
1006
987
  /**
1007
- * Lida com eventos relacionados ao canal e os emite para listeners registrados.
988
+ * Avança a reprodução de mídia.
1008
989
  */
1009
- emitChannelEvent(eventType, data) {
1010
- if ("channel" in data) {
1011
- const channelId = data.channel?.id;
1012
- if (channelId) {
1013
- this.emit(`${eventType}:${channelId}`, data);
1014
- }
990
+ async fastForwardPlayback(playbackId, skipMs) {
991
+ if (!this.channelData?.id) {
992
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1015
993
  }
1016
- this.emit(eventType, data);
994
+ await this.baseClient.post(
995
+ `/channels/${this.channelData.id}/play/${playbackId}/forward`,
996
+ { skipMs }
997
+ );
1017
998
  }
1018
999
  /**
1019
- * Registra um listener para eventos de canal específicos.
1000
+ * Muta o canal.
1020
1001
  */
1021
- registerChannelListener(eventType, channelId, callback) {
1022
- this.on(`${eventType}:${channelId}`, callback);
1002
+ async muteChannel(direction = "both") {
1003
+ if (!this.channelData?.id) {
1004
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1005
+ }
1006
+ await this.baseClient.post(
1007
+ `/channels/${this.channelData.id}/mute?direction=${direction}`
1008
+ );
1023
1009
  }
1024
1010
  /**
1025
- * Remove um listener específico de eventos de canal.
1011
+ * Desmuta o canal.
1026
1012
  */
1027
- unregisterChannelListener(eventType, channelId, callback) {
1028
- this.off(`${eventType}:${channelId}`, callback);
1013
+ async unmuteChannel(direction = "both") {
1014
+ if (!this.channelData?.id) {
1015
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1016
+ }
1017
+ await this.baseClient.delete(
1018
+ `/channels/${this.channelData.id}/mute?direction=${direction}`
1019
+ );
1029
1020
  }
1030
1021
  /**
1031
- * Verifica se um listener já está registrado para um evento de canal.
1022
+ * Coloca o canal em espera.
1032
1023
  */
1033
- isChannelListenerRegistered(eventType, channelId) {
1034
- return this.listenerCount(`${eventType}:${channelId}`) > 0;
1024
+ async holdChannel() {
1025
+ if (!this.channelData?.id) {
1026
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1027
+ }
1028
+ await this.baseClient.post(`/channels/${this.channelData.id}/hold`);
1035
1029
  }
1036
1030
  /**
1037
- * Lista todos os canais ativos.
1031
+ * Remove o canal da espera.
1038
1032
  */
1039
- async list() {
1040
- const channels = await this.baseClient.get("/channels");
1041
- if (!Array.isArray(channels)) {
1042
- throw new Error("Resposta da API /channels n\xE3o \xE9 um array.");
1033
+ async unholdChannel() {
1034
+ if (!this.channelData?.id) {
1035
+ throw new Error("Canal n\xE3o associado a esta inst\xE2ncia.");
1043
1036
  }
1044
- return channels;
1037
+ await this.baseClient.delete(`/channels/${this.channelData.id}/hold`);
1045
1038
  }
1046
- /**
1047
- * Obtém detalhes de um canal específico.
1048
- */
1049
- async getDetails(channelId) {
1050
- return this.baseClient.get(`/channels/${channelId}`);
1039
+ };
1040
+ var Channels = class extends import_events.EventEmitter {
1041
+ constructor(baseClient, client) {
1042
+ super();
1043
+ this.baseClient = baseClient;
1044
+ this.client = client;
1045
+ }
1046
+ createChannelInstance(channelId) {
1047
+ return new ChannelInstance(this.client, this.baseClient, channelId);
1051
1048
  }
1052
1049
  /**
1053
- * Reproduz mídia em um canal.
1050
+ * Origina um canal físico diretamente, sem uma instância de `ChannelInstance`.
1054
1051
  */
1055
- async playMedia(channelId, media, options) {
1056
- const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
1057
- return this.baseClient.post(
1058
- `/channels/${channelId}/play${queryParams}`,
1059
- { media }
1060
- );
1052
+ async originate(data) {
1053
+ return this.baseClient.post("/channels", data);
1061
1054
  }
1062
1055
  /**
1063
- * Encerra um canal específico.
1056
+ * Lista todos os canais ativos.
1064
1057
  */
1065
- async hangup(channelId, options) {
1066
- const queryParams = new URLSearchParams({
1067
- ...options?.reason_code && { reason_code: options.reason_code },
1068
- ...options?.reason && { reason: options.reason }
1069
- });
1070
- return this.baseClient.delete(
1071
- `/channels/${channelId}?${queryParams.toString()}`
1072
- );
1058
+ async list() {
1059
+ const channels = await this.baseClient.get("/channels");
1060
+ if (!Array.isArray(channels)) {
1061
+ throw new Error("Resposta da API /channels n\xE3o \xE9 um array.");
1062
+ }
1063
+ return channels;
1073
1064
  }
1074
1065
  /**
1075
1066
  * Inicia a escuta em um canal.
@@ -1092,38 +1083,30 @@ var Channels = class extends import_events.EventEmitter {
1092
1083
  );
1093
1084
  }
1094
1085
  async createExternalMedia(options) {
1095
- const queryParams = new URLSearchParams(options);
1086
+ const queryParams = toQueryParams2(options);
1096
1087
  return this.baseClient.post(
1097
- `/channels/externalMedia?${queryParams.toString()}`
1088
+ `/channels/externalMedia?${queryParams}`
1098
1089
  );
1099
1090
  }
1100
1091
  async playWithId(channelId, playbackId, media, options) {
1101
- const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
1092
+ const queryParams = options ? `?${toQueryParams2(options)}` : "";
1102
1093
  return this.baseClient.post(
1103
1094
  `/channels/${channelId}/play/${playbackId}${queryParams}`,
1104
1095
  { media }
1105
1096
  );
1106
1097
  }
1107
1098
  async snoopChannelWithId(channelId, snoopId, options) {
1108
- const queryParams = new URLSearchParams(options);
1099
+ const queryParams = toQueryParams2(options);
1109
1100
  return this.baseClient.post(
1110
- `/channels/${channelId}/snoop/${snoopId}?${queryParams.toString()}`
1101
+ `/channels/${channelId}/snoop/${snoopId}?${queryParams}`
1111
1102
  );
1112
1103
  }
1113
1104
  async startMohWithClass(channelId, mohClass) {
1114
1105
  const queryParams = `mohClass=${encodeURIComponent(mohClass)}`;
1115
- return this.baseClient.post(
1106
+ await this.baseClient.post(
1116
1107
  `/channels/${channelId}/moh?${queryParams}`
1117
1108
  );
1118
1109
  }
1119
- /**
1120
- * Gets the value of a channel variable or function.
1121
- *
1122
- * @param channelId - The ID of the channel.
1123
- * @param variable - The name of the channel variable or function to retrieve.
1124
- * @returns A promise that resolves to the value of the variable.
1125
- * @throws Will throw an error if the variable is missing or the channel is not found.
1126
- */
1127
1110
  async getChannelVariable(channelId, variable) {
1128
1111
  if (!variable) {
1129
1112
  throw new Error("The 'variable' parameter is required.");
@@ -1132,15 +1115,6 @@ var Channels = class extends import_events.EventEmitter {
1132
1115
  `/channels/${channelId}/variable?variable=${encodeURIComponent(variable)}`
1133
1116
  );
1134
1117
  }
1135
- /**
1136
- * Sets the value of a channel variable or function.
1137
- *
1138
- * @param channelId - The ID of the channel.
1139
- * @param variable - The name of the channel variable or function to set.
1140
- * @param value - The value to set the variable to.
1141
- * @returns A promise that resolves when the variable is successfully set.
1142
- * @throws Will throw an error if the variable is missing or the channel is not found.
1143
- */
1144
1118
  async setChannelVariable(channelId, variable, value) {
1145
1119
  if (!variable) {
1146
1120
  throw new Error("The 'variable' parameter is required.");
@@ -1150,199 +1124,83 @@ var Channels = class extends import_events.EventEmitter {
1150
1124
  ...value && { value }
1151
1125
  });
1152
1126
  await this.baseClient.post(
1153
- `/channels/${channelId}/variable?${queryParams.toString()}`
1127
+ `/channels/${channelId}/variable?${queryParams}`
1154
1128
  );
1155
1129
  }
1156
- /**
1157
- * Moves the channel to another Stasis application.
1158
- */
1159
1130
  async moveToApplication(channelId, app, appArgs) {
1160
- return this.baseClient.post(`/channels/${channelId}/move`, {
1131
+ await this.baseClient.post(`/channels/${channelId}/move`, {
1161
1132
  app,
1162
1133
  appArgs
1163
1134
  });
1164
1135
  }
1165
- /**
1166
- * Continues the dialplan for a specific channel.
1167
- */
1168
1136
  async continueDialplan(channelId, context, extension, priority, label) {
1169
- return this.baseClient.post(`/channels/${channelId}/continue`, {
1137
+ await this.baseClient.post(`/channels/${channelId}/continue`, {
1170
1138
  context,
1171
1139
  extension,
1172
1140
  priority,
1173
1141
  label
1174
1142
  });
1175
1143
  }
1176
- /**
1177
- * Stops music on hold (MOH) for a channel.
1178
- */
1179
1144
  async stopMusicOnHold(channelId) {
1180
- return this.baseClient.delete(`/channels/${channelId}/moh`);
1145
+ await this.baseClient.delete(`/channels/${channelId}/moh`);
1181
1146
  }
1182
- /**
1183
- * Starts music on hold (MOH) for a channel.
1184
- */
1185
1147
  async startMusicOnHold(channelId) {
1186
- return this.baseClient.post(`/channels/${channelId}/moh`);
1187
- }
1188
- /**
1189
- * Starts playback of a media file on a channel.
1190
- */
1191
- /**
1192
- * Starts playback of a media file on a channel.
1193
- */
1194
- async startPlayback(channelId, media, options) {
1195
- const queryParams = options ? `?${new URLSearchParams(options).toString()}` : "";
1196
- return this.baseClient.post(
1197
- `/channels/${channelId}/play${queryParams}`,
1198
- { media }
1199
- );
1200
- }
1201
- /**
1202
- * Stops playback of a media file on a channel.
1203
- */
1204
- async stopPlayback(channelId, playbackId) {
1205
- return this.baseClient.delete(
1206
- `/channels/${channelId}/play/${playbackId}`
1207
- );
1208
- }
1209
- /**
1210
- * Pauses playback of a media file on a channel.
1211
- */
1212
- async pausePlayback(channelId, playbackId) {
1213
- return this.baseClient.post(
1214
- `/channels/${channelId}/play/${playbackId}/pause`
1215
- );
1148
+ await this.baseClient.post(`/channels/${channelId}/moh`);
1216
1149
  }
1217
- /**
1218
- * Resumes playback of a media file on a channel.
1219
- */
1220
- async resumePlayback(channelId, playbackId) {
1221
- return this.baseClient.delete(
1222
- `/channels/${channelId}/play/${playbackId}/pause`
1223
- );
1224
- }
1225
- /**
1226
- * Rewinds playback of a media file on a channel.
1227
- */
1228
- async rewindPlayback(channelId, playbackId, skipMs) {
1229
- return this.baseClient.post(
1230
- `/channels/${channelId}/play/${playbackId}/rewind`,
1231
- { skipMs }
1232
- );
1233
- }
1234
- /**
1235
- * Fast-forwards playback of a media file on a channel.
1236
- */
1237
- async fastForwardPlayback(channelId, playbackId, skipMs) {
1238
- return this.baseClient.post(
1239
- `/channels/${channelId}/play/${playbackId}/forward`,
1240
- { skipMs }
1241
- );
1242
- }
1243
- /**
1244
- * Records audio from a channel.
1245
- */
1246
1150
  async record(channelId, options) {
1247
- const queryParams = new URLSearchParams(
1248
- Object.entries(options).filter(
1249
- ([, value]) => value !== void 0
1250
- )
1251
- );
1151
+ const queryParams = toQueryParams2(options);
1252
1152
  return this.baseClient.post(
1253
- `/channels/${channelId}/record?${queryParams.toString()}`
1153
+ `/channels/${channelId}/record?${queryParams}`
1254
1154
  );
1255
1155
  }
1256
- /**
1257
- * Dials a created channel.
1258
- */
1259
1156
  async dial(channelId, caller, timeout) {
1260
1157
  const queryParams = new URLSearchParams({
1261
1158
  ...caller && { caller },
1262
1159
  ...timeout && { timeout: timeout.toString() }
1263
1160
  });
1264
- return this.baseClient.post(
1265
- `/channels/${channelId}/dial?${queryParams.toString()}`
1161
+ await this.baseClient.post(
1162
+ `/channels/${channelId}/dial?${queryParams}`
1266
1163
  );
1267
1164
  }
1268
- /**
1269
- * Redirects the channel to a different location.
1270
- */
1271
1165
  async redirectChannel(channelId, endpoint) {
1272
- return this.baseClient.post(
1166
+ await this.baseClient.post(
1273
1167
  `/channels/${channelId}/redirect?endpoint=${encodeURIComponent(endpoint)}`
1274
1168
  );
1275
1169
  }
1276
- /**
1277
- * Answers a channel.
1278
- */
1279
1170
  async answerChannel(channelId) {
1280
- return this.baseClient.post(`/channels/${channelId}/answer`);
1171
+ await this.baseClient.post(`/channels/${channelId}/answer`);
1281
1172
  }
1282
- /**
1283
- * Sends a ringing indication to a channel.
1284
- */
1285
1173
  async ringChannel(channelId) {
1286
- return this.baseClient.post(`/channels/${channelId}/ring`);
1174
+ await this.baseClient.post(`/channels/${channelId}/ring`);
1287
1175
  }
1288
- /**
1289
- * Stops ringing indication on a channel.
1290
- */
1291
1176
  async stopRingChannel(channelId) {
1292
- return this.baseClient.delete(`/channels/${channelId}/ring`);
1177
+ await this.baseClient.delete(`/channels/${channelId}/ring`);
1293
1178
  }
1294
- /**
1295
- * Sends DTMF to a channel.
1296
- */
1297
1179
  async sendDTMF(channelId, dtmf, options) {
1298
- const queryParams = new URLSearchParams({
1299
- dtmf,
1300
- ...options?.before && { before: options.before.toString() },
1301
- ...options?.between && { between: options.between.toString() },
1302
- ...options?.duration && { duration: options.duration.toString() },
1303
- ...options?.after && { after: options.after.toString() }
1304
- });
1305
- return this.baseClient.post(
1306
- `/channels/${channelId}/dtmf?${queryParams.toString()}`
1180
+ const queryParams = toQueryParams2({ dtmf, ...options });
1181
+ await this.baseClient.post(
1182
+ `/channels/${channelId}/dtmf?${queryParams}`
1307
1183
  );
1308
1184
  }
1309
- /**
1310
- * Mutes a channel.
1311
- */
1312
1185
  async muteChannel(channelId, direction = "both") {
1313
- return this.baseClient.post(
1186
+ await this.baseClient.post(
1314
1187
  `/channels/${channelId}/mute?direction=${direction}`
1315
1188
  );
1316
1189
  }
1317
- /**
1318
- * Unmutes a channel.
1319
- */
1320
1190
  async unmuteChannel(channelId, direction = "both") {
1321
- return this.baseClient.delete(
1191
+ await this.baseClient.delete(
1322
1192
  `/channels/${channelId}/mute?direction=${direction}`
1323
1193
  );
1324
1194
  }
1325
- /**
1326
- * Puts a channel on hold.
1327
- */
1328
1195
  async holdChannel(channelId) {
1329
- return this.baseClient.post(`/channels/${channelId}/hold`);
1196
+ await this.baseClient.post(`/channels/${channelId}/hold`);
1330
1197
  }
1331
- /**
1332
- * Removes a channel from hold.
1333
- */
1334
1198
  async unholdChannel(channelId) {
1335
- return this.baseClient.delete(`/channels/${channelId}/hold`);
1199
+ await this.baseClient.delete(`/channels/${channelId}/hold`);
1336
1200
  }
1337
- /**
1338
- * Creates a channel and places it in a Stasis app without dialing it.
1339
- */
1340
1201
  async createChannel(data) {
1341
1202
  return this.baseClient.post("/channels/create", data);
1342
1203
  }
1343
- /**
1344
- * Creates a new channel with a specific ID and originates a call.
1345
- */
1346
1204
  async originateWithId(channelId, data) {
1347
1205
  return this.baseClient.post(`/channels/${channelId}`, data);
1348
1206
  }
@@ -1601,6 +1459,7 @@ var WebSocketClient = class extends import_events3.EventEmitter {
1601
1459
  ws = null;
1602
1460
  isClosedManually = false;
1603
1461
  isReconnecting = false;
1462
+ messageListeners = [];
1604
1463
  /**
1605
1464
  * Establishes a connection to the WebSocket server.
1606
1465
  * @returns A Promise that resolves when the connection is established, or rejects if an error occurs.
@@ -1637,6 +1496,9 @@ var WebSocketClient = class extends import_events3.EventEmitter {
1637
1496
  isConnected() {
1638
1497
  return this.ws?.readyState === import_ws.default.OPEN;
1639
1498
  }
1499
+ onMessage(callback) {
1500
+ this.messageListeners.push(callback);
1501
+ }
1640
1502
  /**
1641
1503
  * Adds a listener for WebSocket events.
1642
1504
  * @param event - The event type to listen for.
@@ -1704,6 +1566,7 @@ var WebSocketClient = class extends import_events3.EventEmitter {
1704
1566
  if (this.ws) {
1705
1567
  this.isClosedManually = true;
1706
1568
  this.ws.close();
1569
+ this.ws = null;
1707
1570
  console.log("WebSocket fechado manualmente.");
1708
1571
  }
1709
1572
  }
@@ -1725,15 +1588,14 @@ var AriClient = class {
1725
1588
  this.asterisk = new Asterisk(this.baseClient);
1726
1589
  this.bridges = new Bridges(this.baseClient);
1727
1590
  }
1591
+ eventListeners = /* @__PURE__ */ new Map();
1728
1592
  wsClient = null;
1729
- channelEmitters = /* @__PURE__ */ new Map();
1730
1593
  baseClient;
1731
1594
  isReconnecting = false;
1732
- eventEmitter = new import_events4.EventEmitter();
1733
- wsConnections = /* @__PURE__ */ new Map();
1734
1595
  isWebSocketConnectedFlag = false;
1735
1596
  webSocketReady = null;
1736
1597
  // Promise para rastrear o estado do WebSocket
1598
+ channelInstances = /* @__PURE__ */ new Map();
1737
1599
  pendingListeners = [];
1738
1600
  processPendingListeners() {
1739
1601
  if (!this.wsClient || !this.isWebSocketConnectedFlag) {
@@ -1758,6 +1620,41 @@ var AriClient = class {
1758
1620
  sounds;
1759
1621
  asterisk;
1760
1622
  bridges;
1623
+ /**
1624
+ * Type guard to check if the given data object contains a valid channel property.
1625
+ * This function is used to narrow down the type of the data object and ensure it has a channel with an id.
1626
+ *
1627
+ * @param data - The object to be checked for the presence of a channel property.
1628
+ * @returns A type predicate indicating whether the data object contains a valid channel.
1629
+ * Returns true if the data object has a channel property with an id, false otherwise.
1630
+ */
1631
+ hasChannel(data) {
1632
+ return data?.channel?.id !== void 0;
1633
+ }
1634
+ // Método para criar uma instância de ChannelInstance
1635
+ createChannelInstance(channelId) {
1636
+ return this.channels.createChannelInstance(channelId);
1637
+ }
1638
+ handleWebSocketEvent(event) {
1639
+ const { type, ...data } = event;
1640
+ if (this.hasChannel(data)) {
1641
+ const channelId = data.channel.id;
1642
+ if (channelId) {
1643
+ if (!this.channelInstances.has(channelId)) {
1644
+ const channelInstance2 = this.createChannelInstance(channelId);
1645
+ this.channelInstances.set(channelId, channelInstance2);
1646
+ }
1647
+ const channelInstance = this.channelInstances.get(channelId);
1648
+ if (channelInstance) {
1649
+ data.channel = { ...data.channel, ...channelInstance };
1650
+ }
1651
+ }
1652
+ }
1653
+ const listener = this.eventListeners.get(type);
1654
+ if (listener) {
1655
+ listener(data);
1656
+ }
1657
+ }
1761
1658
  /**
1762
1659
  * Connects to the ARI WebSocket for a specific application.
1763
1660
  * This function establishes a WebSocket connection to the Asterisk ARI, sets up event listeners,
@@ -1843,18 +1740,6 @@ var AriClient = class {
1843
1740
  `WebSocket client para o app '${app}' n\xE3o est\xE1 conectado.`
1844
1741
  );
1845
1742
  }
1846
- wsClient.on("ChannelDestroyed", (data) => {
1847
- if (data.type === "ChannelDestroyed" && "channel" in data) {
1848
- console.log(`[${app}] Canal destru\xEDdo: ${data.channel.id}`);
1849
- this.removeChannel(data.channel.id);
1850
- }
1851
- });
1852
- wsClient.on("StasisEnd", (data) => {
1853
- if (data.type === "StasisEnd" && "channel" in data) {
1854
- console.log(`[${app}] StasisEnd para o canal: ${data.channel.id}`);
1855
- this.removeChannel(data.channel.id);
1856
- }
1857
- });
1858
1743
  const eventHandlers = {
1859
1744
  PlaybackStarted: (data) => {
1860
1745
  if ("playbackId" in data) {
@@ -1889,100 +1774,6 @@ var AriClient = class {
1889
1774
  }
1890
1775
  console.log(`[${app}] Todos os eventos do WebSocket foram registrados.`);
1891
1776
  }
1892
- /**
1893
- * Registra um listener para eventos globais.
1894
- * @param eventType
1895
- * @param callback - A função a ser executada quando um evento global for recebido.
1896
- */
1897
- onGlobalEvent(eventType, callback) {
1898
- this.eventEmitter.on(eventType, callback);
1899
- }
1900
- /**
1901
- * Remove um listener para eventos globais.
1902
- * @param callback - A função a ser removida dos eventos globais.
1903
- */
1904
- offGlobalEvent(callback) {
1905
- this.eventEmitter.off("globalEvent", callback);
1906
- }
1907
- /**
1908
- * Emite um evento global.
1909
- * @param data - Os dados do evento a serem emitidos.
1910
- */
1911
- emitGlobalEvent(data) {
1912
- this.eventEmitter.emit("globalEvent", data);
1913
- }
1914
- /**
1915
- * Unregisters a listener for playback events.
1916
- *
1917
- * This method removes a specific listener registered for a playback event type,
1918
- * ensuring that no further notifications are sent to the callback function.
1919
- *
1920
- * @param eventType - The type of event to stop listening for.
1921
- * @param playbackId - The unique ID of the playback associated with the listener.
1922
- * @param callback - The callback function to remove from the listener.
1923
- */
1924
- unregisterPlaybackListener(eventType, playbackId, callback) {
1925
- this.playbacks.unregisterListener(eventType, playbackId, callback);
1926
- }
1927
- registerListener(eventType, condition, callback) {
1928
- if (!this.isWebSocketConnected()) {
1929
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1930
- }
1931
- const handler = (eventData) => {
1932
- if (eventData.type === eventType && condition(eventData)) {
1933
- callback(eventData);
1934
- }
1935
- };
1936
- this.wsClient?.on(eventType, handler);
1937
- }
1938
- /**
1939
- * Registers a listener for playback events.
1940
- * The listener is triggered for events such as "PlaybackFinished".
1941
- *
1942
- * @param eventType - The type of event to listen for.
1943
- * @param playbackId - The ID of the playback to associate with this listener.
1944
- * @param callback - The callback function to execute when the event occurs.
1945
- */
1946
- registerPlaybackListener(eventType, playbackId, callback) {
1947
- if (!this.isWebSocketConnected()) {
1948
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1949
- }
1950
- console.log(
1951
- `Registrando listener para evento ${eventType} com playbackId ${playbackId}`
1952
- );
1953
- const handler = (eventData) => {
1954
- if ("playbackId" in eventData && eventData.playbackId === playbackId) {
1955
- callback(eventData);
1956
- }
1957
- };
1958
- this.wsClient?.on(eventType, handler);
1959
- }
1960
- registerChannelListener(eventType, channelId, callback) {
1961
- if (!this.isWebSocketConnected()) {
1962
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1963
- }
1964
- console.log(
1965
- `Registrando listener para evento ${eventType} com channelId ${channelId}`
1966
- );
1967
- const handler = (eventData) => {
1968
- if (eventData.type === eventType && "channel" in eventData && eventData.channel?.id === channelId) {
1969
- callback(
1970
- eventData
1971
- );
1972
- }
1973
- };
1974
- this.wsClient?.on(eventType, handler);
1975
- }
1976
- /**
1977
- * Checks if a listener is already registered for a specific event and playback.
1978
- *
1979
- * @param eventType - The type of event to check.
1980
- * @param playbackId - The playback ID associated with the listener.
1981
- * @returns True if a listener is already registered, false otherwise.
1982
- */
1983
- isPlaybackListenerRegistered(eventType, playbackId) {
1984
- return this.playbacks.isListenerRegistered(eventType, playbackId);
1985
- }
1986
1777
  /**
1987
1778
  * Ensures the ARI application is registered.
1988
1779
  *
@@ -2013,69 +1804,6 @@ var AriClient = class {
2013
1804
  isWebSocketConnected() {
2014
1805
  return this.wsClient ? this.wsClient.isConnected() : false;
2015
1806
  }
2016
- /**
2017
- * Registers a listener for WebSocket events.
2018
- *
2019
- * This function allows you to attach a callback function to a specific WebSocket event type.
2020
- * The callback will be executed whenever an event of the specified type is received.
2021
- *
2022
- * @template T - The type of WebSocket event, extending WebSocketEvent["type"].
2023
- * @param {T} event - The type of WebSocket event to listen for.
2024
- * @param {(data: Extract<WebSocketEvent, { type: T }>) => void} callback - The function to be called when the event is received.
2025
- * The callback receives the event data as its parameter.
2026
- * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
2027
- * @returns {void} This function doesn't return a value.
2028
- */
2029
- async onWebSocketEvent(event, callback) {
2030
- if (this.webSocketReady) {
2031
- console.log(`Aguardando WebSocket conectar antes de registrar: ${event}`);
2032
- await this.webSocketReady;
2033
- }
2034
- if (!this.wsClient || !this.isWebSocketConnectedFlag) {
2035
- throw new Error("WebSocket ainda n\xE3o est\xE1 conectado.");
2036
- }
2037
- console.log(`Registrando listener para evento: ${event}`);
2038
- this.wsClient.on(event, callback);
2039
- }
2040
- /**
2041
- * Removes a specific listener for WebSocket events.
2042
- *
2043
- * This function unregisters a previously registered callback function for a specific WebSocket event type.
2044
- * It's useful for removing event handlers when they are no longer needed or for cleaning up resources.
2045
- *
2046
- * @template T - The type of WebSocket event, extending WebSocketEvent["type"].
2047
- * @param {T} event - The type of WebSocket event to remove the listener from.
2048
- * @param {(data: Extract<WebSocketEvent, { type: T }>) => void} callback - The callback function to be removed.
2049
- * This should be the same function reference that was used when adding the event listener.
2050
- * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
2051
- * @returns {void} This function doesn't return a value.
2052
- */
2053
- offWebSocketEvent(event, callback) {
2054
- if (!this.wsClient) {
2055
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
2056
- }
2057
- this.wsClient.off(event, callback);
2058
- }
2059
- /**
2060
- * Removes all listeners for a specific WebSocket event type.
2061
- *
2062
- * This function removes all event listeners that have been registered for a particular
2063
- * WebSocket event type. It's useful for cleaning up event listeners when they are no
2064
- * longer needed or before re-registering new listeners.
2065
- *
2066
- * @param event - The type of WebSocket event for which all listeners should be removed.
2067
- * This should be a string identifying the event type (e.g., 'message', 'close', etc.).
2068
- *
2069
- * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
2070
- *
2071
- * @returns {void} This function doesn't return a value.
2072
- */
2073
- removeAllWebSocketListeners(event) {
2074
- if (!this.wsClient) {
2075
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
2076
- }
2077
- this.wsClient.removeAllListeners(event);
2078
- }
2079
1807
  /**
2080
1808
  * Closes the WebSocket connection and removes all associated listeners.
2081
1809
  *
@@ -2092,69 +1820,6 @@ var AriClient = class {
2092
1820
  this.wsClient = null;
2093
1821
  }
2094
1822
  }
2095
- /**
2096
- * Obtém ou cria um emissor de eventos para o canal especificado.
2097
- */
2098
- getOrCreateChannelEmitter(channel) {
2099
- if (!this.channelEmitters.has(channel.id)) {
2100
- this.channelEmitters.set(channel.id, new ChannelEventEmitter(channel));
2101
- }
2102
- return this.channelEmitters.get(channel.id);
2103
- }
2104
- handleChannelEvent(event) {
2105
- if ("channel" in event && event.channel) {
2106
- const channelEmitter = this.channelEmitters.get(event.channel.id);
2107
- if (channelEmitter) {
2108
- channelEmitter.emit(event.type, event);
2109
- } else {
2110
- console.warn(
2111
- `Nenhum listener registrado para o canal ${event.channel.id}`
2112
- );
2113
- }
2114
- }
2115
- }
2116
- registerGlobalWebSocketListener() {
2117
- this.wsClient?.on("message", (event) => {
2118
- if ("channel" in event && event.channel) {
2119
- this.handleChannelEvent(event);
2120
- } else {
2121
- this.eventEmitter.emit(event.type, event);
2122
- }
2123
- });
2124
- }
2125
- /**
2126
- * Adiciona um listener para um evento específico de canal.
2127
- */
2128
- onChannelEvent(channelId, eventType, callback) {
2129
- const channelEmitter = this.channelEmitters.get(channelId);
2130
- if (!channelEmitter) {
2131
- throw new Error(`Canal com ID ${channelId} n\xE3o encontrado.`);
2132
- }
2133
- channelEmitter.on(eventType, callback);
2134
- console.log(
2135
- `Listener registrado para o canal ${channelId} e evento ${eventType}`
2136
- );
2137
- }
2138
- removeChannel(channelId) {
2139
- const channelEmitter = this.channelEmitters.get(channelId);
2140
- if (channelEmitter) {
2141
- channelEmitter.removeAllListeners();
2142
- this.channelEmitters.delete(channelId);
2143
- console.log(`Listeners para o canal ${channelId} foram removidos.`);
2144
- } else {
2145
- console.warn(`Nenhum listener encontrado para o canal ${channelId}.`);
2146
- }
2147
- }
2148
- /**
2149
- * Remove um listener para um evento específico de canal.
2150
- */
2151
- offChannelEvent(channelId, eventType, callback) {
2152
- const channelEmitter = this.channelEmitters.get(channelId);
2153
- if (!channelEmitter) {
2154
- throw new Error(`Canal com ID ${channelId} n\xE3o encontrado.`);
2155
- }
2156
- channelEmitter.off(eventType, callback);
2157
- }
2158
1823
  /**
2159
1824
  * Retrieves a list of active channels from the Asterisk ARI.
2160
1825
  *
@@ -2172,18 +1837,6 @@ var AriClient = class {
2172
1837
  async originateChannel(data) {
2173
1838
  return this.channels.originate(data);
2174
1839
  }
2175
- /**
2176
- * Retrieves details of a specific channel.
2177
- */
2178
- async getChannelDetails(channelId) {
2179
- return this.channels.getDetails(channelId);
2180
- }
2181
- /**
2182
- * Hangs up a specific channel.
2183
- */
2184
- async hangupChannel(channelId) {
2185
- return this.channels.hangup(channelId);
2186
- }
2187
1840
  /**
2188
1841
  * Continues the dialplan for a specific channel.
2189
1842
  */
@@ -2214,12 +1867,6 @@ var AriClient = class {
2214
1867
  async getChannelVariable(channelId, variable) {
2215
1868
  return this.channels.getChannelVariable(channelId, variable);
2216
1869
  }
2217
- /**
2218
- * Plays a media file to a channel.
2219
- */
2220
- async playMediaToChannel(channelId, media, options) {
2221
- return this.channels.playMedia(channelId, media, options);
2222
- }
2223
1870
  /**
2224
1871
  * Starts music on hold for a channel.
2225
1872
  */
@@ -2232,42 +1879,6 @@ var AriClient = class {
2232
1879
  async stopChannelMusicOnHold(channelId) {
2233
1880
  return this.channels.stopMusicOnHold(channelId);
2234
1881
  }
2235
- /**
2236
- * Starts playback of a media file on a channel.
2237
- */
2238
- async startChannelPlayback(channelId, media, options) {
2239
- return this.channels.startPlayback(channelId, media, options);
2240
- }
2241
- /**
2242
- * Stops playback of a media file on a channel.
2243
- */
2244
- async stopChannelPlayback(channelId, playbackId) {
2245
- return this.channels.stopPlayback(channelId, playbackId);
2246
- }
2247
- /**
2248
- * Pauses playback of a media file on a channel.
2249
- */
2250
- async pauseChannelPlayback(channelId, playbackId) {
2251
- return this.channels.pausePlayback(channelId, playbackId);
2252
- }
2253
- /**
2254
- * Resumes playback of a media file on a channel.
2255
- */
2256
- async resumeChannelPlayback(channelId, playbackId) {
2257
- return this.channels.resumePlayback(channelId, playbackId);
2258
- }
2259
- /**
2260
- * Rewinds playback of a media file on a channel.
2261
- */
2262
- async rewindChannelPlayback(channelId, playbackId, skipMs) {
2263
- return this.channels.rewindPlayback(channelId, playbackId, skipMs);
2264
- }
2265
- /**
2266
- * Fast-forwards playback of a media file on a channel.
2267
- */
2268
- async fastForwardChannelPlayback(channelId, playbackId, skipMs) {
2269
- return this.channels.fastForwardPlayback(channelId, playbackId, skipMs);
2270
- }
2271
1882
  /**
2272
1883
  * Records audio from a channel.
2273
1884
  */
@@ -2317,12 +1928,6 @@ var AriClient = class {
2317
1928
  async redirectChannel(channelId, endpoint) {
2318
1929
  return this.channels.redirectChannel(channelId, endpoint);
2319
1930
  }
2320
- /**
2321
- * Answers a channel.
2322
- */
2323
- async answerChannel(channelId) {
2324
- return this.channels.answerChannel(channelId);
2325
- }
2326
1931
  /**
2327
1932
  * Sends a ringing indication to a channel.
2328
1933
  */
@@ -2467,18 +2072,6 @@ var AriClient = class {
2467
2072
  async createChannel(data) {
2468
2073
  return this.channels.createChannel(data);
2469
2074
  }
2470
- /**
2471
- * Hangs up a specific channel.
2472
- *
2473
- * @param channelId - The unique identifier of the channel to hang up.
2474
- * @param options - Optional parameters for the hangup operation.
2475
- * @param options.reason_code - An optional reason code for the hangup.
2476
- * @param options.reason - An optional textual reason for the hangup.
2477
- * @returns A promise that resolves when the hangup operation is complete.
2478
- */
2479
- async hangup(channelId, options) {
2480
- return this.channels.hangup(channelId, options);
2481
- }
2482
2075
  /**
2483
2076
  * Originates a new channel with a specified ID using the provided originate request data.
2484
2077
  *