@whanext/core 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.17.0
4
+
5
+ ### Adicionado
6
+
7
+ - Novo evento público `messageEdited` em `app.on()` e `multi.on()`.
8
+ - Novo tipo `MessageEdited`, com versão anterior quando ainda estiver no cache, versão atual, identidade responsável e horário da edição.
9
+ - O provider Baileys passa a interpretar atualizações `editedMessage` recebidas em `messages.update`.
10
+ - O cache recente é atualizado após cada edição, permitindo acompanhar múltiplas alterações da mesma mensagem em sequência.
11
+
12
+ ### Compatibilidade
13
+
14
+ - A mudança é aditiva para consumidores da API pública.
15
+ - Providers customizados passam a incluir `messageEdited` em `ProviderEvents`.
16
+ - Quando a versão anterior já saiu do cache, o evento continua sendo emitido sem o campo `previous`.
17
+
18
+
19
+ ## 0.16.0
20
+
21
+ ### Adicionado
22
+
23
+ - Novo evento público `messageDeleted` em `app.on()` e `multi.on()`.
24
+ - Novo tipo `MessageDeleted`, com chave da mensagem, payload original quando disponível, autor da revogação e horário da exclusão.
25
+ - O provider Baileys passa a observar `messages.update` e reconhecer revogações sem expor tipos do Baileys à aplicação.
26
+ - Mensagens revogadas permanecem no cache recente, permitindo `app.message.repost()` e `app.media.download()` enquanto a entrada estiver disponível.
27
+
28
+ ### Compatibilidade
29
+
30
+ - A mudança é aditiva para consumidores da API pública.
31
+ - Providers customizados passam a incluir `messageDeleted` em `ProviderEvents`.
32
+ - Quando a mensagem original já saiu do cache, o evento continua sendo emitido sem o campo `message`.
3
33
 
4
34
  ## 0.15.0
5
35
 
