@arcaelas/whatsapp 4.5.0 → 6.0.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 (106) hide show
  1. package/README.md +282 -239
  2. package/build/cjs/decorators.js +0 -1
  3. package/build/cjs/index.d.ts +6 -4
  4. package/build/cjs/index.js +22 -3
  5. package/build/cjs/lib/bot/decorator.d.ts +2 -0
  6. package/build/cjs/lib/bot/decorator.js +6 -1
  7. package/build/cjs/lib/bot/decorators.d.ts +2 -2
  8. package/build/cjs/lib/bot/decorators.js +4 -4
  9. package/build/cjs/lib/bot/index.js +0 -1
  10. package/build/cjs/lib/chat/index.d.ts +381 -204
  11. package/build/cjs/lib/chat/index.js +243 -212
  12. package/build/cjs/lib/contact/index.d.ts +162 -179
  13. package/build/cjs/lib/contact/index.js +96 -191
  14. package/build/cjs/lib/internal.d.ts +40 -0
  15. package/build/cjs/lib/internal.js +38 -0
  16. package/build/cjs/lib/message/index.d.ts +468 -289
  17. package/build/cjs/lib/message/index.js +871 -743
  18. package/build/cjs/lib/status/index.d.ts +60 -70
  19. package/build/cjs/lib/status/index.js +106 -112
  20. package/build/cjs/lib/store/engine/index.d.ts +35 -7
  21. package/build/cjs/lib/store/engine/index.js +6 -4
  22. package/build/cjs/lib/store/engine/lib/file_system/index.d.ts +48 -8
  23. package/build/cjs/lib/store/engine/lib/file_system/index.js +117 -66
  24. package/build/cjs/lib/store/engine/lib/index.d.ts +112 -0
  25. package/build/cjs/lib/store/engine/lib/index.js +212 -0
  26. package/build/cjs/lib/store/engine/lib/redis/index.d.ts +44 -15
  27. package/build/cjs/lib/store/engine/lib/redis/index.js +75 -43
  28. package/build/cjs/lib/store/engine/lib/s3/index.d.ts +44 -1
  29. package/build/cjs/lib/store/engine/lib/s3/index.js +112 -65
  30. package/build/cjs/lib/store/engine/lib/sqlite/index.d.ts +110 -0
  31. package/build/cjs/lib/store/engine/lib/sqlite/index.js +132 -0
  32. package/build/cjs/lib/store/index.d.ts +7 -3
  33. package/build/cjs/lib/store/index.js +14 -5
  34. package/build/cjs/lib/whatsapp/index.d.ts +106 -68
  35. package/build/cjs/lib/whatsapp/index.js +393 -167
  36. package/build/esm/decorators.js +0 -1
  37. package/build/esm/index.d.ts +6 -4
  38. package/build/esm/index.js +5 -3
  39. package/build/esm/lib/bot/decorator.d.ts +2 -0
  40. package/build/esm/lib/bot/decorator.js +6 -1
  41. package/build/esm/lib/bot/decorators.d.ts +2 -2
  42. package/build/esm/lib/bot/decorators.js +4 -4
  43. package/build/esm/lib/bot/index.js +0 -1
  44. package/build/esm/lib/chat/index.d.ts +381 -204
  45. package/build/esm/lib/chat/index.js +243 -212
  46. package/build/esm/lib/contact/index.d.ts +162 -179
  47. package/build/esm/lib/contact/index.js +96 -190
  48. package/build/esm/lib/internal.d.ts +40 -0
  49. package/build/esm/lib/internal.js +34 -0
  50. package/build/esm/lib/message/index.d.ts +468 -289
  51. package/build/esm/lib/message/index.js +866 -738
  52. package/build/esm/lib/status/index.d.ts +60 -70
  53. package/build/esm/lib/status/index.js +105 -111
  54. package/build/esm/lib/store/engine/index.d.ts +35 -7
  55. package/build/esm/lib/store/engine/index.js +4 -3
  56. package/build/esm/lib/store/engine/lib/file_system/index.d.ts +48 -8
  57. package/build/esm/lib/store/engine/lib/file_system/index.js +117 -66
  58. package/build/esm/lib/store/engine/lib/index.d.ts +112 -0
  59. package/build/esm/lib/store/engine/lib/index.js +205 -0
  60. package/build/esm/lib/store/engine/lib/redis/index.d.ts +44 -15
  61. package/build/esm/lib/store/engine/lib/redis/index.js +73 -41
  62. package/build/esm/lib/store/engine/lib/s3/index.d.ts +44 -1
  63. package/build/esm/lib/store/engine/lib/s3/index.js +111 -64
  64. package/build/esm/lib/store/engine/lib/sqlite/index.d.ts +110 -0
  65. package/build/esm/lib/store/engine/lib/sqlite/index.js +128 -0
  66. package/build/esm/lib/store/index.d.ts +7 -3
  67. package/build/esm/lib/store/index.js +13 -5
  68. package/build/esm/lib/whatsapp/index.d.ts +106 -68
  69. package/build/esm/lib/whatsapp/index.js +395 -169
  70. package/package.json +25 -6
  71. package/build/cjs/decorators.js.map +0 -1
  72. package/build/cjs/index.js.map +0 -1
  73. package/build/cjs/lib/bot/decorator.js.map +0 -1
  74. package/build/cjs/lib/bot/decorators.js.map +0 -1
  75. package/build/cjs/lib/bot/index.js.map +0 -1
  76. package/build/cjs/lib/chat/index.js.map +0 -1
  77. package/build/cjs/lib/contact/index.js.map +0 -1
  78. package/build/cjs/lib/message/index.js.map +0 -1
  79. package/build/cjs/lib/status/index.js.map +0 -1
  80. package/build/cjs/lib/store/engine/index.js.map +0 -1
  81. package/build/cjs/lib/store/engine/lib/file_system/index.js.map +0 -1
  82. package/build/cjs/lib/store/engine/lib/redis/index.js.map +0 -1
  83. package/build/cjs/lib/store/engine/lib/s3/index.js.map +0 -1
  84. package/build/cjs/lib/store/index.js.map +0 -1
  85. package/build/cjs/lib/whatsapp/index.js.map +0 -1
  86. package/build/cjs/test.d.ts +0 -1
  87. package/build/cjs/test.js +0 -71
  88. package/build/cjs/test.js.map +0 -1
  89. package/build/esm/decorators.js.map +0 -1
  90. package/build/esm/index.js.map +0 -1
  91. package/build/esm/lib/bot/decorator.js.map +0 -1
  92. package/build/esm/lib/bot/decorators.js.map +0 -1
  93. package/build/esm/lib/bot/index.js.map +0 -1
  94. package/build/esm/lib/chat/index.js.map +0 -1
  95. package/build/esm/lib/contact/index.js.map +0 -1
  96. package/build/esm/lib/message/index.js.map +0 -1
  97. package/build/esm/lib/status/index.js.map +0 -1
  98. package/build/esm/lib/store/engine/index.js.map +0 -1
  99. package/build/esm/lib/store/engine/lib/file_system/index.js.map +0 -1
  100. package/build/esm/lib/store/engine/lib/redis/index.js.map +0 -1
  101. package/build/esm/lib/store/engine/lib/s3/index.js.map +0 -1
  102. package/build/esm/lib/store/index.js.map +0 -1
  103. package/build/esm/lib/whatsapp/index.js.map +0 -1
  104. package/build/esm/test.d.ts +0 -1
  105. package/build/esm/test.js +0 -66
  106. package/build/esm/test.js.map +0 -1
