@arcaelas/whatsapp 4.4.0 → 5.1.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.
Files changed (97) hide show
  1. package/build/cjs/index.d.ts +6 -4
  2. package/build/cjs/index.js +22 -2
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/cjs/lib/bot/decorator.d.ts +2 -0
  5. package/build/cjs/lib/bot/decorator.js +6 -0
  6. package/build/cjs/lib/bot/decorator.js.map +1 -1
  7. package/build/cjs/lib/chat/index.d.ts +340 -204
  8. package/build/cjs/lib/chat/index.js +225 -213
  9. package/build/cjs/lib/chat/index.js.map +1 -1
  10. package/build/cjs/lib/contact/index.d.ts +162 -179
  11. package/build/cjs/lib/contact/index.js +96 -190
  12. package/build/cjs/lib/contact/index.js.map +1 -1
  13. package/build/cjs/lib/internal.d.ts +40 -0
  14. package/build/cjs/lib/internal.js +39 -0
  15. package/build/cjs/lib/internal.js.map +1 -0
  16. package/build/cjs/lib/message/index.d.ts +463 -278
  17. package/build/cjs/lib/message/index.js +830 -710
  18. package/build/cjs/lib/message/index.js.map +1 -1
  19. package/build/cjs/lib/status/index.d.ts +60 -70
  20. package/build/cjs/lib/status/index.js +106 -111
  21. package/build/cjs/lib/status/index.js.map +1 -1
  22. package/build/cjs/lib/store/engine/index.d.ts +21 -7
  23. package/build/cjs/lib/store/engine/index.js +6 -3
  24. package/build/cjs/lib/store/engine/index.js.map +1 -1
  25. package/build/cjs/lib/store/engine/lib/file_system/index.d.ts +38 -8
  26. package/build/cjs/lib/store/engine/lib/file_system/index.js +92 -67
  27. package/build/cjs/lib/store/engine/lib/file_system/index.js.map +1 -1
  28. package/build/cjs/lib/store/engine/lib/index.d.ts +112 -0
  29. package/build/cjs/lib/store/engine/lib/index.js +213 -0
  30. package/build/cjs/lib/store/engine/lib/index.js.map +1 -0
  31. package/build/cjs/lib/store/engine/lib/redis/index.d.ts +28 -13
  32. package/build/cjs/lib/store/engine/lib/redis/index.js +56 -42
  33. package/build/cjs/lib/store/engine/lib/redis/index.js.map +1 -1
  34. package/build/cjs/lib/store/engine/lib/s3/index.d.ts +44 -1
  35. package/build/cjs/lib/store/engine/lib/s3/index.js +112 -64
  36. package/build/cjs/lib/store/engine/lib/s3/index.js.map +1 -1
  37. package/build/cjs/lib/store/engine/lib/sqlite/index.d.ts +98 -0
  38. package/build/cjs/lib/store/engine/lib/sqlite/index.js +114 -0
  39. package/build/cjs/lib/store/engine/lib/sqlite/index.js.map +1 -0
  40. package/build/cjs/lib/store/index.d.ts +7 -3
  41. package/build/cjs/lib/store/index.js +14 -4
  42. package/build/cjs/lib/store/index.js.map +1 -1
  43. package/build/cjs/lib/whatsapp/index.d.ts +117 -63
  44. package/build/cjs/lib/whatsapp/index.js +404 -184
  45. package/build/cjs/lib/whatsapp/index.js.map +1 -1
  46. package/build/cjs/test.d.ts +1 -0
  47. package/build/cjs/test.js +72 -0
  48. package/build/cjs/test.js.map +1 -0
  49. package/build/esm/index.d.ts +6 -4
  50. package/build/esm/index.js +5 -2
  51. package/build/esm/index.js.map +1 -1
  52. package/build/esm/lib/bot/decorator.d.ts +2 -0
  53. package/build/esm/lib/bot/decorator.js +6 -0
  54. package/build/esm/lib/bot/decorator.js.map +1 -1
  55. package/build/esm/lib/chat/index.d.ts +340 -204
  56. package/build/esm/lib/chat/index.js +225 -213
  57. package/build/esm/lib/chat/index.js.map +1 -1
  58. package/build/esm/lib/contact/index.d.ts +162 -179
  59. package/build/esm/lib/contact/index.js +96 -189
  60. package/build/esm/lib/contact/index.js.map +1 -1
  61. package/build/esm/lib/internal.d.ts +40 -0
  62. package/build/esm/lib/internal.js +35 -0
  63. package/build/esm/lib/internal.js.map +1 -0
  64. package/build/esm/lib/message/index.d.ts +463 -278
  65. package/build/esm/lib/message/index.js +825 -705
  66. package/build/esm/lib/message/index.js.map +1 -1
  67. package/build/esm/lib/status/index.d.ts +60 -70
  68. package/build/esm/lib/status/index.js +105 -110
  69. package/build/esm/lib/status/index.js.map +1 -1
  70. package/build/esm/lib/store/engine/index.d.ts +21 -7
  71. package/build/esm/lib/store/engine/index.js +4 -2
  72. package/build/esm/lib/store/engine/index.js.map +1 -1
  73. package/build/esm/lib/store/engine/lib/file_system/index.d.ts +38 -8
  74. package/build/esm/lib/store/engine/lib/file_system/index.js +92 -67
  75. package/build/esm/lib/store/engine/lib/file_system/index.js.map +1 -1
  76. package/build/esm/lib/store/engine/lib/index.d.ts +112 -0
  77. package/build/esm/lib/store/engine/lib/index.js +206 -0
  78. package/build/esm/lib/store/engine/lib/index.js.map +1 -0
  79. package/build/esm/lib/store/engine/lib/redis/index.d.ts +28 -13
  80. package/build/esm/lib/store/engine/lib/redis/index.js +54 -40
  81. package/build/esm/lib/store/engine/lib/redis/index.js.map +1 -1
  82. package/build/esm/lib/store/engine/lib/s3/index.d.ts +44 -1
  83. package/build/esm/lib/store/engine/lib/s3/index.js +111 -63
  84. package/build/esm/lib/store/engine/lib/s3/index.js.map +1 -1
  85. package/build/esm/lib/store/engine/lib/sqlite/index.d.ts +98 -0
  86. package/build/esm/lib/store/engine/lib/sqlite/index.js +110 -0
  87. package/build/esm/lib/store/engine/lib/sqlite/index.js.map +1 -0
  88. package/build/esm/lib/store/index.d.ts +7 -3
  89. package/build/esm/lib/store/index.js +13 -4
  90. package/build/esm/lib/store/index.js.map +1 -1
  91. package/build/esm/lib/whatsapp/index.d.ts +117 -63
  92. package/build/esm/lib/whatsapp/index.js +406 -186
  93. package/build/esm/lib/whatsapp/index.js.map +1 -1
  94. package/build/esm/test.d.ts +1 -0
  95. package/build/esm/test.js +67 -0
  96. package/build/esm/test.js.map +1 -0
  97. package/package.json +2 -2
@@ -1,33 +1,30 @@
1
1
  "use strict";
2
2
  /**
3
3
  * @file message/index.ts
4
- * @description Entidad Message — una sola clase base que recibe `{wa, doc}` en el constructor.
5
- * Subclases especializadas (Text, Image, Video, Audio, Gps, Poll) override `content()` según su tipo.
4
+ * @description Entidad Message — clase base con getters puros y subclases por tipo
5
+ * (Text, Image, Video, Audio, Sticker, Document, Location, Poll, VCard, Event);
6
+ * `message(wa, raw)` evalúa el tipo y retorna la instancia correcta.
7
+ * Message entity — pure-getter base class with per-type subclasses;
8
+ * `message(wa, raw)` evaluates the type and returns the right instance.
6
9
  */
7
10
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.Event = exports.VCard = exports.Document = exports.Poll = exports.Gps = exports.Audio = exports.Video = exports.Image = exports.Text = exports.Message = exports.MessageStatus = void 0;
9
- exports.build_message_doc = build_message_doc;
11
+ exports.Event = exports.VCard = exports.Poll = exports.Location = exports.Document = exports.Sticker = exports.Audio = exports.Video = exports.Image = exports.Text = exports.Message = void 0;
10
12
  exports.message = message;
11
13
  const baileys_1 = require("baileys");
12
14
  const node_crypto_1 = require("node:crypto");
13
15
  const node_stream_1 = require("node:stream");
16
+ const internal_1 = require("../../lib/internal");
14
17
  const chat_1 = require("../../lib/chat");
15
18
  const store_1 = require("../../lib/store");