package/README.md CHANGED
@@ -37,7 +37,7 @@ await app.login({
37
37
  - Prefixo global e comandos declarativos com argumentos tipados.
38
38
  - Comandos exclusivos da conta conectada com `guards.owner()` ou `onlyOwner`.
39
39
  - Usuários normalizados entre JID, LID e PN.
40
- - Mensagens, replies, edição, exclusão, menções, mídias e download normalizado.
40
+ - Mensagens, replies, edição, exclusão, revogações, menções, mídias e download normalizado.
41
41
  - Operações de grupos e membros com resultados idempotentes.
42
42
  - Cache de metadados transparente e substituível.
43
43
  - Mute permanente ou temporário com SQLite ou banco próprio.
@@ -159,6 +159,34 @@ if (principal?.isReady) {
159
159
 
160
160
  `multi.commands.command()`, `use()`, `onError()` e `load()` aplicam a mesma configuração de comandos a todas as contas. Dentro de um comando, `ctx.account.id` informa qual conta recebeu e executou aquela interação. Eventos também podem ser observados em conjunto com `multi.on()`.
161
161
 
162
+ ## Mensagens apagadas
163
+
164
+ Revogações recebidas pelo WhatsApp são expostas pelo evento `messageDeleted`. Quando a mensagem original ainda estiver no cache recente, o payload inclui `message`, que pode ser republicada ou usada para baixar a mídia pelas APIs existentes.
165
+
166
+ ```ts
167
+ app.on('messageDeleted', async ({ message, deletedByMe }) => {
168
+ if (!message || deletedByMe) return;
169
+
170
+ await app.message.repost(message, app.account.selfChatId);
171
+ });
172
+ ```
173
+
174
+ O evento também informa `deletedById` quando o WhatsApp fornece a identidade responsável pela revogação.
175
+
176
+ ## Mensagens editadas
177
+
178
+ Edições recebidas pelo WhatsApp são expostas pelo evento `messageEdited`. Quando a versão anterior ainda estiver no cache recente, o payload inclui `previous`; `message` contém a versão atual.
179
+
180
+ ```ts
181
+ app.on('messageEdited', async ({ previous, message, editedByMe }) => {
182
+ if (!previous || editedByMe) return;
183
+
184
+ console.log(previous.text, message.text);
185
+ });
186
+ ```
187
+
188
+ Após cada edição, a nova versão substitui a anterior no cache recente. Assim, edições consecutivas da mesma mensagem sempre comparam a versão atual com a imediatamente anterior.
189
+
162
190
  ## Logging
163
191
 
164
192
  O nível padrão é `info`. Estão disponíveis `debug`, `info`, `warn`, `error` e `silent`.
package/dist/index.d.ts CHANGED
@@ -90,6 +90,21 @@ interface QuotedMessage {
90
90
  contentKind?: MessageContentKind;
91
91
  media?: MessageMedia;
92
92
  }
93
+ interface MessageDeleted {
94
+ key: MessageKey;
95
+ message?: Message;
96
+ deletedByMe: boolean;
97
+ deletedById?: string;
98
+ deletedAt: Date;
99
+ }
100
+ interface MessageEdited {
101
+ key: MessageKey;
102
+ previous?: Message;
103
+ message: Message;
104
+ editedByMe: boolean;
105
+ editedById?: string;
106
+ editedAt: Date;
107
+ }
93
108
  interface Message {
94
109
  id: string;
95
110
  jid: string;
@@ -247,6 +262,8 @@ interface ConnectionUpdate {
247
262
  }
248
263
  interface ProviderEvents {
249
264
  message: Message;
265
+ messageDeleted: MessageDeleted;
266
+ messageEdited: MessageEdited;
250
267
  connection: ConnectionUpdate;
251
268
  groupChanged: {
252
269
  groupId: string;
@@ -746,6 +763,8 @@ declare class AccountService {
746
763
 
747
764
  interface AppEvents {
748
765
  message: Message;
766
+ messageDeleted: MessageDeleted;
767
+ messageEdited: MessageEdited;
749
768
  connection: ConnectionUpdate;
750
769
  error: WhaNextError;
751
770
  mute: MuteEnforcement;
@@ -905,4 +924,4 @@ declare class SqliteMuteStore implements MuteStore {
905
924
  close(): void;
906
925
  }
907
926
 
908
- export { AccountService, type AddMuteOptions, type AddMuteResult, type AppEvents, type AppHealth, type AppHealthStatus, ArgsParser, type AudioContent, type BooleanOption, Browser, type ButtonsContent, type CacheOptions, type CacheStore, type CallEvent, type CallStatus, type ChangeResult, type CommandAccountContext, type CommandCatalogOptions, type CommandCatalogView, type CommandChatContext, type CommandConcurrency, type CommandContext, type CommandCooldown, type CommandDefinition, type CommandErrorHandler, type CommandGroupContext, type CommandGroupDefinition, type CommandGuard, type CommandHelpOptions, type CommandHooks, type CommandLocalization, type CommandMetadata, type CommandMiddleware, type CommandOptionDefinition, type CommandOptionSchema, type CommandOptionValue, type CommandOptionValues, type CommandRegistrar, CommandRouter, type CommandRuntimeServices, type CommandScope, type ConcurrencyStrategy, type ConnectionState, type ConnectionUpdate, type CopyCodeButton, type CreateMultiOptions, type CreateOptions, DeferredReply, type DownloadedMedia, type DurationOption, type EnumOption, type ExecutableCommandDefinition, type GroupAccess, type GroupAddressingMode, type GroupParticipant, type GroupParticipantAction, type GroupParticipantsChanged, type GroupRole, type GroupSnapshot, type GuardResult, type ImageContent, type InviteResult, type LinkButton, type LoadCommandsOptions, type LoadCommandsResult, type LoadedCommand, type LogContext, type LogEntry, type LogFormat, type LogLevel, type LogWriter, Logger, type LoggerConfig, type LoggerOptions, type LoginOptions, type MediaKind, type MediaSource, type MemberActionState, MemoryCache, type MemoryCacheStats, type MentionTarget, type Message, type MessageButton, type MessageContent, type MessageContentKind, type MessageKey, type MessageMedia, type MultiAccountOptions, type MultiAppEvent, type MultiAppHealth, MultiCommandRouter, type MultiLoadCommandsResult, type MultiLoginOptions, type MuteChangeResult, type MuteEnforcement, type MuteOptions, type MuteRecord, MuteService, type MuteStore, type NumberOption, ParsedCommandOptions, type ParticipantUpdateResult, type PresenceState, type QuotedMessage, type ReconnectOptions, type RegisteredCommand, type RemoveMuteResult, type ReplyOptions, type RepostMessageOptions, type RouterOptions, type SentMessage, SqliteMuteStore, type StickerContent, type StoredMute, type StringOption, type TextContent, User, type UserData, type UserOption, type VideoContent, WhaNextApp, WhaNextError, type WhaNextErrorCode, WhaNextMultiApp, type WhatsAppProvider, create, createMulti, defineCommand, defineCommandGroup, defineCommands, defineSubcommand, guards, isCommandGroup, loadCommands, option, toWhaNextError };
927
+ export { AccountService, type AddMuteOptions, type AddMuteResult, type AppEvents, type AppHealth, type AppHealthStatus, ArgsParser, type AudioContent, type BooleanOption, Browser, type ButtonsContent, type CacheOptions, type CacheStore, type CallEvent, type CallStatus, type ChangeResult, type CommandAccountContext, type CommandCatalogOptions, type CommandCatalogView, type CommandChatContext, type CommandConcurrency, type CommandContext, type CommandCooldown, type CommandDefinition, type CommandErrorHandler, type CommandGroupContext, type CommandGroupDefinition, type CommandGuard, type CommandHelpOptions, type CommandHooks, type CommandLocalization, type CommandMetadata, type CommandMiddleware, type CommandOptionDefinition, type CommandOptionSchema, type CommandOptionValue, type CommandOptionValues, type CommandRegistrar, CommandRouter, type CommandRuntimeServices, type CommandScope, type ConcurrencyStrategy, type ConnectionState, type ConnectionUpdate, type CopyCodeButton, type CreateMultiOptions, type CreateOptions, DeferredReply, type DownloadedMedia, type DurationOption, type EnumOption, type ExecutableCommandDefinition, type GroupAccess, type GroupAddressingMode, type GroupParticipant, type GroupParticipantAction, type GroupParticipantsChanged, type GroupRole, type GroupSnapshot, type GuardResult, type ImageContent, type InviteResult, type LinkButton, type LoadCommandsOptions, type LoadCommandsResult, type LoadedCommand, type LogContext, type LogEntry, type LogFormat, type LogLevel, type LogWriter, Logger, type LoggerConfig, type LoggerOptions, type LoginOptions, type MediaKind, type MediaSource, type MemberActionState, MemoryCache, type MemoryCacheStats, type MentionTarget, type Message, type MessageButton, type MessageContent, type MessageContentKind, type MessageDeleted, type MessageEdited, type MessageKey, type MessageMedia, type MultiAccountOptions, type MultiAppEvent, type MultiAppHealth, MultiCommandRouter, type MultiLoadCommandsResult, type MultiLoginOptions, type MuteChangeResult, type MuteEnforcement, type MuteOptions, type MuteRecord, MuteService, type MuteStore, type NumberOption, ParsedCommandOptions, type ParticipantUpdateResult, type PresenceState, type QuotedMessage, type ReconnectOptions, type RegisteredCommand, type RemoveMuteResult, type ReplyOptions, type RepostMessageOptions, type RouterOptions, type SentMessage, SqliteMuteStore, type StickerContent, type StoredMute, type StringOption, type TextContent, User, type UserData, type UserOption, type VideoContent, WhaNextApp, WhaNextError, type WhaNextErrorCode, WhaNextMultiApp, type WhatsAppProvider, create, createMulti, defineCommand, defineCommandGroup, defineCommands, defineSubcommand, guards, isCommandGroup, loadCommands, option, toWhaNextError };
package/dist/index.js CHANGED
@@ -2197,6 +2197,24 @@ var WhaNextApp = class {
2197
2197
  });
2198
2198
  await this.#events.emit("call", call);
2199
2199
  });
2200
+ this.#provider.on("messageDeleted", async (deletion) => {
2201
+ this.logger.debug("Message deleted", {
2202
+ chatId: deletion.key.chatId,
2203
+ messageId: deletion.key.id,
2204
+ deletedByMe: deletion.deletedByMe,
2205
+ cached: deletion.message !== void 0
2206
+ });
2207
+ await this.#events.emit("messageDeleted", deletion);
2208
+ });
2209
+ this.#provider.on("messageEdited", async (edit) => {
2210
+ this.logger.debug("Message edited", {
2211
+ chatId: edit.key.chatId,
2212
+ messageId: edit.key.id,
2213
+ editedByMe: edit.editedByMe,
2214
+ cached: edit.previous !== void 0
2215
+ });
2216
+ await this.#events.emit("messageEdited", edit);
2217
+ });
2200
2218
  this.#provider.on("message", async (message) => {
2201
2219
  try {
2202
2220
  const enforcement = await this.mute.enforce(message);
@@ -2848,6 +2866,50 @@ var BaileysProvider = class {
2848
2866
  if (message) void this.#events.emit("message", message);
2849
2867
  }
2850
2868
  });