@@ -3,62 +3,55 @@
3
3
  * @description Entidad Chat — conversaciones individuales y grupales.
4
4
  * Chat entity — individual and group conversations.
5
5
  */
6
+ import { internals } from '../../lib/internal.js';
7
+ import { Message } from '../../lib/message/index.js';
6
8
  import { deserialize, serialize } from '../../lib/store/index.js';
7
9
  /**
8
- * Duración usada cuando `chat.mute(true)` silencia "siempre".
9
- * Duration used when `chat.mute(true)` means "mute forever".
10
- */
11
- const MUTE_FOREVER_MS = 365 * 100 * 24 * 3_600 * 1_000;
12
- /**
13
- * Clase base del chat (forma pública, solo lectura).
14
- * Base Chat class (public shape, read-only).
10
+ * Clase base del chat: recibe el raw y deriva todo con getters.
11
+ * Base Chat class: receives the raw and derives everything via getters.
15
12
  */
16
13
  export class Chat {
17
- constructor(raw) {
18
- this._raw = raw;
14
+ /**
15
+ * @internal Documento crudo del chat. `id` es el identificador del engine (JID, LID o
16
+ * `@g.us`); `pinned` y `mute_end_time` son epoch ms.
17
+ * Raw chat document. `id` is the engine identifier (JID, LID or `@g.us`); `pinned` and
18
+ * `mute_end_time` are epoch ms.
19
+ */
20
+ constructor(_raw) {
21
+ this._raw = _raw;
19
22
  }
20
- /** JID del chat. / Chat JID. */
23
+ /** Teléfono del contacto, o el identificador crudo en grupos y LIDs. / Contact phone, or the raw identifier for groups and LIDs. */
21
24
  get id() {
22
- return this._raw.id;
25
+ return this._raw.id.endsWith('@s.whatsapp.net') ? this._raw.id.split('@')[0].split(':')[0] : this._raw.id;
23
26
  }
24
- /** CID (alias). / CID (alias). */
25
- get cid() {
26
- return this._raw.id;
27
+ /** Nombre del grupo o del contacto. / Group or contact name. */
28
+ get name() {
29
+ return this._raw.name ?? this.id;
27
30
  }
28
- /** Tipo: contact o group. / Type: contact or group. */
31
+ /** Tipo de conversación. / Conversation type. */
29
32
  get type() {
30
33
  return this._raw.id.endsWith('@g.us') ? 'group' : 'contact';
31
34
  }
32
- /** Nombre del chat. / Chat name. */
33
- get name() {
34
- return this._raw.name ?? this._raw.display_name ?? this._raw.id.split('@')[0];
35
- }
36
- /** Descripción del grupo. / Group description. */
37
- get content() {
38
- return this._raw.description ?? '';
35
+ /** true si el chat está archivado. / true when the chat is archived. */
36
+ get archived() {
37
+ return this._raw.archived ?? false;
39
38
  }
40
- /** Si está fijado. / Whether it's pinned. */
39
+ /** true si el chat está fijado. / true when the chat is pinned. */
41
40
  get pinned() {
42
41
  return this._raw.pinned != null;
43
42
  }
44
- /** Si está archivado. / Whether it's archived. */
45
- get archived() {
46
- return this._raw.archived ?? false;
43
+ /** Mensajes sin leer del chat. / Chat's unread messages. */
44
+ get count() {
45
+ return this._raw.unread_count ?? 0;
47
46
  }
48
- /** true si el chat está silenciado y el silencio aún no expira. / true if chat is muted and the mute has not expired. */
47
+ /** Fecha ISO UTC hasta la que el chat está silenciado, o null. / ISO UTC date until the chat stays muted, or null. */
49
48
  get muted() {
50
49
  const end = this._raw.mute_end_time;
51
- return end != null && end > Date.now();
52
- }
53
- /** Si está leído. / Whether it's read. */
54
- get read() {
55
- return !this._raw.unread_count && !this._raw.marked_as_unread;
56
- }
57
- /** Si es solo lectura. / Whether it's read-only. */
58
- get readonly() {
59
- return this._raw.read_only ?? false;
50
+ return end != null && end > Date.now() ? new Date(end).toISOString() : null;
60
51
  }
61
52
  }
53
+ /** Máximo de chats fijados que acepta WhatsApp; el cuarto se descarta en silencio. / Max pinned chats WhatsApp accepts; the fourth is silently dropped. */
54
+ const MAX_PINNED = 3;
62
55
  /**
63
56
  * Factoría de Chat ligada al contexto WhatsApp.
64
57
  * Context-bound Chat factory.
@@ -67,243 +60,281 @@ export class Chat {
67
60
  */
68
61
  export function chat(wa) {
69
62
  /**
70
- * Obtiene la key del último mensaje para operaciones de chatModify que la requieren.
71
- * Fetches the last message key required by chatModify operations.
63
+ * Último mensaje del chat en el formato que exige `chatModify`.
64
+ * The chat's last message in the shape `chatModify` requires.
72
65
  */
73
66
  async function last_messages(cid) {
74
67
  const [raw] = await wa.engine.list(`/chat/${cid}/message`, 0, 1);
75
68
  const parsed = deserialize(raw ?? null);
76
69
  return parsed
77
- ? [
78
- {
79
- key: { remoteJid: cid, id: parsed.id, fromMe: parsed.me },
80
- messageTimestamp: Math.floor(parsed.created_at / 1000),
81
- },
82
- ]
70
+ ? [{ key: { remoteJid: cid, id: parsed.id, fromMe: parsed.me }, messageTimestamp: Math.floor(parsed.created_at / 1000) }]
83
71
  : [];
84
72
  }
85
- return class _Chat extends Chat {
86
- constructor() {
87
- super(...arguments);
88
- /** @internal Cache TTL (15s) de la promesa de participants del grupo. Evita round-trips a `groupMetadata` y deduplica llamadas concurrentes. */
89
- this._members_cache = null;
90
- }
91
- /**
92
- * Obtiene un chat por CID. Si no está persistido, lo crea a partir del contacto.
93
- * Retrieves a chat by CID. If not persisted, creates it from the contact.
94
- */
95
- static async get(cid) {
96
- let result = null;
97
- const jid = await wa._resolve_jid(cid);
98
- if (jid) {
99
- const cached = deserialize(await wa.engine.get(`/chat/${jid}`));
100
- if (cached) {
101
- result = new _Chat(cached);
102
- }
103
- else {
104
- const c = await wa.Contact.get(jid);
105
- if (c) {
106
- const raw = { id: jid, name: c.name };
107
- await wa.engine.set(`/chat/${jid}`, serialize(raw));
108
- result = new _Chat(raw);
109
- }
110
- }
73
+ /**
74
+ * Cuenta los chats fijados distintos del indicado, cortando al llegar al máximo.
75
+ * Counts pinned chats other than the given one, stopping once the max is reached.
76
+ */
77
+ async function count_pinned(exclude) {
78
+ let total = 0;
79
+ for (let offset = 0; total < MAX_PINNED; offset += 200) {
80
+ const page = await wa.engine.list('/chat', offset, 200);
81
+ if (page.length === 0) {
82
+ break;
111
83
  }
112
- return result;
113
- }
114
- /** Pagina los chats persistidos por mtime DESC. / Paginates persisted chats by mtime DESC. */
115
- static async list(offset = 0, limit = 50) {
116
- const chats = [];
117
- for (const raw of await wa.engine.list('/chat', offset, limit)) {
84
+ for (const raw of page) {
118
85
  const parsed = deserialize(raw);
119
- if (parsed) {
120
- chats.push(new _Chat(parsed));
86
+ if (parsed && parsed.id !== exclude && parsed.pinned != null) {
87
+ total++;
121
88
  }
122
89
  }
123
- return chats;
124
90
  }
125
- /** Fija/desfija un chat por CID. / Pins or unpins a chat by CID. */
126
- static async pin(cid, value) {
127
- const c = await _Chat.get(cid);
128
- return c ? c.pin(value) : false;
129
- }
130
- /** Archiva/desarchiva un chat por CID. / Archives or unarchives a chat by CID. */
131
- static async archive(cid, value) {
132
- const c = await _Chat.get(cid);
133
- return c ? c.archive(value) : false;
91
+ return total;
92
+ }
93
+ /**
94
+ * Participantes del grupo memoizados 15s, para no repetir `groupMetadata` en cada página.
95
+ * Group participants memoized for 15s, avoiding a `groupMetadata` round-trip per page.
96
+ */
97
+ const groups_cache = new Map();
98
+ function group_meta(jid) {
99
+ if (!groups_cache.has(jid)) {
100
+ const socket = internals(wa).socket;
101
+ groups_cache.set(jid, socket ? socket.groupMetadata(jid).catch(() => ({ participants: [] })) : Promise.resolve({ participants: [] }));
102
+ setTimeout(() => groups_cache.delete(jid), 15_000);
134
103
  }
135
- /** Silencia/des-silencia un chat por CID. / Mutes or unmutes a chat by CID. */
136
- static async mute(cid, value) {
137
- const c = await _Chat.get(cid);
138
- return c ? c.mute(value) : false;
104
+ return groups_cache.get(jid);
105
+ }
106
+ /**
107
+ * Contacto desde el engine, o ficha mínima local cuando no está persistido (sin red).
108
+ * Contact from the engine, or a minimal local card when not persisted (no network).
109
+ */
110
+ async function load_contact(id) {
111
+ const cached = deserialize(await wa.engine.get(`/contact/${id}`));
112
+ return new wa.Contact(cached ?? { id });
113
+ }
114
+ return class _Chat extends Chat {
115
+ /**
116
+ * Participantes del chat: los integrantes en grupos, el contacto y yo en 1:1.
117
+ * Chat participants: members for groups, the contact and myself for 1:1.
118
+ *
119
+ * @param offset - Desplazamiento / Offset
120
+ * @param limit - Tamaño de página / Page size
121
+ * @returns Página de contactos / Contact page
122
+ */
123
+ async members(offset = 0, limit = 50) {
124
+ const ids = this.type === 'group'
125
+ ? (await group_meta(this._raw.id)).participants.map((participant) => participant.id)
126
+ : [this._raw.id, internals(wa).socket?.user?.id].filter((id) => Boolean(id));
127
+ return Promise.all(ids.slice(offset, offset + limit).map(load_contact));
139
128
  }
140
- /** Vacía mensajes del chat (local). / Clears the chat's messages (local only). */
141
- static async clear(cid) {
142
- const c = await _Chat.get(cid);
143
- return c ? c.clear() : false;
129
+ /**
130
+ * Descripción del chat: el asunto del grupo o, en un 1:1, la bio del contacto.
131
+ * Es asíncrono porque ninguno de los dos vive en el documento del chat.
132
+ * Chat description: the group's subject or, on a 1:1, the contact's bio. It is async
133
+ * because neither of them lives in the chat document.
134
+ *
135
+ * @returns Descripción, o cadena vacía si no hay / Description, or an empty string when absent
136
+ */
137
+ async content() {
138
+ if (this.type === 'group') {
139
+ return (await group_meta(this._raw.id)).desc ?? '';
140
+ }
141
+ return deserialize(await wa.engine.get(`/contact/${this._raw.id}`))?.status ?? '';
144
142
  }
145
- /** Elimina el chat y sus mensajes. / Deletes the chat and its messages. */
146
- static async delete(cid) {
147
- const c = await _Chat.get(cid);
148
- return c ? c.delete() : false;
143
+ /**
144
+ * Mensajes del chat paginados desde el más reciente.
145
+ * Chat messages paginated from the most recent one.
146
+ *
147
+ * @param offset - Desplazamiento / Offset
148
+ * @param limit - Tamaño de página / Page size
149
+ * @returns Página de mensajes / Message page
150
+ */
151
+ async messages(offset = 0, limit = 50) {
152
+ return Message.list(wa, this._raw.id, offset, limit);
149
153
  }
150
- /** Re-hidrata metadata del chat desde el socket. / Re-hydrates chat metadata from the socket. */
151
- async refresh() {
154
+ /**
155
+ * Activa o desactiva el indicador «escribiendo…».
156
+ * Toggles the "typing…" indicator.
157
+ *
158
+ * @param value - true activa, false vuelve a pausa / true enables, false returns to paused
159
+ * @returns true si el socket estaba disponible / true when the socket was available
160
+ */
161
+ async typing(value) {
152
162
  let ok = false;
153
- if (wa._socket) {
154
- if (this.type === 'group') {
155
- try {
156
- const meta = await wa._socket.groupMetadata(this.id);
157
- this._raw.name = meta.subject;
158
- this._raw.description = meta.desc ?? null;
159
- this._raw.participants = meta.participants.map((p) => ({
160
- id: p.id,
161
- admin: p.admin ?? null,
162
- }));
163
- this._raw.created_by = meta.owner ?? null;
164
- this._raw.created_at = meta.creation ?? null;
165
- }
166
- catch {
167
- /* group metadata may fail */
168
- }
169
- }
170
- else {
171
- const c = await wa.Contact.get(this.id);
172
- if (c) {
173
- await c.refresh();
174
- this._raw.name = c.name;
175
- }
176
- }
177
- await wa.engine.set(`/chat/${this.id}`, serialize(this._raw));
163
+ const socket = internals(wa).socket;
164
+ if (socket) {
165
+ await socket.sendPresenceUpdate(value ? 'composing' : 'paused', this._raw.id);
178
166
  ok = true;
179
167
  }
180
- return ok ? this : null;
168
+ return ok;
181
169
  }
182
- /** Fija/desfija el chat. / Pins or unpins the chat. */
183
- async pin(value) {
170
+ /**
171
+ * Activa o desactiva el indicador «grabando audio…».
172
+ * Toggles the "recording audio…" indicator.
173
+ *
174
+ * @param value - true activa, false vuelve a pausa / true enables, false returns to paused
175
+ * @returns true si el socket estaba disponible / true when the socket was available
176
+ */
177
+ async recording(value) {
184
178
  let ok = false;
185
- if (wa._socket) {
186
- await wa._socket.chatModify({ pin: value, lastMessages: await last_messages(this.id) }, this.id);
187
- this._raw.pinned = value ? Date.now() : null;
188
- await wa.engine.set(`/chat/${this.id}`, serialize(this._raw));
179
+ const socket = internals(wa).socket;
180
+ if (socket) {
181
+ await socket.sendPresenceUpdate(value ? 'recording' : 'paused', this._raw.id);
189
182
  ok = true;
190
183
  }
191
184
  return ok;
192
185
  }
193
- /** Archiva/desarchiva el chat. / Archives or unarchives the chat. */
186
+ /**
187
+ * Archiva o desarchiva el chat en la cuenta de WhatsApp.
188
+ * Archives or unarchives the chat on the WhatsApp account.
189
+ *
190
+ * @param value - true archiva, false desarchiva / true archives, false unarchives
191
+ * @returns true si la acción se envió / true when the action was sent
192
+ */
194
193
  async archive(value) {
195
194
  let ok = false;
196
- if (wa._socket) {
197
- await wa._socket.chatModify({ archive: value, lastMessages: await last_messages(this.id) }, this.id);
195
+ const socket = internals(wa).socket;
196
+ if (socket) {
197
+ await socket.chatModify({ archive: value, lastMessages: await last_messages(this._raw.id) }, this._raw.id);
198
198
  this._raw.archived = value;
199
- await wa.engine.set(`/chat/${this.id}`, serialize(this._raw));
199
+ await wa.engine.set(`/chat/${this._raw.id}`, serialize(this._raw));
200
200
  ok = true;
201
201
  }
202
202
  return ok;
203
203
  }
204
- /** Silencia/des-silencia el chat. / Mutes or unmutes the chat. */
205
- async mute(value) {
204
+ /**
205
+ * Fija o desfija el chat en la cuenta de WhatsApp. WhatsApp acepta hasta 3 chats
206
+ * fijados y descarta el cuarto sin avisar, así que el límite se verifica antes.
207
+ * Pins or unpins the chat on the WhatsApp account. WhatsApp accepts up to 3 pinned
208
+ * chats and silently drops the fourth, so the limit is checked beforehand.
209
+ *
210
+ * @param value - true fija, false desfija / true pins, false unpins
211
+ * @returns false si el socket está caído o ya hay 3 chats fijados / false when the socket is down or 3 chats are already pinned
212
+ */
213
+ async pin(value) {
206
214
  let ok = false;
207
- if (wa._socket) {
208
- const mute_end = value === true ? Date.now() + MUTE_FOREVER_MS : null;
209
- await wa._socket.chatModify({ mute: mute_end, lastMessages: await last_messages(this.id) }, this.id);
210
- this._raw.mute_end_time = mute_end;
211
- await wa.engine.set(`/chat/${this.id}`, serialize(this._raw));
212
- ok = true;
215
+ const socket = internals(wa).socket;
216
+ if (socket) {
217
+ const allowed = value ? (await count_pinned(this._raw.id)) < MAX_PINNED : true;
218
+ if (allowed) {
219
+ await socket.chatModify({ pin: value }, this._raw.id);
220
+ this._raw.pinned = value ? Date.now() : null;
221
+ await wa.engine.set(`/chat/${this._raw.id}`, serialize(this._raw));
222
+ ok = true;
223
+ }
213
224
  }
214
225
  return ok;
215
226
  }
216
- /** Toggle "Escribiendo...". / Toggles the "typing..." indicator. */
217
- async typing(on) {
227
+ /**
228
+ * Silencia el chat hasta la fecha indicada. `false` o una fecha pasada lo des-silencian.
229
+ * Mutes the chat until the given date. `false` or a past date unmutes it.
230
+ *
231
+ * @param until - Fecha límite (ISO, epoch ms o Date) o false / Deadline (ISO, epoch ms or Date) or false
232
+ * @returns true si la acción se envió / true when the action was sent
233
+ */
234
+ async mute(until) {
218
235
  let ok = false;
219
- if (wa._socket) {
220
- await wa._socket.sendPresenceUpdate(on ? 'composing' : 'paused', this.id);
236
+ const socket = internals(wa).socket;
237
+ if (socket) {
238
+ const end = until === false ? 0 : new Date(until).getTime();
239
+ const muted = end > Date.now();
240
+ await socket.chatModify({ mute: muted ? end : null }, this._raw.id);
241
+ this._raw.mute_end_time = muted ? end : null;
242
+ await wa.engine.set(`/chat/${this._raw.id}`, serialize(this._raw));
221
243
  ok = true;
222
244
  }
223
245
  return ok;
224
246
  }
225
- /** Toggle "Grabando audio...". / Toggles the "recording audio..." indicator. */
226
- async recording(on) {
247
+ /**
248
+ * Marca el chat completo como leído en la cuenta de WhatsApp.
249
+ * Marks the whole chat as read on the WhatsApp account.
250
+ *
251
+ * @returns true si la acción se envió / true when the action was sent
252
+ */
253
+ async seen() {
227
254
  let ok = false;
228
- if (wa._socket) {
229
- await wa._socket.sendPresenceUpdate(on ? 'recording' : 'paused', this.id);
255
+ const socket = internals(wa).socket;
256
+ if (socket) {
257
+ await socket.chatModify({ markRead: true, lastMessages: await last_messages(this._raw.id) }, this._raw.id);
258
+ this._raw.unread_count = 0;
259
+ await wa.engine.set(`/chat/${this._raw.id}`, serialize(this._raw));
230
260
  ok = true;
231
261
  }
232
262
  return ok;
233
263
  }
234
- /** Vacía mensajes del chat (engine local). / Clears chat messages (local engine). */
264
+ /**
265
+ * Vacía los mensajes del chat en la cuenta de WhatsApp y en el engine, conservando el chat.
266
+ * Clears the chat messages on the WhatsApp account and in the engine, keeping the chat.
267
+ *
268
+ * @returns true siempre; la limpieza local es idempotente / always true; local cleanup is idempotent
269
+ */
235
270
  async clear() {
236
- await wa.engine.unset(`/chat/${this.id}/message`);
271
+ const socket = internals(wa).socket;
272
+ if (socket) {
273
+ await socket
274
+ .chatModify({ clear: true, lastMessages: await last_messages(this._raw.id) }, this._raw.id)
275
+ .catch(() => null);
276
+ }
277
+ await wa.engine.unset(`/chat/${this._raw.id}/message`);
237
278
  return true;
238
279
  }
239
- /** Elimina el chat y sus mensajes (remoto + local). / Deletes the chat and its messages (remote + local). */
280
+ /**
281
+ * Elimina el chat y sus mensajes en la cuenta de WhatsApp y en el engine; en grupos
282
+ * abandona el grupo.
283
+ * Deletes the chat and its messages on the WhatsApp account and in the engine; for
284
+ * groups it leaves the group.
285
+ *
286
+ * @returns true siempre; la limpieza local es idempotente / always true; local cleanup is idempotent
287
+ */
240
288
  async delete() {
241
- if (wa._socket) {
289
+ const socket = internals(wa).socket;
290
+ if (socket) {
242
291
  if (this.type === 'group') {
243
- try {
244
- await wa._socket.groupLeave(this.id);
245
- }
246
- catch {
247
- /* may fail */
248
- }
292
+ await socket.groupLeave(this._raw.id).catch(() => null);
249
293
  }
250
294
  else {
251
- try {
252
- await wa._socket.chatModify({ delete: true, lastMessages: [] }, this.id);
253
- }
254
- catch {
255
- /* may fail */
256
- }
295
+ await socket
296
+ .chatModify({ delete: true, lastMessages: await last_messages(this._raw.id) }, this._raw.id)
297
+ .catch(() => null);
257
298
  }
258
299
  }
259
- await this.clear();
260
- await wa.engine.unset(`/chat/${this.id}`);
300
+ await wa.engine.unset(`/chat/${this._raw.id}`);
261
301
  return true;
262
302
  }
263
303
  /**
264
- * Participantes del chat paginados (incluyéndome en grupos). Para grupos,
265
- * el `groupMetadata` se memoiza en la instancia con TTL de 15s para evitar
266
- * round-trips repetidos al socket.
267
- * Chat participants paginated (self included in groups). For groups,
268
- * `groupMetadata` is memoized on the instance with a 15s TTL to avoid
269
- * repeated socket round-trips.
304
+ * Carga un chat por teléfono, JID, LID o id de grupo: el persistido en el engine o,
305
+ * si todavía no existe, una instancia mínima lista para usar (no se persiste).
306
+ * Loads a chat by phone, JID, LID or group id: the engine-persisted one or, when it
307
+ * does not exist yet, a minimal ready-to-use instance (not persisted).
308
+ *
309
+ * @param cid - Teléfono, JID, LID o id de grupo / Phone, JID, LID or group id
310
+ * @returns Chat o null si el identificador es irresoluble / Chat or null when the identifier cannot be resolved
270
311
  */
271
- async members(offset = 0, limit = 50) {
272
- const result = [];
273
- if (this.type !== 'group') {
274
- if (offset === 0 && limit > 0) {
275
- const c = await wa.Contact.get(this.id);
276
- if (c) {
277
- result.push(c);
278
- }
279
- }
280
- }
281
- else if (wa._socket) {
282
- try {
283
- const socket = wa._socket;
284
- const participants = await (this._members_cache ??= (async () => {
285
- const meta = await socket.groupMetadata(this.id);
286
- setTimeout(() => { this._members_cache = null; }, 15_000);
287
- return meta.participants;
288
- })());
289
- const slice = participants.slice(offset, offset + limit);
290
- for (const p of slice) {
291
- const existing = await wa.Contact.get(p.id);
292
- if (existing) {
293
- result.push(existing);
294
- }
295
- }
296
- }
297
- catch {
298
- /* may fail */
299
- }
312
+ static async get(cid) {
313
+ const digits = String(cid).replace(/\D+/g, '');
314
+ const jid = String(cid).includes('@')
315
+ ? await internals(wa).resolve_jid(String(cid))
316
+ : digits
317
+ ? `${digits}@s.whatsapp.net`
318
+ : null;
319
+ if (jid) {
320
+ const cached = deserialize(await wa.engine.get(`/chat/${jid}`));
321
+ return new _Chat(cached ?? { id: jid });
300
322
  }
301
- return result;
323
+ return null;
302
324
  }
303
- /** Mensajes del chat paginados por mtime DESC. / Chat messages paginated by mtime DESC. */
304
- async messages(offset = 0, limit = 50) {
305
- return wa.Message.list(this.id, offset, limit);
325
+ /**
326
+ * Pagina los chats persistidos, del más reciente al más antiguo.
327
+ * Paginates persisted chats, from the most recent to the oldest.
328
+ *
329
+ * @param offset - Desplazamiento / Offset
330
+ * @param limit - Tamaño de página / Page size
331
+ * @returns Página de chats / Chat page
332
+ */
333
+ static async list(offset = 0, limit = 50) {
334
+ return (await wa.engine.list('/chat', offset, limit))
335
+ .map((raw) => deserialize(raw))
336
+ .filter((parsed) => parsed !== null)
337
+ .map((parsed) => new _Chat(parsed));
306
338
  }
307
339
  };
308
340
  }
309
- //# sourceMappingURL=index.js.map