16
- var MessageStatus;
17
- (function (MessageStatus) {
18
- MessageStatus[MessageStatus["ERROR"] = 0] = "ERROR";
19
- MessageStatus[MessageStatus["PENDING"] = 1] = "PENDING";
20
- MessageStatus[MessageStatus["SERVER_ACK"] = 2] = "SERVER_ACK";
21
- MessageStatus[MessageStatus["DELIVERED"] = 3] = "DELIVERED";
22
- MessageStatus[MessageStatus["READ"] = 4] = "READ";
23
- MessageStatus[MessageStatus["PLAYED"] = 5] = "PLAYED";
24
- })(MessageStatus || (exports.MessageStatus = MessageStatus = {}));
19
+ /** Estados legibles indexados por el status numérico de baileys. / Readable states indexed by the baileys numeric status. */
20
+ const STATUS = ['error', 'pending', 'sent', 'delivered', 'read', 'played'];
25
21
  const MESSAGE_TYPE_MAP = {
26
22
  conversation: 'text',
27
23
  extendedTextMessage: 'text',
28
24
  imageMessage: 'image',
29
25
  videoMessage: 'video',
30
26
  audioMessage: 'audio',
27
+ stickerMessage: 'sticker',
31
28
  locationMessage: 'location',
32
29
  liveLocationMessage: 'location',
33
30
  pollCreationMessage: 'poll',
@@ -40,292 +37,407 @@ const MESSAGE_TYPE_MAP = {
40
37
  eventMessage: 'event',
41
38
  };
42
39
  /**
43
- * Construye el documento IMessage desde el raw de baileys.
40
+ * Desenvuelve los wrappers de contenido (view-once, documento con caption).
41
+ * Unwraps content wrappers (view-once, captioned document).
44
42
  */
45
- function build_message_doc(raw, self_id, edited = false) {
46
- const key = raw.key ?? {};
47
- const msg = raw.message ?? {};
48
- const unwrapped = msg.viewOnceMessage?.message ??
43
+ function unwrap(msg) {
44
+ return (msg.viewOnceMessage?.message ??
49
45
  msg.viewOnceMessageV2?.message ??
50
46
  msg.viewOnceMessageV2Extension?.message ??
51
47
  msg.documentWithCaptionMessage?.message ??
52
- msg;
53
- const content_type = (0, baileys_1.getContentType)(unwrapped);
54
- const msg_type = MESSAGE_TYPE_MAP[content_type ?? ''] ?? 'text';
55
- const msg_content = unwrapped[content_type];
56
- const context_info = msg_content
57
- ?.contextInfo;
58
- const ephemeral_duration = raw.ephemeralDuration ?? context_info?.expiration;
59
- const deleted_at = raw.ephemeralStartTimestamp != null && ephemeral_duration != null
60
- ? (Number(raw.ephemeralStartTimestamp) + ephemeral_duration) * 1000
61
- : null;
62
- let mime = 'text/plain';
63
- if (msg_type === 'location' || msg_type === 'poll' || msg_type === 'event') {
64
- mime = 'application/json';
65
- }
66
- else if (msg_type === 'vcard') {
67
- mime = 'text/vcard';
68
- }
69
- else if (msg_type !== 'text' && typeof msg_content === 'object') {
70
- mime = msg_content?.mimetype ?? 'application/octet-stream';
71
- }
72
- let caption = '';
73
- if (typeof msg_content === 'string') {
74
- caption = msg_content;
75
- }
76
- else if (msg_type === 'event') {
77
- caption = msg_content?.description ?? '';
78
- }
79
- else if (msg_content) {
80
- caption =
81
- msg_content.caption ??
82
- msg_content.text ??
83
- msg_content.name ??
84
- msg_content.displayName ??
85
- '';
86
- }
87
- const author = key.fromMe && self_id
88
- ? (0, baileys_1.jidNormalizedUser)(self_id)
89
- : key.participant || key.remoteJidAlt || key.remoteJid || '';
90
- return {
91
- id: key.id ?? '',
92
- cid: key.remoteJidAlt ?? key.remoteJid ?? '',
93
- mid: context_info?.stanzaId ?? null,
94
- me: key.fromMe ?? false,
95
- type: msg_type,
96
- author,
97
- status: raw.status ?? MessageStatus.PENDING,
98
- starred: raw.starred ?? false,
99
- forwarded: context_info?.isForwarded ?? false,
100
- created_at: (Number(raw.messageTimestamp) || Math.floor(Date.now() / 1000)) * 1000,
101
- deleted_at,
102
- mime,
103
- caption,
104
- edited,
105
- raw,
106
- };
48
+ msg);
49
+ }
50
+ /**
51
+ * Convierte un número o Long del proto a number plano.
52
+ * Converts a proto number or Long into a plain number.
53
+ */
54
+ function to_number(value) {
55
+ return Number(value?.toString() ?? 0);
56
+ }
57
+ /**
58
+ * Convierte los bytes del proto (Uint8Array runtime o base64 post-engine) a Buffer.
59
+ * Converts proto bytes (runtime Uint8Array or post-engine base64) into a Buffer.
60
+ */
61
+ function to_buffer(value) {
62
+ if (value instanceof Uint8Array && value.length > 0)
63
+ return Buffer.from(value);
64
+ if (typeof value === 'string' && value.length > 0)
65
+ return Buffer.from(value, 'base64');
66
+ return null;
67
+ }
68
+ /**
69
+ * Envío base: resuelve el destino, cita si hay `mid`, marca view-once, persiste el doc
70
+ * (con su binario cuando aplica) y retorna la instancia del mensaje enviado.
71
+ * Base send: resolves the target, quotes when `mid` is given, flags view-once, persists
72
+ * the doc (with its binary when it applies) and returns the sent message instance.
73
+ */
74
+ async function send(wa, cid, content, binary, extra = {}, doc_overrides) {
75
+ let result = null;
76
+ const jid = await (0, internal_1.internals)(wa).resolve_jid(cid);
77
+ const socket = (0, internal_1.internals)(wa).socket;
78
+ if (jid && socket) {
79
+ const quoted = extra.mid
80
+ ? ((0, store_1.deserialize)(await wa.engine.get(`/chat/${jid}/message/${extra.mid}`))?.raw ?? undefined)
81
+ : undefined;
82
+ const raw = await socket.sendMessage(jid, {
83
+ ...content,
84
+ ...(extra.once && { viewOnce: true }),
85
+ ...(quoted && { quoted }),
86
+ });
87
+ const sent_id = raw?.key?.id;
88
+ if (raw && sent_id) {
89
+ const instance = message(wa, raw);
90
+ if (doc_overrides) {
91
+ Object.assign(instance._raw, doc_overrides);
92
+ }
93
+ await wa.engine.set(`/chat/${jid}/message/${sent_id}`, (0, store_1.serialize)(instance._raw), instance._raw.created_at);
94
+ if (binary) {
95
+ await wa.engine.set(`/chat/${jid}/message/${sent_id}/content`, (0, store_1.serialize)({ data: binary.toString('base64') }));
96
+ }
97
+ result = instance;
98
+ }
99
+ }
100
+ return result;
101
+ }
102
+ /**
103
+ * Stream del binario del mensaje: cache del engine o descarga de baileys.
104
+ * Message binary stream: engine cache or baileys download.
105
+ */
106
+ async function media_stream(wa, doc) {
107
+ const cached = (0, store_1.deserialize)(await wa.engine.get(`/chat/${doc.cid}/message/${doc.id}/content`));
108
+ if (cached?.data) {
109
+ return node_stream_1.Readable.from(Buffer.from(cached.data, 'base64'));
110
+ }
111
+ const socket = (0, internal_1.internals)(wa).socket;
112
+ if (socket) {
113
+ try {
114
+ return (await (0, baileys_1.downloadMediaMessage)(doc.raw, 'stream', {}));
115
+ }
116
+ catch {
117
+ /* media may be expired */
118
+ }
119
+ }
120
+ return node_stream_1.Readable.from(Buffer.alloc(0));
121
+ }
122
+ /**
123
+ * Acumula un Readable en Buffer.
124
+ * Drains a Readable into a Buffer.
125
+ */
126
+ async function drain(readable) {
127
+ const chunks = [];
128
+ for await (const chunk of readable) {
129
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
130
+ }
131
+ return Buffer.concat(chunks);
107
132
  }
108
133
  /**
109
- * Clase base del mensaje. Una sola clase toda la API de instancia vive aquí.
110
- * Base message class. Single class all instance API lives here.
134
+ * Clase base del mensaje: recibe el cliente y el raw, deriva el estado con getters y
135
+ * opera contra WhatsApp con sus métodos. Los estáticos reciben el cliente como primer
136
+ * argumento (`Message.text(wa, cid, …)`).
137
+ * Base message class: receives the client and the raw, derives state via getters and
138
+ * operates against WhatsApp with its methods. Statics take the client as their first
139
+ * argument (`Message.text(wa, cid, …)`).
111
140
  */
112
141
  class Message {
113
- constructor(options) {
114
- /** @internal Cache de la promesa de `author()` para evitar engine round-trips repetidos. */
115
- this._author_cache = null;
116
- /** @internal Cache de la promesa de `chat()` para evitar engine round-trips repetidos. */
117
- this._chat_cache = null;
118
- this._wa = options.wa;
119
- this._doc = options.doc;
142
+ /**
143
+ * @internal Cliente dueño y documento persistido. `status`, `created_at` y
144
+ * `deleted_at` guardan los valores numéricos del protocolo; los getters los
145
+ * presentan legibles. `viewed` existe únicamente en los status broadcast (Feed).
146
+ * Owner client and persisted document. `status`, `created_at` and `deleted_at`
147
+ * keep the protocol numeric values; getters expose them readable. `viewed` only
148
+ * exists on status broadcasts (Feed).
149
+ */
150
+ constructor(_wa, _raw) {
151
+ this._wa = _wa;
152
+ this._raw = _raw;
120
153
  }
154
+ /** Identificador del mensaje. / Message identifier. */
121
155
  get id() {
122
- return this._doc.id;
156
+ return this._raw.id;
123
157
  }
158
+ /** Identificador del chat del mensaje. / Message chat identifier. */
124
159
  get cid() {
125
- return this._doc.cid;
160
+ return this._raw.cid;
126
161
  }
127
- get type() {
128
- return this._doc.type;
162
+ /** Identificador del mensaje citado, o null. / Quoted message identifier, or null. */
163
+ get mid() {
164
+ return this._raw.mid;
129
165
  }
130
- /** JID del autor del mensaje. Para acceso síncrono sin hidratar el Contact. */
166
+ /** JID del autor, para acceso síncrono. / Author JID, for sync access. */
131
167
  get from() {
132
- return this._doc.author;
133
- }
134
- /** MIME type del contenido. `text/plain` para texto, `application/json` para location/poll, mimetype real para media. */
135
- get mime() {
136
- return this._doc.mime;
137
- }
138
- get mid() {
139
- return this._doc.mid;
168
+ return this._raw.author;
140
169
  }
170
+ /** true si soy el autor. / true when I am the author. */
141
171
  get me() {
142
- return this._doc.me;
172
+ return this._raw.me;
173
+ }
174
+ /** Tipo del mensaje. / Message type. */
175
+ get type() {
176
+ return this._raw.type;
143
177
  }
178
+ /** MIME: text/plain en texto, text/json en poll/location/vcard/event, real en media. / MIME: text/plain for text, text/json for poll/location/vcard/event, actual for media. */
179
+ get mime() {
180
+ const { type } = this._raw;
181
+ if (type === 'text')
182
+ return 'text/plain';
183
+ if (type === 'poll' || type === 'location' || type === 'vcard' || type === 'event')
184
+ return 'text/json';
185
+ return this._raw.mime;
186
+ }
187
+ /** Texto del mensaje o caption del media. / Message text or media caption. */
144
188
  get caption() {
145
- return this._doc.caption;
189
+ return this._raw.caption;
190
+ }
191
+ /** Estado legible del mensaje. / Readable message state. */
192
+ get status() {
193
+ return STATUS[this._raw.status] ?? 'pending';
194
+ }
195
+ /** true si el mensaje fue visto. / true when the message was seen. */
196
+ get read() {
197
+ return this._raw.status >= 4;
146
198
  }
199
+ /** true si está destacado. / true when starred. */
147
200
  get starred() {
148
- return this._doc.starred;
201
+ return this._raw.starred;
149
202
  }
203
+ /** true si fue reenviado. / true when forwarded. */
150
204
  get forwarded() {
151
- return this._doc.forwarded;
205
+ return this._raw.forwarded;
152
206
  }
207
+ /** true si fue editado. / true when edited. */
208
+ get edited() {
209
+ return this._raw.edited;
210
+ }
211
+ /** true si es de una sola lectura (view-once). / true when view-once. */
153
212
  get once() {
154
- return this._doc.deleted_at !== null;
213
+ const msg = this._raw.raw.message;
214
+ return Boolean(msg?.viewOnceMessage ?? msg?.viewOnceMessageV2 ?? msg?.viewOnceMessageV2Extension);
155
215
  }
216
+ /** Fecha de creación en ISO UTC. / Creation date as ISO UTC. */
156
217
  get created_at() {
157
- return this._doc.created_at;
218
+ return new Date(this._raw.created_at).toISOString();
158
219
  }
159
- get deleted_at() {
160
- return this._doc.deleted_at;
161
- }
162
- get status() {
163
- return this._doc.status;
164
- }
165
- get edited() {
166
- return this._doc.edited;
220
+ /** Vencimiento del mensaje temporal en ISO UTC, o null. / Ephemeral expiration as ISO UTC, or null. */
221
+ get expires_at() {
222
+ return this._raw.deleted_at != null ? new Date(this._raw.deleted_at).toISOString() : null;
167
223
  }
168
224
  /**
169
- * Contacto del autor (resuelve vía `wa.Contact.get`; fallback a instancia mínima).
170
- * Memoizado por instancia: la primera llamada va al engine; las siguientes
171
- * reutilizan la misma promesa sin nuevos round-trips.
172
- * Author contact (resolves via `wa.Contact.get`; falls back to a minimal instance).
173
- * Instance-memoized: first call hits the engine; subsequent calls reuse the
174
- * same promise without further round-trips.
225
+ * Contacto autor del mensaje, desde el engine (ficha mínima si no está persistido).
226
+ * Message author contact, from the engine (minimal card when not persisted).
227
+ *
228
+ * @returns Contacto / Contact
175
229
  */
176
230
  async author() {
177
- return (this._author_cache ??= (async () => {
178
- const { _wa, _doc } = this;
179
- const fetched = _doc.author ? await _wa.Contact.get(_doc.author) : null;
180
- return (fetched ??
181
- new _wa.Contact({
182
- id: _doc.author,
183
- lid: null,
184
- name: null,
185
- notify: null,
186
- verified_name: null,
187
- img_url: null,
188
- status: null,
189
- }, new _wa.Chat({ id: _doc.author, name: _doc.author.split('@')[0] })));
190
- })());
231
+ const cached = (0, store_1.deserialize)(await this._wa.engine.get(`/contact/${this._raw.author}`));
232
+ return new this._wa.Contact(cached ?? { id: this._raw.author });
191
233
  }
192
234
  /**
193
- * Chat al que pertenece el mensaje. Memoizado por instancia: la primera llamada
194
- * va al engine; las siguientes reutilizan la misma promesa.
195
- * Chat the message belongs to. Instance-memoized: first call hits the engine;
196
- * subsequent calls reuse the same promise.
235
+ * Chat al que pertenece el mensaje.
236
+ * Chat the message belongs to.
237
+ *
238
+ * @returns Chat / Chat
197
239
  */
198
240
  async chat() {
199
- return (this._chat_cache ??= (async () => {
200
- const cached = (0, store_1.deserialize)(await this._wa.engine.get(`/chat/${this._doc.cid}`));
201
- return new this._wa.Chat(cached ?? { id: this._doc.cid, name: this._doc.cid.split('@')[0] });
202
- })());
241
+ const cached = (0, store_1.deserialize)(await this._wa.engine.get(`/chat/${this._raw.cid}`));
242
+ return new this._wa.Chat(cached ?? { id: this._raw.cid });
243
+ }
244
+ /**
245
+ * Mensaje citado cuando hay `mid`, o null.
246
+ * Quoted message when `mid` exists, or null.
247
+ *
248
+ * @returns Mensaje citado o null / Quoted message or null
249
+ */
250
+ async message() {
251
+ return this._raw.mid ? Message.get(this._wa, this._raw.cid, this._raw.mid) : null;
203
252
  }
204
- /** Contenido sin parsear, directo del engine. Las subclases override según su tipo. */
253
+ /**
254
+ * Contenido del mensaje: texto como su caption, media como binario, y
255
+ * poll/location/vcard/event como JSON.
256
+ * Message content: text as its caption, media as binary, and
257
+ * poll/location/vcard/event as JSON.
258
+ *
259
+ * @returns Buffer del contenido / Content buffer
260
+ */
205
261
  async content() {
206
- const cached = (0, store_1.deserialize)(await this._wa.engine.get(`/chat/${this._doc.cid}/message/${this._doc.id}/content`));
262
+ const cached = (0, store_1.deserialize)(await this._wa.engine.get(`/chat/${this._raw.cid}/message/${this._raw.id}/content`));
207
263
  return cached?.data ? Buffer.from(cached.data, 'base64') : Buffer.alloc(0);
208
264
  }
209
265
  /**
210
- * Devuelve un `Readable` con los bytes del mensaje. Para media (image/video/audio)
211
- * lee desde el cache del engine o, si falta, descarga desde baileys. Para text/location/poll
212
- * retorna el mismo binario que `content()` envuelto en un Readable.
213
- * Returns a `Readable` of the message bytes. For media (image/video/audio) it reads
214
- * from the engine cache or, if missing, downloads from baileys. For text/location/poll
215
- * it wraps the `content()` buffer in a Readable.
266
+ * Stream del contenido; para media descarga de baileys si el cache falta.
267
+ * Content stream; media falls back to a baileys download when the cache is missing.
268
+ *
269
+ * @returns Readable del contenido / Content readable
216
270
  */
217
271
  async stream() {
218
- return _media_stream(this);
272
+ return media_stream(this._wa, this._raw);
273
+ }
274
+ /**
275
+ * Reacciones del mensaje agrupadas por emoji con su conteo.
276
+ * Message reactions grouped by emoji with their count.
277
+ *
278
+ * @returns Conteo por emoji / Per-emoji count
279
+ */
280
+ async reactions() {
281
+ const counts = new Map();
282
+ for (const { emoji } of this._raw.reactions ?? []) {
283
+ counts.set(emoji, (counts.get(emoji) ?? 0) + 1);
284
+ }
285
+ return [...counts.entries()].map(([emoji, count]) => ({ emoji, count }));
219
286
  }
220
- /** Reacciona al mensaje (emoji vacío para retirar). */
287
+ /**
288
+ * Reacciona al mensaje; el emoji vacío retira la reacción.
289
+ * Reacts to the message; an empty emoji removes the reaction.
290
+ *
291
+ * @param emoji - Emoji o '' / Emoji or ''
292
+ * @returns true si se envió / true when sent
293
+ */
221
294
  async react(emoji) {
222
- const { _wa, _doc } = this;
223
295
  let ok = false;
224
- if (_wa._socket) {
225
- await _wa._socket.sendMessage(_doc.cid, {
226
- react: { text: emoji, key: { remoteJid: _doc.cid, id: _doc.id, fromMe: _doc.me } },
296
+ const socket = (0, internal_1.internals)(this._wa).socket;
297
+ if (socket) {
298
+ const { cid, id, me, author } = this._raw;
299
+ await socket.sendMessage(cid, {
300
+ react: {
301
+ text: emoji,
302
+ key: { remoteJid: cid, id, fromMe: me, ...(cid.endsWith('@g.us') && !me && { participant: author }) },
303
+ },
227
304
  });
228
305
  ok = true;
229
306
  }
230
307
  return ok;
231
308
  }
232
- /** Reenvía el mensaje a un destino (CID, Chat o Contact). */
233
- async forward(target) {
234
- const { _wa, _doc } = this;
235
- const to_cid = typeof target === 'string'
236
- ? target
237
- : target instanceof chat_1.Chat
238
- ? target.id
239
- : (await target.chat()).id;
309
+ /**
310
+ * Destaca o quita el destacado del mensaje.
311
+ * Stars or unstars the message.
312
+ *
313
+ * @param value - true destaca / true stars
314
+ * @returns true si se envió / true when sent
315
+ */
316
+ async star(value) {
240
317
  let ok = false;
241
- if (_wa._socket) {
242
- const jid = await _wa._resolve_jid(to_cid);
243
- if (jid) {
244
- if (_doc.raw.message) {
245
- try {
246
- const wa_msg = (0, baileys_1.generateWAMessageFromContent)(jid, (0, baileys_1.generateForwardMessageContent)(_doc.raw, false), { userJid: _wa._socket.user?.id ?? '' });
247
- if (wa_msg.message && wa_msg.key?.id) {
248
- await _wa._socket.relayMessage(jid, wa_msg.message, { messageId: wa_msg.key.id });
249
- ok = true;
250
- }
251
- }
252
- catch {
253
- /* fallback below */
254
- }
255
- }
256
- if (!ok) {
257
- const buf = await this.content();
258
- if (buf.length > 0) {
259
- if (_doc.type === 'text') {
260
- ok = (await _wa.Message.text(jid, buf.toString())) !== null;
261
- }
262
- else if (_doc.type === 'image') {
263
- ok =
264
- (await _wa.Message.image(jid, buf, { caption: _doc.caption || undefined })) !==
265
- null;
266
- }
267
- else if (_doc.type === 'video') {
268
- ok =
269
- (await _wa.Message.video(jid, buf, { caption: _doc.caption || undefined })) !==
270
- null;
271
- }
272
- else if (_doc.type === 'audio') {
273
- ok = (await _wa.Message.audio(jid, buf)) !== null;
274
- }
275
- else if (_doc.type === 'location') {
276
- try {
277
- ok =
278
- (await _wa.Message.location(jid, JSON.parse(buf.toString()))) !== null;
279
- }
280
- catch {
281
- /* invalid payload */
282
- }
283
- }
284
- }
285
- }
286
- }
318
+ const socket = (0, internal_1.internals)(this._wa).socket;
319
+ if (socket) {
320
+ const doc = this._raw;
321
+ await socket.chatModify({ star: { messages: [{ id: doc.id, fromMe: doc.me }], star: value } }, doc.cid);
322
+ doc.starred = value;
323
+ await this._wa.engine.set(`/chat/${doc.cid}/message/${doc.id}`, (0, store_1.serialize)(doc), doc.created_at);
324
+ ok = true;
287
325
  }
288
326
  return ok;
289
327
  }
290
- /** Marca el mensaje como leído. */
328
+ /**
329
+ * Marca el mensaje como leído.
330
+ * Marks the message as read.
331
+ *
332
+ * @returns true si se envió / true when sent
333
+ */
291
334
  async seen() {
292
- const { _wa, _doc } = this;
293
335
  let ok = false;
294
- if (_wa._socket) {
295
- const is_group = _doc.cid.endsWith('@g.us');
296
- await _wa._socket.readMessages([
297
- { remoteJid: _doc.cid, id: _doc.id, participant: is_group ? _doc.author : undefined },
336
+ const socket = (0, internal_1.internals)(this._wa).socket;
337
+ if (socket) {
338
+ const { cid, id, author } = this._raw;
339
+ await socket.readMessages([
340
+ { remoteJid: cid, id, participant: cid.endsWith('@g.us') ? author : undefined },
298
341
  ]);
299
342
  ok = true;
300
343
  }
301
344
  return ok;
302
345
  }
303
- /** Destaca/retira destacado del mensaje. */
304
- async star(value) {
305
- const { _wa: wa, _doc: doc } = this;
346
+ /**
347
+ * Edita el caption del mensaje propio (texto, imagen o video).
348
+ * Edits the own message caption (text, image or video).
349
+ *
350
+ * @param caption - Texto nuevo / New text
351
+ * @returns true si se editó / true when edited
352
+ */
353
+ async edit(caption) {
354
+ const doc = this._raw;
306
355
  let ok = false;
307
- if (wa._socket) {
308
- await wa._socket.chatModify({
309
- star: { messages: [{ id: doc.id, fromMe: doc.me }], star: value },
310
- }, doc.cid);
311
- doc.starred = value;
312
- await wa.engine.set(`/chat/${doc.cid}/message/${doc.id}`, (0, store_1.serialize)(doc));
313
- ok = true;
356
+ const socket = (0, internal_1.internals)(this._wa).socket;
357
+ if (socket && doc.me) {
358
+ if (doc.type === 'text') {
359
+ await socket.sendMessage(doc.cid, {
360
+ text: caption,
361
+ edit: { remoteJid: doc.cid, id: doc.id, fromMe: true },
362
+ });
363
+ const content_type = (0, baileys_1.getContentType)(doc.raw.message ?? {});
364
+ doc.raw.message =
365
+ content_type === 'conversation' ? { conversation: caption } : { extendedTextMessage: { text: caption } };
366
+ ok = true;
367
+ }
368
+ else if (doc.type === 'image' || doc.type === 'video') {
369
+ const media_key = doc.type === 'image' ? 'imageMessage' : 'videoMessage';
370
+ const media = doc.raw.message?.[media_key];
371
+ if (media) {
372
+ const edited = { [media_key]: { ...media, caption } };
373
+ await socket.relayMessage(doc.cid, {
374
+ protocolMessage: {
375
+ key: { remoteJid: doc.cid, id: doc.id, fromMe: true },
376
+ type: baileys_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
377
+ editedMessage: edited,
378
+ timestampMs: Date.now(),
379
+ },
380
+ }, { messageId: (0, baileys_1.generateMessageID)() });
381
+ doc.raw.message = { ...doc.raw.message, ...edited };
382
+ ok = true;
383
+ }
384
+ }
385
+ if (ok) {
386
+ doc.caption = caption;
387
+ doc.edited = true;
388
+ await this._wa.engine.set(`/chat/${doc.cid}/message/${doc.id}`, (0, store_1.serialize)(doc), doc.created_at);
389
+ }
314
390
  }
315
391
  return ok;
316
392
  }
317
- /** Elimina el mensaje. `all=true` (default) borra para todos; `all=false` borra sólo en mi dispositivo. */
318
- async delete(all = true) {
319
- const { _wa: wa, _doc: doc } = this;
393
+ /**
394
+ * Reenvía el mensaje a otro chat.
395
+ * Forwards the message to another chat.
396
+ *
397
+ * @param target - CID, Chat o Contact destino / Target CID, Chat or Contact
398
+ * @returns true si se reenvió / true when forwarded
399
+ */
400
+ async forward(target) {
401
+ const doc = this._raw;
402
+ const to_cid = typeof target === 'string' ? target : target instanceof chat_1.Chat ? target._raw.id : (target.jid ?? target.lid ?? '');
320
403
  let ok = false;
321
- if (wa._socket) {
404
+ const socket = (0, internal_1.internals)(this._wa).socket;
405
+ if (socket && to_cid) {
406
+ const jid = await (0, internal_1.internals)(this._wa).resolve_jid(to_cid);
407
+ if (jid && doc.raw.message) {
408
+ try {
409
+ const wa_msg = (0, baileys_1.generateWAMessageFromContent)(jid, (0, baileys_1.generateForwardMessageContent)(doc.raw, false), {
410
+ userJid: socket.user?.id ?? '',
411
+ });
412
+ if (wa_msg.message && wa_msg.key?.id) {
413
+ await socket.relayMessage(jid, wa_msg.message, { messageId: wa_msg.key.id });
414
+ ok = true;
415
+ }
416
+ }
417
+ catch {
418
+ /* forward content may be unsupported */
419
+ }
420
+ }
421
+ }
422
+ return ok;
423
+ }
424
+ /**
425
+ * Elimina el mensaje: solo en mi dispositivo por defecto, para todos con `true`.
426
+ * Deletes the message: this device only by default, for everyone with `true`.
427
+ *
428
+ * @param all - true elimina para todos / true deletes for everyone
429
+ * @returns true si se eliminó / true when deleted
430
+ */
431
+ async delete(all = false) {
432
+ const doc = this._raw;
433
+ let ok = false;
434
+ const socket = (0, internal_1.internals)(this._wa).socket;
435
+ if (socket) {
322
436
  if (all) {
323
- await wa._socket.sendMessage(doc.cid, {
324
- delete: { remoteJid: doc.cid, id: doc.id, fromMe: doc.me },
325
- });
437
+ await socket.sendMessage(doc.cid, { delete: { remoteJid: doc.cid, id: doc.id, fromMe: doc.me } });
326
438
  }
327
439
  else {
328
- await wa._socket.chatModify({
440
+ await socket.chatModify({
329
441
  deleteForMe: {
330
442
  deleteMedia: false,
331
443
  key: { remoteJid: doc.cid, id: doc.id, fromMe: doc.me },
@@ -333,166 +445,368 @@ class Message {
333
445
  },
334
446
  }, doc.cid);
335
447
  }
336
- await wa.engine.unset(`/chat/${doc.cid}/message/${doc.id}`);
448
+ await this._wa.engine.unset(`/chat/${doc.cid}/message/${doc.id}`);
337
449
  ok = true;
338
450
  }
339
451
  return ok;
340
452
  }
341
- /** Edita el texto/caption del mensaje (solo propios editables). */
342
- async edit(text) {
343
- const { _wa: wa, _doc: doc } = this;
344
- let ok = false;
345
- if (wa._socket && doc.me) {
346
- try {
347
- await wa._socket.sendMessage(doc.cid, {
348
- text,
349
- edit: { remoteJid: doc.cid, id: doc.id, fromMe: true },
350
- });
351
- const content_type = (0, baileys_1.getContentType)(doc.raw.message ?? {});
352
- if (content_type === 'conversation') {
353
- doc.raw.message = { conversation: text };
354
- }
355
- else if (content_type === 'extendedTextMessage') {
356
- doc.raw.message = { extendedTextMessage: { text } };
357
- }
358
- doc.caption = text;
359
- doc.edited = true;
360
- await wa.engine.set(`/chat/${doc.cid}/message/${doc.id}`, (0, store_1.serialize)(doc));
361
- ok = true;
362
- }
363
- catch {
364
- ok = false;
365
- }
366
- }
367
- return ok;
453
+ /** Responde con texto. / Replies with text. */
454
+ async text(caption, extra = {}) {
455
+ return Message.text(this._wa, this._raw.cid, caption, { ...extra, mid: this._raw.id });
368
456
  }
369
- /** Observa cambios sobre este mensaje. Retorna unsubscribe. / Watches this message. Returns unsubscribe. */
370
- watch(handler) {
371
- const cid = this.cid;
372
- const id = this.id;
373
- return this._wa.on('message:updated', (updated) => {
374
- if (updated.cid === cid && updated.id === id) {
375
- handler(updated);
376
- }
377
- });
457
+ /** Responde con imagen. / Replies with an image. */
458
+ async image(buf, extra = {}) {
459
+ return Message.image(this._wa, this._raw.cid, buf, { ...extra, mid: this._raw.id });
378
460
  }
379
- /** Responde con texto. */
380
- async text(caption, opts = {}) {
381
- return this._wa.Message.text(this.cid, caption, { ...opts, mid: this.id });
461
+ /** Responde con video. / Replies with a video. */
462
+ async video(buf, extra = {}) {
463
+ return Message.video(this._wa, this._raw.cid, buf, { ...extra, mid: this._raw.id });
382
464
  }
383
- /** Responde con imagen. */
384
- async image(buf, opts = {}) {
385
- return this._wa.Message.image(this.cid, buf, { ...opts, mid: this.id });
465
+ /** Responde con audio. / Replies with audio. */
466
+ async audio(buf, extra = {}) {
467
+ return Message.audio(this._wa, this._raw.cid, buf, { ...extra, mid: this._raw.id });
386
468
  }
387
- /** Responde con video. */
388
- async video(buf, opts = {}) {
389
- return this._wa.Message.video(this.cid, buf, { ...opts, mid: this.id });
469
+ /** Responde con ubicación. / Replies with a location. */
470
+ async location(loc, extra = {}) {
471
+ return Message.location(this._wa, this._raw.cid, loc, { ...extra, mid: this._raw.id });
390
472
  }
391
- /** Responde con audio. */
392
- async audio(buf, opts = {}) {
393
- return this._wa.Message.audio(this.cid, buf, { ...opts, mid: this.id });
473
+ /** Responde con encuesta. / Replies with a poll. */
474
+ async poll(input, extra = {}) {
475
+ return Message.poll(this._wa, this._raw.cid, input, { ...extra, mid: this._raw.id });
394
476
  }
395
- /** Responde con ubicación. */
396
- async location(loc, opts = {}) {
397
- return this._wa.Message.location(this.cid, loc, { ...opts, mid: this.id });
477
+ /** Responde con documento. / Replies with a document. */
478
+ async document(buf, extra) {
479
+ return Message.document(this._wa, this._raw.cid, buf, { ...extra, mid: this._raw.id });
398
480
  }
399
- /** Responde con encuesta. */
400
- async poll(poll, opts = {}) {
401
- return this._wa.Message.poll(this.cid, poll, { ...opts, mid: this.id });
481
+ /** Responde con tarjeta(s) de contacto. / Replies with contact card(s). */
482
+ async vcard(contacts, extra = {}) {
483
+ return Message.vcard(this._wa, this._raw.cid, contacts, { ...extra, mid: this._raw.id });
402
484
  }
403
- /** Responde con documento. */
404
- async document(buf, opts) {
405
- return this._wa.Message.document(this.cid, buf, { ...opts, mid: this.id });
485
+ /** Responde con evento. / Replies with an event. */
486
+ async event(data, extra = {}) {
487
+ return Message.event(this._wa, this._raw.cid, data, { ...extra, mid: this._raw.id });
488
+ }
489
+ /**
490
+ * Obtiene un mensaje por chat y id.
491
+ * Retrieves a message by chat and id.
492
+ *
493
+ * @param wa - Cliente dueño / Owner client
494
+ * @param cid - Identificador del chat / Chat identifier
495
+ * @param mid - Identificador del mensaje / Message identifier
496
+ * @returns Mensaje o null / Message or null
497
+ */
498
+ static async get(wa, cid, mid) {
499
+ const jid = await (0, internal_1.internals)(wa).resolve_jid(cid);
500
+ if (jid) {
501
+ const doc = (0, store_1.deserialize)(await wa.engine.get(`/chat/${jid}/message/${mid}`));
502
+ if (doc)
503
+ return message(wa, doc);
504
+ }
505
+ return null;
406
506
  }
407
- /** Responde con tarjeta(s) de contacto. */
408
- async vcard(contacts, opts = {}) {
409
- return this._wa.Message.vcard(this.cid, contacts, { ...opts, mid: this.id });
507
+ /**
508
+ * Pagina los mensajes de un chat desde el más reciente.
509
+ * Paginates chat messages from the most recent one.
510
+ *
511
+ * @param wa - Cliente dueño / Owner client
512
+ * @param cid - Identificador del chat / Chat identifier
513
+ * @param offset - Desplazamiento / Offset
514
+ * @param limit - Tamaño de página / Page size
515
+ * @returns Página de mensajes / Message page
516
+ */
517
+ static async list(wa, cid, offset = 0, limit = 50) {
518
+ const jid = await (0, internal_1.internals)(wa).resolve_jid(cid);
519
+ if (jid) {
520
+ return (await wa.engine.list(`/chat/${jid}/message`, offset, limit))
521
+ .map((raw) => (0, store_1.deserialize)(raw))
522
+ .filter((doc) => doc !== null)
523
+ .map((doc) => message(wa, doc));
524
+ }
525
+ return [];
526
+ }
527
+ /** Envía texto. / Sends text. */
528
+ static async text(wa, cid, caption, extra = {}) {
529
+ return send(wa, cid, { text: caption }, undefined, extra);
530
+ }
531
+ /** Envía imagen. / Sends an image. */
532
+ static async image(wa, cid, buf, extra = {}) {
533
+ return send(wa, cid, { image: buf, caption: extra.caption }, buf, extra);
534
+ }
535
+ /** Envía video. / Sends a video. */
536
+ static async video(wa, cid, buf, extra = {}) {
537
+ return send(wa, cid, { video: buf, caption: extra.caption }, buf, extra);
538
+ }
539
+ /** Envía audio. / Sends audio. */
540
+ static async audio(wa, cid, buf, extra = {}) {
541
+ return send(wa, cid, { audio: buf, ptt: extra.ptt ?? true }, buf, extra);
542
+ }
543
+ /** Envía ubicación. / Sends a location. */
544
+ static async location(wa, cid, loc, extra = {}) {
545
+ return send(wa, cid, { location: { degreesLatitude: loc.lat, degreesLongitude: loc.lng } }, undefined, extra);
546
+ }
547
+ /** Envía encuesta. / Sends a poll. */
548
+ static async poll(wa, cid, input, extra = {}) {
549
+ const multiple = extra.multiple ?? false;
550
+ return send(wa, cid, {
551
+ poll: {
552
+ name: input.content,
553
+ values: input.options.map((option) => option.content),
554
+ selectableCount: multiple ? 0 : 1,
555
+ },
556
+ }, undefined, extra, { multiple });
557
+ }
558
+ /** Envía documento. / Sends a document. */
559
+ static async document(wa, cid, buf, extra) {
560
+ return send(wa, cid, { document: buf, fileName: extra.file_name, mimetype: extra.mimetype ?? 'application/octet-stream', caption: extra.caption }, buf, extra);
561
+ }
562
+ /** Envía tarjeta(s) de contacto. / Sends contact card(s). */
563
+ static async vcard(wa, cid, contacts, extra = {}) {
564
+ const built = contacts.map((entry) => ({
565
+ displayName: entry.name,
566
+ vcard: [
567
+ 'BEGIN:VCARD',
568
+ 'VERSION:3.0',
569
+ `FN:${entry.name}`,
570
+ `TEL;type=CELL;waid=${entry.phone.replace(/\D+/g, '')}:${entry.phone}`,
571
+ 'END:VCARD',
572
+ ].join('\n'),
573
+ }));
574
+ return send(wa, cid, { contacts: { contacts: built } }, Buffer.from(built.map((entry) => entry.vcard).join('\n'), 'utf-8'), extra);
410
575
  }
411
- /** Responde con evento. */
412
- async event(data, opts = {}) {
413
- return this._wa.Message.event(this.cid, data, { ...opts, mid: this.id });
576
+ /** Envía evento. / Sends an event. */
577
+ static async event(wa, cid, data, extra = {}) {
578
+ const binary = Buffer.from(JSON.stringify({ name: data.name, caption: data.caption, start: data.start.getTime(), end: data.end?.getTime() ?? null }), 'utf-8');
579
+ return send(wa, cid, {
580
+ event: {
581
+ name: data.name,
582
+ description: data.caption,
583
+ startDate: data.start,
584
+ endDate: data.end,
585
+ location: data.place ? { degreesLatitude: data.place.lat, degreesLongitude: data.place.lng } : undefined,
586
+ },
587
+ }, binary, extra);
588
+ }
589
+ /** Reacciona a un mensaje por id. / Reacts to a message by id. */
590
+ static async react(wa, cid, mid, emoji) {
591
+ const msg = await Message.get(wa, cid, mid);
592
+ return msg ? msg.react(emoji) : false;
593
+ }
594
+ /** Destaca un mensaje por id. / Stars a message by id. */
595
+ static async star(wa, cid, mid, value) {
596
+ const msg = await Message.get(wa, cid, mid);
597
+ return msg ? msg.star(value) : false;
598
+ }
599
+ /** Marca un mensaje como leído por id. / Marks a message as read by id. */
600
+ static async seen(wa, cid, mid) {
601
+ const msg = await Message.get(wa, cid, mid);
602
+ return msg ? msg.seen() : false;
603
+ }
604
+ /** Edita un mensaje por id. / Edits a message by id. */
605
+ static async edit(wa, cid, mid, caption) {
606
+ const msg = await Message.get(wa, cid, mid);
607
+ return msg ? msg.edit(caption) : false;
608
+ }
609
+ /** Reenvía un mensaje por id. / Forwards a message by id. */
610
+ static async forward(wa, cid, mid, target) {
611
+ const msg = await Message.get(wa, cid, mid);
612
+ return msg ? msg.forward(target) : false;
613
+ }
614
+ /** Elimina un mensaje por id. / Deletes a message by id. */
615
+ static async delete(wa, cid, mid, all = false) {
616
+ const msg = await Message.get(wa, cid, mid);
617
+ return msg ? msg.delete(all) : false;
618
+ }
619
+ /** Reacciones de un mensaje por id. / Reactions of a message by id. */
620
+ static async reactions(wa, cid, mid) {
621
+ const msg = await Message.get(wa, cid, mid);
622
+ return msg ? msg.reactions() : [];
414
623
  }
415
624
  }
416
625
  exports.Message = Message;
417
626
  /**
418
- * Mensaje de texto. Override `content()` para retornar el caption como Buffer sin pasar por engine.
419
- * Text message. Overrides `content()` returning caption as Buffer directly.
627
+ * Mensaje de texto; `preview()` expone la tarjeta del enlace embebido.
628
+ * Text message; `preview()` exposes the embedded link card.
420
629
  */
421
630
  class Text extends Message {
422
- async content() {
423
- return Buffer.from(this.caption, 'utf-8');
424
- }
425
- }
426
- exports.Text = Text;
427
- /** @internal Helper compartido por media classes: stream del binario (cache → download). */
428
- async function _media_stream(msg) {
429
- const wa = msg._wa;
430
- const doc = msg._doc;
431
- const cached = (0, store_1.deserialize)(await wa.engine.get(`/chat/${doc.cid}/message/${doc.id}/content`));
432
- if (cached?.data) {
433
- return node_stream_1.Readable.from(Buffer.from(cached.data, 'base64'));
434
- }
435
- if (wa._socket) {
436
- try {
437
- return (await (0, baileys_1.downloadMediaMessage)(doc.raw, 'stream', {}));
438
- }
439
- catch {
440
- /* fallback empty */
631
+ /**
632
+ * Preview del enlace del texto, o null cuando no trae metadata.
633
+ * Text link preview, or null when it carries no metadata.
634
+ *
635
+ * @returns { link, name, content, thumb } o null / { link, name, content, thumb } or null
636
+ */
637
+ async preview() {
638
+ const ext = this._raw.raw.message?.extendedTextMessage;
639
+ if (ext?.matchedText && (ext.title || ext.description)) {
640
+ return {
641
+ link: ext.matchedText,
642
+ name: ext.title ?? null,
643
+ content: ext.description ?? null,
644
+ thumb: to_buffer(ext.jpegThumbnail),
645
+ };
441
646
  }
647
+ return null;
442
648
  }
443
- return node_stream_1.Readable.from(Buffer.alloc(0));
444
- }
445
- /** @internal Acumula un Readable en Buffer. */
446
- async function _drain(readable) {
447
- const chunks = [];
448
- for await (const chunk of readable) {
449
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
450
- }
451
- return Buffer.concat(chunks);
452
649
  }
650
+ exports.Text = Text;
453
651
  /**
454
- * Mensaje de imagen. Hereda `stream()` de la clase base; `content()` drena el stream.
455
- * Image message. Inherits `stream()` from the base class; `content()` drains the stream.
652
+ * Mensaje de imagen: dimensiones, peso y miniatura.
653
+ * Image message: dimensions, size and thumbnail.
456
654
  */
457
655
  class Image extends Message {
656
+ /** @internal */
657
+ get _media() {
658
+ return unwrap(this._raw.raw.message ?? {}).imageMessage;
659
+ }
660
+ /** Ancho en píxeles. / Width in pixels. */
661
+ get width() {
662
+ return this._media?.width ?? 0;
663
+ }
664
+ /** Alto en píxeles. / Height in pixels. */
665
+ get height() {
666
+ return this._media?.height ?? 0;
667
+ }
668
+ /** Peso en bytes. / Size in bytes. */
669
+ get size() {
670
+ return to_number(this._media?.fileLength);
671
+ }
672
+ /**
673
+ * Miniatura JPEG embebida, o null.
674
+ * Embedded JPEG thumbnail, or null.
675
+ *
676
+ * @returns Buffer de la miniatura o null / Thumbnail buffer or null
677
+ */
678
+ async thumb() {
679
+ return to_buffer(this._media?.jpegThumbnail);
680
+ }
458
681
  async content() {
459
- return _drain(await this.stream());
682
+ return drain(await this.stream());
460
683
  }
461
684
  }
462
685
  exports.Image = Image;
463
686
  /**
464
- * Mensaje de video. Hereda `stream()` de la clase base; `content()` drena el stream.
465
- * Video message. Inherits `stream()` from the base class; `content()` drains the stream.
687
+ * Mensaje de video: dimensiones, duración, peso y miniatura.
688
+ * Video message: dimensions, duration, size and thumbnail.
466
689
  */
467
690
  class Video extends Message {
691
+ /** @internal */
692
+ get _media() {
693
+ return unwrap(this._raw.raw.message ?? {}).videoMessage;
694
+ }
695
+ /** Ancho en píxeles. / Width in pixels. */
696
+ get width() {
697
+ return this._media?.width ?? 0;
698
+ }
699
+ /** Alto en píxeles. / Height in pixels. */
700
+ get height() {
701
+ return this._media?.height ?? 0;
702
+ }
703
+ /** Duración en segundos. / Duration in seconds. */
704
+ get duration() {
705
+ return this._media?.seconds ?? 0;
706
+ }
707
+ /** Peso en bytes. / Size in bytes. */
708
+ get size() {
709
+ return to_number(this._media?.fileLength);
710
+ }
711
+ /**
712
+ * Miniatura JPEG embebida, o null.
713
+ * Embedded JPEG thumbnail, or null.
714
+ *
715
+ * @returns Buffer de la miniatura o null / Thumbnail buffer or null
716
+ */
717
+ async thumb() {
718
+ return to_buffer(this._media?.jpegThumbnail);
719
+ }
468
720
  async content() {
469
- return _drain(await this.stream());
721
+ return drain(await this.stream());
470
722
  }
471
723
  }
472
724
  exports.Video = Video;
473
725
  /**
474
- * Mensaje de audio. Hereda `stream()` de la clase base; `content()` drena el stream.
475
- * `ptt` indica si es nota de voz (push-to-talk).
476
- * Audio message. Inherits `stream()` from the base class; `content()` drains the stream.
477
- * `ptt` flags voice notes.
726
+ * Mensaje de audio: nota de voz o archivo, con forma de onda del protocolo.
727
+ * Audio message: voice note or file, with the protocol waveform.
478
728
  */
479
729
  class Audio extends Message {
480
- /** true si es nota de voz (push-to-talk). / true if push-to-talk voice note. */
730
+ /** @internal */
731
+ get _media() {
732
+ return unwrap(this._raw.raw.message ?? {}).audioMessage;
733
+ }
734
+ /** true si es nota de voz. / true when push-to-talk. */
481
735
  get ptt() {
482
- return this._doc.raw.message?.audioMessage?.ptt === true;
736
+ return this._media?.ptt === true;
737
+ }
738
+ /** Duración en segundos. / Duration in seconds. */
739
+ get duration() {
740
+ return this._media?.seconds ?? 0;
741
+ }
742
+ /** Peso en bytes. / Size in bytes. */
743
+ get size() {
744
+ return to_number(this._media?.fileLength);
745
+ }
746
+ /** Forma de onda 0-100 lista para pintar. / Paint-ready 0-100 waveform. */
747
+ get waveform() {
748
+ const wave = this._media?.waveform;
749
+ const bytes = wave instanceof Uint8Array ? wave : typeof wave === 'string' ? Buffer.from(wave, 'base64') : Buffer.alloc(0);
750
+ return Array.from(bytes);
483
751
  }
484
752
  async content() {
485
- return _drain(await this.stream());
753
+ return drain(await this.stream());
486
754
  }
487
755
  }
488
756
  exports.Audio = Audio;
489
757
  /**
490
- * Mensaje de ubicación. Agrega getters sync `lat`, `lng`, `link` derivados del raw.
491
- * Location message. Adds sync getters `lat`, `lng`, `link` derived from raw.
758
+ * Mensaje de sticker: dimensiones, peso y animación.
759
+ * Sticker message: dimensions, size and animation.
760
+ */
761
+ class Sticker extends Message {
762
+ /** @internal */
763
+ get _media() {
764
+ return unwrap(this._raw.raw.message ?? {}).stickerMessage;
765
+ }
766
+ /** Ancho en píxeles. / Width in pixels. */
767
+ get width() {
768
+ return this._media?.width ?? 0;
769
+ }
770
+ /** Alto en píxeles. / Height in pixels. */
771
+ get height() {
772
+ return this._media?.height ?? 0;
773
+ }
774
+ /** true si el sticker es animado. / true when animated. */
775
+ get animated() {
776
+ return this._media?.isAnimated === true;
777
+ }
778
+ /** Peso en bytes. / Size in bytes. */
779
+ get size() {
780
+ return to_number(this._media?.fileLength);
781
+ }
782
+ async content() {
783
+ return drain(await this.stream());
784
+ }
785
+ }
786
+ exports.Sticker = Sticker;
787
+ /**
788
+ * Mensaje de documento; el MIME real vive en `mime` de la base.
789
+ * Document message; the actual MIME lives in the base `mime`.
492
790
  */
493
- class Gps extends Message {
791
+ class Document extends Message {
792
+ /** Peso en bytes. / Size in bytes. */
793
+ get size() {
794
+ const media = unwrap(this._raw.raw.message ?? {}).documentMessage;
795
+ return to_number(media?.fileLength);
796
+ }
797
+ async content() {
798
+ return drain(await this.stream());
799
+ }
800
+ }
801
+ exports.Document = Document;
802
+ /**
803
+ * Mensaje de ubicación, fija o en vivo.
804
+ * Location message, static or live.
805
+ */
806
+ class Location extends Message {
807
+ /** @internal */
494
808
  get _loc() {
495
- return this._doc.raw.message?.locationMessage ?? this._doc.raw.message?.liveLocationMessage;
809
+ return this._raw.raw.message?.locationMessage ?? this._raw.raw.message?.liveLocationMessage;
496
810
  }
497
811
  /** Latitud en grados. / Latitude in degrees. */
498
812
  get lat() {
@@ -502,251 +816,187 @@ class Gps extends Message {
502
816
  get lng() {
503
817
  return this._loc?.degreesLongitude ?? 0;
504
818
  }
505
- /** URL de Google Maps apuntando a la coordenada. / Google Maps URL for the coordinate. */
506
- get link() {
507
- return `https://www.google.com/maps/@${this.lat},${this.lng},15z`;
508
- }
509
819
  /** true si es ubicación en tiempo real. / true when live location. */
510
820
  get live() {
511
- return Boolean(this._doc.raw.message?.liveLocationMessage);
821
+ return Boolean(this._raw.raw.message?.liveLocationMessage);
822
+ }
823
+ /** URL de Google Maps de la coordenada. / Google Maps URL for the coordinate. */
824
+ get link() {
825
+ return `https://www.google.com/maps/@${this.lat},${this.lng},15z`;
512
826
  }
513
827
  }
514
- exports.Gps = Gps;
828
+ exports.Location = Location;
515
829
  /**
516
- * Mensaje de encuesta. `caption` es la pregunta (heredada); agrega `options[]` con conteo y `multiple`.
517
- * Poll message. `caption` is the question (inherited); adds `options[]` with counts and `multiple`.
830
+ * Mensaje de encuesta: opciones con conteo, votos por contacto y voto propio.
831
+ * Poll message: options with counts, per-contact votes and self-voting.
518
832
  */
519
833
  class Poll extends Message {
834
+ /** @internal */
520
835
  get _poll() {
521
- const m = this._doc.raw.message;
522
- return m?.pollCreationMessage ?? m?.pollCreationMessageV2 ?? m?.pollCreationMessageV3;
836
+ const msg = this._raw.raw.message;
837
+ return msg?.pollCreationMessage ?? msg?.pollCreationMessageV2 ?? msg?.pollCreationMessageV3;
838
+ }
839
+ /** @internal Updates de voto con los bytes normalizados post-engine. / Vote updates with post-engine normalized bytes. */
840
+ get _updates() {
841
+ return (this._raw.raw.pollUpdates ?? []).map((update) => ({
842
+ ...update,
843
+ vote: update.vote
844
+ ? {
845
+ ...update.vote,
846
+ selectedOptions: (update.vote.selectedOptions ?? []).map((option) => typeof option === 'string' ? Buffer.from(option, 'base64') : option),
847
+ }
848
+ : update.vote,
849
+ }));
523
850
  }
524
- /**
525
- * true si admite múltiples respuestas. Lee primero el flag explícito persistido
526
- * al enviar (caso propio, donde WhatsApp pierde el discriminador en el echo);
527
- * fallback al `selectableOptionsCount` del proto (polls foráneos o de UI móvil).
528
- * true if the poll accepts multiple answers. Prefers the persisted send-time
529
- * flag (own polls, since WhatsApp drops the discriminator on echo); falls back
530
- * to the proto `selectableOptionsCount` (foreign or mobile-UI polls).
531
- */
851
+ /** true si admite varias respuestas. / true when multi-select. */
532
852
  get multiple() {
533
- if (typeof this._doc.multiple === 'boolean') {
534
- return this._doc.multiple;
853
+ if (typeof this._raw.multiple === 'boolean') {
854
+ return this._raw.multiple;
535
855
  }
536
856
  return (this._poll?.selectableOptionsCount ?? 1) !== 1;
537
857
  }
538
- /** Opciones con conteo de votos actualizado. / Options with up-to-date vote counts. */
858
+ /** Opciones con su conteo de votos. / Options with their vote counts. */
539
859
  get options() {
540
- const opts = this._poll?.options ?? [];
541
- const raw_updates = this._doc.raw.pollUpdates ?? [];
542
- // Normaliza selectedOptions de base64-string a Buffer (BufferJSON no reconstruye el tipo aquí)
543
- const updates = raw_updates.map((u) => ({
544
- ...u,
545
- vote: u.vote
546
- ? {
547
- ...u.vote,
548
- selectedOptions: (u.vote.selectedOptions ?? []).map((s) => typeof s === 'string' ? Buffer.from(s, 'base64') : s),
549
- }
550
- : u.vote,
551
- }));
552
- const aggregated = (0, baileys_1.getAggregateVotesInPollMessage)({ message: this._doc.raw.message ?? undefined, pollUpdates: updates }, this._wa._socket?.user?.id);
553
- const counts = new Map(aggregated.map((a) => [a.name, a.voters.length]));
554
- return opts.map((o) => ({
555
- content: o.optionName ?? '',
556
- count: counts.get(o.optionName ?? '') ?? 0,
860
+ const aggregated = (0, baileys_1.getAggregateVotesInPollMessage)({ message: this._raw.raw.message ?? undefined, pollUpdates: this._updates }, (0, internal_1.internals)(this._wa).socket?.user?.id);
861
+ const counts = new Map(aggregated.map((entry) => [entry.name, entry.voters.length]));
862
+ return (this._poll?.options ?? []).map((option) => ({
863
+ name: option.optionName ?? '',
864
+ count: counts.get(option.optionName ?? '') ?? 0,
557
865
  }));
558
866
  }
559
867
  /**
560
- * Vota en la encuesta. Acepta un índice o lista de índices (para `multiple`).
561
- * Votes in the poll. Accepts a single index or list (for `multiple`).
868
+ * Votos individuales: opción elegida y teléfono del votante.
869
+ * Individual votes: chosen option and voter phone.
870
+ *
871
+ * @returns Lista de votos / Vote list
872
+ */
873
+ async votes() {
874
+ const aggregated = (0, baileys_1.getAggregateVotesInPollMessage)({ message: this._raw.raw.message ?? undefined, pollUpdates: this._updates }, (0, internal_1.internals)(this._wa).socket?.user?.id);
875
+ const result = [];
876
+ for (const entry of aggregated) {
877
+ for (const voter of entry.voters) {
878
+ const jid = await (0, internal_1.internals)(this._wa).resolve_jid(voter);
879
+ result.push({ name: entry.name, contact: (jid ?? voter).split('@')[0].split(':')[0] });
880
+ }
881
+ }
882
+ return result;
883
+ }
884
+ /**
885
+ * Vota en la encuesta con uno o varios índices. Cifra el voto (HMAC+AES-GCM) y lo
886
+ * enruta al chat @lid con la identidad LID propia. Best-effort: el voto entrante
887
+ * descifra correcto, pero WhatsApp no propaga el voto emitido desde un dispositivo
888
+ * vinculado (companion).
889
+ * Votes in the poll with one or more indexes. Encrypts the vote (HMAC+AES-GCM) and
890
+ * routes it to the @lid chat with the own LID identity. Best-effort: incoming votes
891
+ * decrypt fine, but WhatsApp does not propagate votes emitted from a linked
892
+ * (companion) device.
893
+ *
894
+ * @param index - Índice o índices de la opción / Option index or indexes
895
+ * @returns true si el voto se emitió / true when the vote was relayed
562
896
  */
563
897
  async select(index) {
564
- const { _wa, _doc } = this;
565
- const indices = Array.isArray(index) ? index : [index];
898
+ const doc = this._raw;
566
899
  const opts = this._poll?.options ?? [];
567
- const selected_options = indices
900
+ const selected_options = (Array.isArray(index) ? index : [index])
568
901
  .filter((i) => i >= 0 && i < opts.length)
569
902
  .map((i) => (0, baileys_1.sha256)(Buffer.from(opts[i].optionName ?? '')));
570
- // messageSecret puede llegar como Buffer (raw runtime) o string base64 (post-deserialize
571
- // del engine). Normaliza a Buffer antes de derivar el HMAC.
572
- // messageSecret may arrive as Buffer (runtime raw) or base64 string (post engine
573
- // deserialize). Normalize to Buffer before deriving the HMAC.
574
- const secret_raw = _doc.raw.message?.messageContextInfo?.messageSecret;
903
+ const secret_raw = doc.raw.message?.messageContextInfo?.messageSecret;
575
904
  const poll_enc_key = typeof secret_raw === 'string' ? Buffer.from(secret_raw, 'base64') : secret_raw;
576
- if (!poll_enc_key || !_wa._socket || selected_options.length === 0) {
905
+ const socket = (0, internal_1.internals)(this._wa).socket;
906
+ if (!poll_enc_key || !socket || selected_options.length === 0) {
577
907
  return false;
578
908
  }
579
- // La identidad propia del HMAC debe coincidir con la que baileys.relayMessage
580
- // usará al enviar ("ADDRESSING CONSISTENCY"): LID sólo en chats @lid, PN en
581
- // chats @s.whatsapp.net. Forzar LID siempre (fix 3.1.1) producía votos
582
- // indescifrables en chats PN: el receptor deriva la clave del JID del stanza.
583
- // Own HMAC identity must match what baileys.relayMessage uses on send
584
- // ("ADDRESSING CONSISTENCY"): LID only on @lid chats, PN on @s.whatsapp.net.
585
- // Always forcing LID (3.1.1 fix) made votes undecryptable on PN chats: the
586
- // receiver derives the key from the stanza's sender JID.
587
- const poll_key = _doc.raw.key ?? {};
588
- const self_id = _wa._socket.user?.id ?? '';
589
- const self_lid = _wa._socket.user?.lid ?? '';
590
- const self_for_chat = _doc.cid.endsWith('@lid') && self_lid ? self_lid : self_id;
591
- const voter_jid = (0, baileys_1.jidNormalizedUser)(self_for_chat);
592
- let poll_creator_raw;
593
- if (poll_key.fromMe) {
594
- poll_creator_raw = self_for_chat;
595
- }
596
- else if (poll_key.remoteJid?.endsWith('@lid')) {
597
- poll_creator_raw = poll_key.remoteJid;
909
+ const poll_key = doc.raw.key ?? {};
910
+ const self_id = socket.user?.id ?? '';
911
+ const self_lid = socket.user?.lid ?? '';
912
+ let dest = doc.cid;
913
+ if (poll_key.remoteJid?.endsWith('@lid')) {
914
+ dest = poll_key.remoteJid;
598
915
  }
599
- else {
600
- poll_creator_raw = (0, baileys_1.getKeyAuthor)(poll_key, self_id);
916
+ else if (!doc.cid.endsWith('@lid')) {
917
+ const contact_raw = (0, store_1.deserialize)(await this._wa.engine.get(`/contact/${doc.cid}`));
918
+ const mapped = await socket.signalRepository?.lidMapping?.getLIDForPN(doc.cid).catch(() => null);
919
+ dest = contact_raw?.lid ?? mapped ?? doc.cid;
601
920
  }
602
- const poll_creator_jid = (0, baileys_1.jidNormalizedUser)(poll_creator_raw);
603
- const poll_msg_id = this.id;
604
- // Derivar clave y encriptar el voto (mismo algoritmo que baileys.decryptPollVote)
921
+ const self_for_send = dest.endsWith('@lid') && self_lid ? self_lid : self_id;
922
+ const voter_jid = (0, baileys_1.jidNormalizedUser)(self_for_send);
923
+ const poll_creator_jid = (0, baileys_1.jidNormalizedUser)(poll_key.fromMe
924
+ ? self_for_send
925
+ : poll_key.remoteJid?.endsWith('@lid')
926
+ ? poll_key.remoteJid
927
+ : (0, baileys_1.getKeyAuthor)(poll_key, self_id));
605
928
  const sign = Buffer.concat([
606
- Buffer.from(poll_msg_id),
929
+ Buffer.from(doc.id),
607
930
  Buffer.from(poll_creator_jid),
608
931
  Buffer.from(voter_jid),
609
932
  Buffer.from('Poll Vote'),
610
933
  new Uint8Array([1]),
611
934
  ]);
612
- const key0 = (0, baileys_1.hmacSign)(poll_enc_key, new Uint8Array(32), 'sha256');
613
- const enc_key = (0, baileys_1.hmacSign)(sign, key0, 'sha256');
614
- const payload = baileys_1.proto.Message.PollVoteMessage.encode({
615
- selectedOptions: selected_options,
616
- }).finish();
617
- const aad = Buffer.from(`${poll_msg_id}\x00${voter_jid}`);
935
+ const enc_key = (0, baileys_1.hmacSign)(sign, (0, baileys_1.hmacSign)(poll_enc_key, new Uint8Array(32), 'sha256'), 'sha256');
618
936
  const enc_iv = (0, node_crypto_1.randomBytes)(12);
619
- const enc_payload = (0, baileys_1.aesEncryptGCM)(payload, enc_key, enc_iv, aad);
937
+ const enc_payload = (0, baileys_1.aesEncryptGCM)(baileys_1.proto.Message.PollVoteMessage.encode({ selectedOptions: selected_options }).finish(), enc_key, enc_iv, Buffer.from(`${doc.id}\x00${voter_jid}`));
620
938
  const msg_id = (0, baileys_1.generateMessageID)();
621
- await _wa._socket.relayMessage(_doc.cid, {
939
+ await socket.relayMessage(dest, {
622
940
  pollUpdateMessage: {
623
- pollCreationMessageKey: _doc.raw.key,
941
+ pollCreationMessageKey: dest === doc.cid ? doc.raw.key : { ...doc.raw.key, remoteJid: dest },
624
942
  vote: { encPayload: enc_payload, encIv: enc_iv },
625
943
  senderTimestampMs: Date.now(),
626
944
  },
627
945
  }, { messageId: msg_id });
628
- // baileys.relayMessage no echa upsert local al companion que envió el voto.
629
- // Mergemos el voto propio en el doc para que `options[].count` y el evento
630
- // `message:updated` reflejen el cambio sin esperar (nunca) un echo del servidor.
631
- // baileys.relayMessage doesn't emit a local upsert on the originating companion.
632
- // We merge the own vote into the doc so `options[].count` and the `message:updated`
633
- // event reflect the change without waiting for a server echo that never comes.
634
- const own_update_key = {
635
- remoteJid: _doc.raw.key?.remoteJid ?? _doc.cid,
636
- fromMe: true,
637
- id: msg_id,
638
- };
639
- (0, baileys_1.updateMessageWithPollUpdate)(_doc.raw, {
640
- pollUpdateMessageKey: own_update_key,
946
+ (0, baileys_1.updateMessageWithPollUpdate)(doc.raw, {
947
+ pollUpdateMessageKey: { remoteJid: doc.raw.key?.remoteJid ?? doc.cid, fromMe: true, id: msg_id },
641
948
  vote: { selectedOptions: selected_options },
642
949
  senderTimestampMs: Date.now(),
643
950
  });
644
- await _wa.engine.set(`/chat/${_doc.cid}/message/${_doc.id}`, (0, store_1.serialize)(_doc));
645
- _wa._event.emit('message:updated', this, await this.chat(), _wa);
951
+ await this._wa.engine.set(`/chat/${doc.cid}/message/${doc.id}`, (0, store_1.serialize)(doc), doc.created_at);
952
+ this._wa.emit('message:updated', this, await this.chat(), this._wa);
646
953
  return true;
647
954
  }
648
955
  }
649
956
  exports.Poll = Poll;
650
957
  /**
651
- * Mensaje de documento. WhatsApp permite enviar cualquier archivo (PDF, imagen,
652
- * audio, video, etc.) como documento; lo que lo distingue de image/video/audio es
653
- * el tipo de mensaje (`documentMessage`), no el mimetype. Hereda `stream()` de la
654
- * clase base; `content()` drena el stream (cache → download).
655
- * Document message. WhatsApp lets you send any file (PDF, image, audio, video…)
656
- * as a document; what sets it apart from image/video/audio is the message type
657
- * (`documentMessage`), not the mimetype. Inherits `stream()` from the base class;
658
- * `content()` drains the stream (cache → download).
659
- */
660
- class Document extends Message {
661
- get _doc_msg() {
662
- const m = this._doc.raw.message;
663
- return m?.documentMessage ?? m?.documentWithCaptionMessage?.message?.documentMessage;
664
- }
665
- /** Nombre del archivo. / File name. */
666
- get file_name() {
667
- return this._doc_msg?.fileName ?? '';
668
- }
669
- /** Tamaño en bytes (0 si se desconoce). / Size in bytes (0 if unknown). */
670
- get size() {
671
- return Number(this._doc_msg?.fileLength?.toString() ?? '0');
672
- }
673
- /** Número de páginas (PDF); 0 si no aplica. / Page count (PDF); 0 when not applicable. */
674
- get pages() {
675
- return this._doc_msg?.pageCount ?? 0;
676
- }
677
- /** Título del documento. / Document title. */
678
- get title() {
679
- return this._doc_msg?.title ?? '';
680
- }
681
- async content() {
682
- return _drain(await this.stream());
683
- }
684
- }
685
- exports.Document = Document;
686
- /**
687
- * Construye un vCard 3.0 mínimo con el teléfono enlazado como contacto de WhatsApp.
688
- * Builds a minimal vCard 3.0 with the phone linked as a WhatsApp contact.
689
- *
690
- * @param name - Nombre mostrado / Display name
691
- * @param phone - Teléfono en formato internacional / Phone in international format
692
- * @returns String vCard (VCF) / vCard (VCF) string
693
- */
694
- function build_vcard(name, phone) {
695
- const waid = phone.replace(/\D+/g, '');
696
- return [
697
- 'BEGIN:VCARD',
698
- 'VERSION:3.0',
699
- `FN:${name}`,
700
- `TEL;type=CELL;waid=${waid}:${phone}`,
701
- 'END:VCARD',
702
- ].join('\n');
703
- }
704
- /**
705
- * Mensaje de tarjeta(s) de contacto (vCard). Unifica `contactMessage` (uno) y
706
- * `contactsArrayMessage` (varios) bajo una sola lista `contacts`.
707
- * Contact card message (vCard). Unifies `contactMessage` (single) and
708
- * `contactsArrayMessage` (multiple) under a single `contacts` list.
958
+ * Mensaje de tarjeta(s) de contacto.
959
+ * Contact card(s) message.
709
960
  */
710
961
  class VCard extends Message {
711
- /** Contactos de la tarjeta con nombre y teléfono. / Card contacts with name and phone. */
962
+ /** Contactos de la tarjeta. / Card contacts. */
712
963
  get contacts() {
713
- const m = this._doc.raw.message;
714
- const raw = m?.contactsArrayMessage?.contacts ?? (m?.contactMessage ? [m.contactMessage] : []);
715
- return raw.map((c) => {
716
- const tel = (c.vcard ?? '').match(/TEL[^:]*:(.+)/);
717
- return { name: c.displayName ?? '', phone: tel ? tel[1].trim() : '' };
964
+ const msg = this._raw.raw.message;
965
+ const raw = msg?.contactsArrayMessage?.contacts ?? (msg?.contactMessage ? [msg.contactMessage] : []);
966
+ return raw.map((card) => {
967
+ const tel = (card.vcard ?? '').match(/TEL[^:]*:(.+)/);
968
+ return { name: card.displayName ?? '', phone: tel ? tel[1].trim() : '' };
718
969
  });
719
970
  }
720
971
  }
721
972
  exports.VCard = VCard;
722
973
  /**
723
- * Mensaje de evento de calendario (`eventMessage`): nombre, descripción, rango de
724
- * fechas, estado de cancelación, link de unión y ubicación.
725
- * Calendar event message (`eventMessage`): name, description, date range,
726
- * cancellation state, join link and location.
974
+ * Mensaje de evento de calendario.
975
+ * Calendar event message.
727
976
  */
728
977
  class Event extends Message {
978
+ /** @internal */
729
979
  get _event() {
730
- return this._doc.raw.message?.eventMessage;
980
+ return this._raw.raw.message?.eventMessage;
731
981
  }
732
982
  /** Nombre del evento. / Event name. */
733
983
  get name() {
734
984
  return this._event?.name ?? '';
735
985
  }
736
- /** Epoch ms de inicio. / Start epoch ms. */
986
+ /** Inicio en ISO UTC. / Start as ISO UTC. */
737
987
  get start() {
738
- return Number(this._event?.startTime?.toString() ?? '0') * 1000;
988
+ return new Date(to_number(this._event?.startTime) * 1000).toISOString();
739
989
  }
740
- /** Epoch ms de fin, o null. / End epoch ms, or null. */
990
+ /** Fin en ISO UTC, o null. / End as ISO UTC, or null. */
741
991
  get end() {
742
992
  const end = this._event?.endTime;
743
- return end == null ? null : Number(end.toString()) * 1000;
993
+ return end == null ? null : new Date(to_number(end) * 1000).toISOString();
744
994
  }
745
- /** true si el evento fue cancelado. / true if the event was canceled. */
995
+ /** true si fue cancelado. / true when canceled. */
746
996
  get canceled() {
747
997
  return this._event?.isCanceled ?? false;
748
998
  }
749
- /** Link de unión (audio/video), si aplica. / Join link (audio/video), if any. */
999
+ /** Link de unión, si aplica. / Join link, if any. */
750
1000
  get link() {
751
1001
  return this._event?.joinLink ?? '';
752
1002
  }
@@ -758,205 +1008,75 @@ class Event extends Message {
758
1008
  }
759
1009
  exports.Event = Event;
760
1010
  /**
761
- * Factoría que enlaza los statics a `wa` y expone las subclases.
762
- * Factory binding statics to `wa` and exposing subclasses.
1011
+ * Factoría de Message: evalúa el tipo y retorna la instancia de la subclase correcta.
1012
+ * Acepta el documento persistido o el mensaje crudo de baileys — en ese caso el
1013
+ * documento se deriva aquí mismo (id, tipo, autor, caption, mime, fechas).
1014
+ * Message factory: evaluates the type and returns the right subclass instance. Accepts
1015
+ * the persisted document or the raw baileys message — in that case the document is
1016
+ * derived right here (id, type, author, caption, mime, dates).
1017
+ *
1018
+ * @param wa - Instancia principal / Main WhatsApp instance
1019
+ * @param raw - Documento persistido o WAMessage crudo / Persisted document or raw WAMessage
1020
+ * @returns Instancia del tipo correcto / Right-type instance
763
1021
  */
764
- function message(wa) {
765
- async function build_instance(doc) {
766
- const opts = { wa, doc };
767
- if (doc.type === 'text') {
768
- return new Text(opts);
769
- }
770
- if (doc.type === 'image') {
771
- return new Image(opts);
772
- }
773
- if (doc.type === 'video') {
774
- return new Video(opts);
775
- }
776
- if (doc.type === 'audio') {
777
- return new Audio(opts);
778
- }
779
- if (doc.type === 'location') {
780
- return new Gps(opts);
781
- }
782
- if (doc.type === 'poll') {
783
- return new Poll(opts);
784
- }
785
- if (doc.type === 'document') {
786
- return new Document(opts);
787
- }
788
- if (doc.type === 'vcard') {
789
- return new VCard(opts);
790
- }
791
- if (doc.type === 'event') {
792
- return new Event(opts);
793
- }
794
- return new Message(opts);
795
- }
796
- async function send(cid, content, binary, reply_to, doc_overrides) {
797
- let result = null;
798
- const jid = await wa._resolve_jid(cid);
799
- if (jid && wa._socket) {
800
- let quoted;
801
- if (reply_to) {
802
- const ref_doc = (0, store_1.deserialize)(await wa.engine.get(`/chat/${jid}/message/${reply_to}`));
803
- if (ref_doc) {
804
- quoted = ref_doc.raw;
805
- }
806
- }
807
- const raw = await wa._socket.sendMessage(jid, {
808
- ...content,
809
- ...(quoted ? { quoted } : {}),
810
- });
811
- const sent_id = raw?.key?.id;
812
- if (raw && sent_id) {
813
- const doc = build_message_doc(raw, wa._socket?.user?.id);
814
- if (doc_overrides) {
815
- Object.assign(doc, doc_overrides);
816
- }
817
- await wa.engine.set(`/chat/${jid}/message/${sent_id}`, (0, store_1.serialize)(doc));
818
- if (binary) {
819
- await wa.engine.set(`/chat/${jid}/message/${sent_id}/content`, (0, store_1.serialize)({ data: binary.toString('base64') }));
820
- }
821
- result = await build_instance(doc);
822
- }
823
- }
824
- return result;
1022
+ function message(wa, raw) {
1023
+ let doc;
1024
+ if ('key' in raw) {
1025
+ const key = raw.key ?? {};
1026
+ const unwrapped = unwrap(raw.message ?? {});
1027
+ const content_type = (0, baileys_1.getContentType)(unwrapped);
1028
+ const msg_type = MESSAGE_TYPE_MAP[content_type] ?? 'text';
1029
+ const msg_content = unwrapped[content_type];
1030
+ const context_info = msg_content?.contextInfo;
1031
+ const ephemeral_duration = raw.ephemeralDuration ?? context_info?.expiration;
1032
+ const self_id = (0, internal_1.internals)(wa).socket?.user?.id;
1033
+ doc = {
1034
+ id: key.id ?? '',
1035
+ cid: key.remoteJidAlt ?? key.remoteJid ?? '',
1036
+ mid: context_info?.stanzaId ?? null,
1037
+ me: key.fromMe ?? false,
1038
+ type: msg_type,
1039
+ author: key.fromMe && self_id
1040
+ ? (0, baileys_1.jidNormalizedUser)(self_id)
1041
+ : key.participant || key.remoteJidAlt || key.remoteJid || '',
1042
+ status: raw.status ?? 1,
1043
+ starred: raw.starred ?? false,
1044
+ forwarded: context_info?.isForwarded ?? false,
1045
+ created_at: (Number(raw.messageTimestamp) || Math.floor(Date.now() / 1000)) * 1000,
1046
+ deleted_at: raw.ephemeralStartTimestamp != null && ephemeral_duration != null
1047
+ ? (Number(raw.ephemeralStartTimestamp) + ephemeral_duration) * 1000
1048
+ : null,
1049
+ mime: typeof msg_content === 'object' && msg_type !== 'text'
1050
+ ? (msg_content?.mimetype ?? 'application/octet-stream')
1051
+ : 'text/plain',
1052
+ caption: typeof msg_content === 'string'
1053
+ ? msg_content
1054
+ : msg_type === 'event'
1055
+ ? (msg_content?.description ?? '')
1056
+ : (msg_content?.caption ??
1057
+ msg_content?.text ??
1058
+ msg_content?.name ??
1059
+ msg_content?.displayName ??
1060
+ ''),
1061
+ edited: false,
1062
+ raw,
1063
+ };
825
1064
  }
826
- const api = {
827
- // Clases expuestas para instanceof
828
- Text,
829
- Image,
830
- Video,
831
- Audio,
832
- Gps,
833
- Poll,
834
- Document,
835
- VCard,
836
- Event,
837
- // Helpers internos (usados por orquestador WhatsApp)
838
- build_message_doc,
839
- build_instance,
840
- /** Obtiene un mensaje por CID/MID. */
841
- async get(cid, mid) {
842
- const jid = await wa._resolve_jid(cid);
843
- if (!jid) {
844
- return null;
845
- }
846
- const doc = (0, store_1.deserialize)(await wa.engine.get(`/chat/${jid}/message/${mid}`));
847
- return doc ? build_instance(doc) : null;
848
- },
849
- /** Pagina mensajes de un chat. */
850
- async list(cid, offset = 0, limit = 50) {
851
- const jid = await wa._resolve_jid(cid);
852
- const result = [];
853
- if (jid) {
854
- for (const raw of await wa.engine.list(`/chat/${jid}/message`, offset, limit)) {
855
- const doc = (0, store_1.deserialize)(raw);
856
- if (doc) {
857
- result.push(await build_instance(doc));
858
- }
859
- }
860
- }
861
- return result;
862
- },
863
- /** Cuenta mensajes de un chat. */
864
- async count(cid) {
865
- const jid = await wa._resolve_jid(cid);
866
- return jid ? wa.engine.count(`/chat/${jid}/message`) : 0;
867
- },
868
- async text(cid, caption, opts = {}) {
869
- return send(cid, { text: caption }, undefined, opts.mid);
870
- },
871
- async image(cid, buf, opts = {}) {
872
- return send(cid, { image: buf, caption: opts.caption }, buf, opts.mid);
873
- },
874
- async video(cid, buf, opts = {}) {
875
- return send(cid, { video: buf, caption: opts.caption }, buf, opts.mid);
876
- },
877
- async audio(cid, buf, opts = {}) {
878
- return send(cid, { audio: buf, ptt: opts.ptt ?? true }, buf, opts.mid);
879
- },
880
- async location(cid, loc, opts = {}) {
881
- return send(cid, { location: { degreesLatitude: loc.lat, degreesLongitude: loc.lng } }, undefined, opts.mid);
882
- },
883
- async poll(cid, p, opts = {}) {
884
- const multiple = opts.multiple ?? false;
885
- return send(cid, {
886
- poll: {
887
- name: p.content,
888
- values: p.options.map((o) => o.content),
889
- selectableCount: multiple ? 0 : 1,
890
- },
891
- }, undefined, opts.mid, { multiple });
892
- },
893
- async document(cid, buf, opts) {
894
- return send(cid, {
895
- document: buf,
896
- fileName: opts.file_name,
897
- mimetype: opts.mimetype ?? 'application/octet-stream',
898
- caption: opts.caption,
899
- }, buf, opts.mid);
900
- },
901
- async vcard(cid, contacts, opts = {}) {
902
- const built = contacts.map((c) => ({
903
- displayName: c.name,
904
- vcard: build_vcard(c.name, c.phone),
905
- }));
906
- const binary = Buffer.from(built.map((c) => c.vcard).join('\n'), 'utf-8');
907
- return send(cid, { contacts: { contacts: built } }, binary, opts.mid);
908
- },
909
- async event(cid, data, opts = {}) {
910
- const binary = Buffer.from(JSON.stringify({
911
- name: data.name,
912
- caption: data.caption,
913
- start: data.start.getTime(),
914
- end: data.end?.getTime() ?? null,
915
- }), 'utf-8');
916
- return send(cid, {
917
- event: {
918
- name: data.name,
919
- description: data.caption,
920
- startDate: data.start,
921
- endDate: data.end,
922
- location: data.place
923
- ? { degreesLatitude: data.place.lat, degreesLongitude: data.place.lng }
924
- : undefined,
925
- },
926
- }, binary, opts.mid);
927
- },
928
- async edit(cid, mid, text) {
929
- const m = await api.get(cid, mid);
930
- return m ? m.edit(text) : false;
931
- },
932
- async delete(cid, mid, all = true) {
933
- const m = await api.get(cid, mid);
934
- return m ? m.delete(all) : false;
935
- },
936
- async react(cid, mid, emoji) {
937
- const m = await api.get(cid, mid);
938
- return m ? m.react(emoji) : false;
939
- },
940
- async forward(cid, mid, target) {
941
- const m = await api.get(cid, mid);
942
- return m ? m.forward(target) : false;
943
- },
944
- async seen(cid, mid) {
945
- const m = await api.get(cid, mid);
946
- return m ? m.seen() : false;
947
- },
948
- async star(cid, mid, value) {
949
- const m = await api.get(cid, mid);
950
- return m ? m.star(value) : false;
951
- },
952
- watch(cid, mid, handler) {
953
- return wa.on('message:updated', (updated) => {
954
- if (updated.cid === cid && updated.id === mid) {
955
- handler(updated);
956
- }
957
- });
958
- },
1065
+ else {
1066
+ doc = raw;
1067
+ }
1068
+ const types = {
1069
+ text: Text,
1070
+ image: Image,
1071
+ video: Video,
1072
+ audio: Audio,
1073
+ sticker: Sticker,
1074
+ document: Document,
1075
+ location: Location,
1076
+ poll: Poll,
1077
+ vcard: VCard,
1078
+ event: Event,
959
1079
  };
960
- return api;
1080
+ return new (types[doc.type] ?? Message)(wa, doc);
961
1081
  }
962
1082
  //# sourceMappingURL=index.js.map