2869
+ socket.ev.on("messages.update", (updates) => {
2870
+ for (const { key, update } of updates) {
2871
+ if (!key.id || !key.remoteJid) continue;
2872
+ const stored = this.#messageStore.get(this.#messageStoreKey(key));
2873
+ if (update.message === null) {
2874
+ const message2 = stored ? normalizeBaileysMessage(stored) : void 0;
2875
+ const deletionKey = update.key;
2876
+ const deletedByMe = deletionKey?.fromMe === true;
2877
+ const deletedById = deletionKey?.participant ?? deletionKey?.participantAlt ?? (deletedByMe ? this.#socket?.user?.id : deletionKey?.remoteJid ?? void 0);
2878
+ void this.#events.emit("messageDeleted", {
2879
+ key: message2?.keys ?? normalizeKey(key),
2880
+ ...message2 ? { message: message2 } : {},
2881
+ deletedByMe,
2882
+ ...deletedById ? { deletedById } : {},
2883
+ deletedAt: /* @__PURE__ */ new Date()
2884
+ });
2885
+ continue;
2886
+ }
2887
+ if (!update.message?.editedMessage?.message) continue;
2888
+ const editedRaw = {
2889
+ ...stored ?? {},
2890
+ key: {
2891
+ ...stored?.key ?? {},
2892
+ ...key
2893
+ },
2894
+ message: update.message,
2895
+ messageTimestamp: update.messageTimestamp ?? stored?.messageTimestamp ?? Math.floor(Date.now() / 1e3)
2896
+ };
2897
+ const previous = stored ? normalizeBaileysMessage(stored) : void 0;
2898
+ const message = normalizeBaileysMessage(editedRaw);
2899
+ if (!message) continue;
2900
+ this.#remember(editedRaw);
2901
+ const editedByMe = key.fromMe === true;
2902
+ const editedById = key.participant ?? key.participantAlt ?? (editedByMe ? this.#socket?.user?.id : key.remoteJid ?? void 0);
2903
+ void this.#events.emit("messageEdited", {
2904
+ key: message.keys,
2905
+ ...previous ? { previous } : {},
2906
+ message,
2907
+ editedByMe,
2908
+ ...editedById ? { editedById } : {},
2909
+ editedAt: message.timestamp
2910
+ });
2911
+ }
2912
+ });
2851
2913
  socket.ev.on("groups.update", (groups) => {
2852
2914
  for (const group of groups) {
2853
2915
  if (group.id) {