@arcaelas/whatsapp 6.1.3 → 7.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 (42) hide show
  1. package/README.md +19 -15
  2. package/build/cjs/index.d.ts +9 -5
  3. package/build/cjs/index.js +8 -7
  4. package/build/cjs/lib/bot/decorator.d.ts +2 -9
  5. package/build/cjs/lib/bot/decorator.js +0 -1
  6. package/build/cjs/lib/bot/decorators.d.ts +48 -4
  7. package/build/cjs/lib/bot/decorators.js +2 -2
  8. package/build/cjs/lib/chat/index.d.ts +144 -152
  9. package/build/cjs/lib/chat/index.js +138 -209
  10. package/build/cjs/lib/contact/index.d.ts +114 -80
  11. package/build/cjs/lib/contact/index.js +187 -94
  12. package/build/cjs/lib/message/index.d.ts +400 -321
  13. package/build/cjs/lib/message/index.js +425 -913
  14. package/build/cjs/lib/status/index.d.ts +22 -33
  15. package/build/cjs/lib/status/index.js +52 -93
  16. package/build/cjs/lib/store/index.d.ts +16 -0
  17. package/build/cjs/lib/store/index.js +29 -3
  18. package/build/cjs/lib/whatsapp/index.d.ts +44 -212
  19. package/build/cjs/lib/whatsapp/index.js +473 -1067
  20. package/build/esm/index.d.ts +9 -5
  21. package/build/esm/index.js +6 -4
  22. package/build/esm/lib/bot/decorator.d.ts +2 -9
  23. package/build/esm/lib/bot/decorator.js +1 -1
  24. package/build/esm/lib/bot/decorators.d.ts +48 -4
  25. package/build/esm/lib/bot/decorators.js +2 -2
  26. package/build/esm/lib/chat/index.d.ts +144 -152
  27. package/build/esm/lib/chat/index.js +139 -209
  28. package/build/esm/lib/contact/index.d.ts +114 -80
  29. package/build/esm/lib/contact/index.js +186 -94
  30. package/build/esm/lib/message/index.d.ts +400 -321
  31. package/build/esm/lib/message/index.js +422 -913
  32. package/build/esm/lib/status/index.d.ts +22 -33
  33. package/build/esm/lib/status/index.js +49 -93
  34. package/build/esm/lib/store/index.d.ts +16 -0
  35. package/build/esm/lib/store/index.js +25 -0
  36. package/build/esm/lib/whatsapp/index.d.ts +44 -212
  37. package/build/esm/lib/whatsapp/index.js +476 -1069
  38. package/package.json +1 -1
  39. package/build/cjs/lib/internal.d.ts +0 -40
  40. package/build/cjs/lib/internal.js +0 -38
  41. package/build/esm/lib/internal.d.ts +0 -40
  42. package/build/esm/lib/internal.js +0 -34
@@ -1,26 +1,30 @@
1
1
  /**
2
2
  * @file status/index.ts
3
- * @description Entidad Feed — publicación del status broadcast (`status@broadcast`) como
4
- * subclase de Message: hereda author/chat/content/stream y anula lo que un status no soporta.
5
- * Feed entity — status broadcast post as a Message subclass: inherits
6
- * author/chat/content/stream and voids what a status does not support.
3
+ * @description Entidad Feed — publicación del status broadcast como subclase de Message:
4
+ * hereda author/stream y anula lo que un status no soporta.
5
+ * Feed entity — status broadcast post as a Message subclass: inherits author/stream and
6
+ * voids what a status does not support.
7
7
  */
8
- import type { WAMessage } from 'baileys';
9
- import { Message } from '../../lib/message';
10
- import type { WhatsApp } from '../../lib/whatsapp';
8
+ import type { WAMessage, WASocket } from 'baileys';
9
+ import Message from '../../lib/message';
10
+ import { type Engine } from '../../lib/store';
11
+ import type WhatsApp from '../../lib/whatsapp';
11
12
  /** Vida útil del status: 24 horas en ms. / Status lifetime: 24h in ms. */
12
13
  export declare const TTL_MS: number;
13
14
  /**
14
- * Publicación del status broadcast. El documento del status se adapta al shape de
15
- * Message en el constructor (`cid` fijo a `status@broadcast`, `author` desde
16
- * `author_jid`, `deleted_at` desde `expires_at`), así los getters heredados aplican
17
- * tal cual.
18
- * Status broadcast post. The status document is adapted to the Message shape in the
19
- * constructor (`cid` pinned to `status@broadcast`, `author` from `author_jid`,
20
- * `deleted_at` from `expires_at`), so inherited getters apply as-is.
15
+ * Publicación del status broadcast. El documento se adapta al shape de Message en el
16
+ * constructor (`cid` fijo a `status@broadcast`, `author` desde `author_jid`, `deleted_at`
17
+ * desde `expires_at`), así los getters heredados aplican tal cual.
18
+ * Status broadcast post. The document is adapted to the Message shape in the constructor
19
+ * (`cid` pinned to `status@broadcast`, `author` from `author_jid`, `deleted_at` from
20
+ * `expires_at`), so inherited getters apply as-is.
21
21
  */
22
22
  export declare class Feed extends Message {
23
- constructor(wa: WhatsApp, doc: {
23
+ constructor(init: {
24
+ wa: WhatsApp;
25
+ engine: Engine;
26
+ socket: WASocket;
27
+ }, doc: {
24
28
  id: string;
25
29
  author_jid: string;
26
30
  type: 'text' | 'image' | 'video' | 'audio';
@@ -33,43 +37,28 @@ export declare class Feed extends Message {
33
37
  });
34
38
  /** true si ya enviamos read receipt sobre este status. / true once a read receipt was sent. */
35
39
  get viewed(): boolean;
40
+ /** Binario del status: vive bajo `/status`, no bajo `/chat`. / Status binary: it lives under `/status`, not `/chat`. */
41
+ content(): Promise<Buffer>;
36
42
  /**
37
43
  * Marca el status como visto enviando read receipt y persiste `viewed`.
38
- * Marks the status as seen sending a read receipt and persists `viewed`.
39
- *
40
- * @returns true si se envió / true when sent
44
+ * Marks the status as seen sending a read receipt and persisting `viewed`.
41
45
  */
42
46
  view(): Promise<boolean>;
43
47
  /** Un status marca visto con `view()`. / A status marks seen via `view()`. */
44
48
  seen(): Promise<boolean>;
45
- /** No soportado en un status. / Unsupported on a status. */
46
49
  message(): Promise<never>;
47
- /** No soportado en un status. / Unsupported on a status. */
48
50
  react(): Promise<never>;
49
- /** No soportado en un status. / Unsupported on a status. */
50
51
  star(): Promise<never>;
51
- /** No soportado en un status. / Unsupported on a status. */
52
52
  edit(): Promise<never>;
53
- /** No soportado en un status. / Unsupported on a status. */
54
53
  forward(): Promise<never>;
55
- /** No soportado en un status. / Unsupported on a status. */
56
54
  delete(): Promise<never>;
57
- /** No soportado en un status. / Unsupported on a status. */
58
55
  text(): Promise<never>;
59
- /** No soportado en un status. / Unsupported on a status. */
60
56
  image(): Promise<never>;
61
- /** No soportado en un status. / Unsupported on a status. */
62
57
  video(): Promise<never>;
63
- /** No soportado en un status. / Unsupported on a status. */
64
58
  audio(): Promise<never>;
65
- /** No soportado en un status. / Unsupported on a status. */
66
59
  location(): Promise<never>;
67
- /** No soportado en un status. / Unsupported on a status. */
68
60
  poll(): Promise<never>;
69
- /** No soportado en un status. / Unsupported on a status. */
70
61
  document(): Promise<never>;
71
- /** No soportado en un status. / Unsupported on a status. */
72
62
  vcard(): Promise<never>;
73
- /** No soportado en un status. / Unsupported on a status. */
74
63
  event(): Promise<never>;
75
64
  }
@@ -1,30 +1,31 @@
1
1
  "use strict";
2
2
  /**
3
3
  * @file status/index.ts
4
- * @description Entidad Feed — publicación del status broadcast (`status@broadcast`) como
5
- * subclase de Message: hereda author/chat/content/stream y anula lo que un status no soporta.
6
- * Feed entity — status broadcast post as a Message subclass: inherits
7
- * author/chat/content/stream and voids what a status does not support.
4
+ * @description Entidad Feed — publicación del status broadcast como subclase de Message:
5
+ * hereda author/stream y anula lo que un status no soporta.
6
+ * Feed entity — status broadcast post as a Message subclass: inherits author/stream and
7
+ * voids what a status does not support.
8
8
  */
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
9
12
  Object.defineProperty(exports, "__esModule", { value: true });
10
13
  exports.Feed = exports.TTL_MS = void 0;
11
- const internal_1 = require("../../lib/internal");
12
- const message_1 = require("../../lib/message");
14
+ const message_1 = __importDefault(require("../../lib/message"));
13
15
  const store_1 = require("../../lib/store");
14
16
  /** Vida útil del status: 24 horas en ms. / Status lifetime: 24h in ms. */
15
- exports.TTL_MS = 24 * 60 * 60 * 1000;
17
+ exports.TTL_MS = 24 * 60 * 60 * 1_000;
16
18
  /**
17
- * Publicación del status broadcast. El documento del status se adapta al shape de
18
- * Message en el constructor (`cid` fijo a `status@broadcast`, `author` desde
19
- * `author_jid`, `deleted_at` desde `expires_at`), así los getters heredados aplican
20
- * tal cual.
21
- * Status broadcast post. The status document is adapted to the Message shape in the
22
- * constructor (`cid` pinned to `status@broadcast`, `author` from `author_jid`,
23
- * `deleted_at` from `expires_at`), so inherited getters apply as-is.
19
+ * Publicación del status broadcast. El documento se adapta al shape de Message en el
20
+ * constructor (`cid` fijo a `status@broadcast`, `author` desde `author_jid`, `deleted_at`
21
+ * desde `expires_at`), así los getters heredados aplican tal cual.
22
+ * Status broadcast post. The document is adapted to the Message shape in the constructor
23
+ * (`cid` pinned to `status@broadcast`, `author` from `author_jid`, `deleted_at` from
24
+ * `expires_at`), so inherited getters apply as-is.
24
25
  */
25
- class Feed extends message_1.Message {
26
- constructor(wa, doc) {
27
- super(wa, {
26
+ class Feed extends message_1.default {
27
+ constructor(init, doc) {
28
+ super(init, {
28
29
  ...doc,
29
30
  cid: 'status@broadcast',
30
31
  mid: null,
@@ -41,91 +42,49 @@ class Feed extends message_1.Message {
41
42
  get viewed() {
42
43
  return this._raw.viewed ?? false;
43
44
  }
45
+ /** Binario del status: vive bajo `/status`, no bajo `/chat`. / Status binary: it lives under `/status`, not `/chat`. */
46
+ async content() {
47
+ const path = `/status/${this._raw.id}/content`;
48
+ const cached = await this._init.engine.get_buffer?.(path);
49
+ if (cached?.length)
50
+ return cached;
51
+ const legacy = (0, store_1.deserialize)(await this._init.engine.get(path));
52
+ return legacy?.data ? Buffer.from(legacy.data, 'base64') : Buffer.alloc(0);
53
+ }
44
54
  /**
45
55
  * Marca el status como visto enviando read receipt y persiste `viewed`.
46
- * Marks the status as seen sending a read receipt and persists `viewed`.
47
- *
48
- * @returns true si se envió / true when sent
56
+ * Marks the status as seen sending a read receipt and persisting `viewed`.
49
57
  */
50
58
  async view() {
51
- let ok = false;
52
- const socket = (0, internal_1.internals)(this._wa).socket;
53
- if (socket) {
54
- if (!this.viewed) {
55
- await socket.readMessages([
56
- { remoteJid: 'status@broadcast', id: this._raw.id, participant: this._raw.author },
57
- ]);
58
- this._raw.viewed = true;
59
- await this._wa.engine.set(`/status/${this._raw.id}`, (0, store_1.serialize)(this._raw));
60
- }
61
- this._wa.emit('feed:updated', this, this._wa);
62
- ok = true;
59
+ if (!this.viewed) {
60
+ await this._init.socket.readMessages([
61
+ { remoteJid: 'status@broadcast', id: this._raw.id, participant: this._raw.author },
62
+ ]);
63
+ this._raw.viewed = true;
64
+ await this._init.engine.set(`/status/${this._raw.id}`, (0, store_1.serialize)(this._raw));
63
65
  }
64
- return ok;
66
+ this._init.wa.emit('feed:updated', this, this._init.wa);
67
+ return true;
65
68
  }
66
69
  /** Un status marca visto con `view()`. / A status marks seen via `view()`. */
67
70
  async seen() {
68
71
  return this.view();
69
72
  }
70
- /** No soportado en un status. / Unsupported on a status. */
71
- async message() {
72
- throw new Error('ERR_FEED_UNSUPPORTED');
73
- }
74
- /** No soportado en un status. / Unsupported on a status. */
75
- async react() {
76
- throw new Error('ERR_FEED_UNSUPPORTED');
77
- }
78
- /** No soportado en un status. / Unsupported on a status. */
79
- async star() {
80
- throw new Error('ERR_FEED_UNSUPPORTED');
81
- }
82
- /** No soportado en un status. / Unsupported on a status. */
83
- async edit() {
84
- throw new Error('ERR_FEED_UNSUPPORTED');
85
- }
86
- /** No soportado en un status. / Unsupported on a status. */
87
- async forward() {
88
- throw new Error('ERR_FEED_UNSUPPORTED');
89
- }
90
- /** No soportado en un status. / Unsupported on a status. */
91
- async delete() {
92
- throw new Error('ERR_FEED_UNSUPPORTED');
93
- }
94
- /** No soportado en un status. / Unsupported on a status. */
95
- async text() {
96
- throw new Error('ERR_FEED_UNSUPPORTED');
97
- }
98
- /** No soportado en un status. / Unsupported on a status. */
99
- async image() {
100
- throw new Error('ERR_FEED_UNSUPPORTED');
101
- }
102
- /** No soportado en un status. / Unsupported on a status. */
103
- async video() {
104
- throw new Error('ERR_FEED_UNSUPPORTED');
105
- }
106
- /** No soportado en un status. / Unsupported on a status. */
107
- async audio() {
108
- throw new Error('ERR_FEED_UNSUPPORTED');
109
- }
110
- /** No soportado en un status. / Unsupported on a status. */
111
- async location() {
112
- throw new Error('ERR_FEED_UNSUPPORTED');
113
- }
114
- /** No soportado en un status. / Unsupported on a status. */
115
- async poll() {
116
- throw new Error('ERR_FEED_UNSUPPORTED');
117
- }
118
- /** No soportado en un status. / Unsupported on a status. */
119
- async document() {
120
- throw new Error('ERR_FEED_UNSUPPORTED');
121
- }
122
- /** No soportado en un status. / Unsupported on a status. */
123
- async vcard() {
124
- throw new Error('ERR_FEED_UNSUPPORTED');
125
- }
126
- /** No soportado en un status. / Unsupported on a status. */
127
- async event() {
128
- throw new Error('ERR_FEED_UNSUPPORTED');
129
- }
73
+ /* Un status no soporta el resto de operaciones de Message. / A status supports none of the remaining Message operations. */
74
+ async message() { throw new Error('ERR_FEED_UNSUPPORTED'); }
75
+ async react() { throw new Error('ERR_FEED_UNSUPPORTED'); }
76
+ async star() { throw new Error('ERR_FEED_UNSUPPORTED'); }
77
+ async edit() { throw new Error('ERR_FEED_UNSUPPORTED'); }
78
+ async forward() { throw new Error('ERR_FEED_UNSUPPORTED'); }
79
+ async delete() { throw new Error('ERR_FEED_UNSUPPORTED'); }
80
+ async text() { throw new Error('ERR_FEED_UNSUPPORTED'); }
81
+ async image() { throw new Error('ERR_FEED_UNSUPPORTED'); }
82
+ async video() { throw new Error('ERR_FEED_UNSUPPORTED'); }
83
+ async audio() { throw new Error('ERR_FEED_UNSUPPORTED'); }
84
+ async location() { throw new Error('ERR_FEED_UNSUPPORTED'); }
85
+ async poll() { throw new Error('ERR_FEED_UNSUPPORTED'); }
86
+ async document() { throw new Error('ERR_FEED_UNSUPPORTED'); }
87
+ async vcard() { throw new Error('ERR_FEED_UNSUPPORTED'); }
88
+ async event() { throw new Error('ERR_FEED_UNSUPPORTED'); }
130
89
  }
131
90
  exports.Feed = Feed;
@@ -3,6 +3,8 @@
3
3
  * @description Barrel del módulo store — reexporta Engine + drivers y expone helpers de serialización.
4
4
  * Store module barrel — re-exports Engine + drivers and provides serialization helpers.
5
5
  */
6
+ import { type WASocket } from 'baileys';
7
+ import type { Engine } from '../../lib/store/engine';
6
8
  export { FileSystemEngine, RedisEngine, S3Engine, SQLiteEngine, type Engine, type RedisClient, type SQLiteDatabase } from '../../lib/store/engine';
7
9
  /**
8
10
  * Serializa un documento a string preservando Buffers con BufferJSON de baileys.
@@ -24,3 +26,17 @@ export declare function serialize<T>(doc: T): string;
24
26
  * @returns Documento parseado o null / Parsed document or null
25
27
  */
26
28
  export declare function deserialize<T>(raw: string | null): T | null;
29
+ /**
30
+ * JID canónico de un teléfono, JID o LID: los grupos y JIDs pasan tal cual, el LID se mapea
31
+ * contra los índices `/lid` del engine (o contra baileys cuando hay socket) y el resto se
32
+ * trata como teléfono.
33
+ * Canonical JID for a phone, JID or LID: groups and JIDs pass through, the LID is mapped
34
+ * against the engine `/lid` indexes (or against baileys when a socket is given) and the rest
35
+ * is treated as a phone.
36
+ *
37
+ * @param engine - Motor con los índices `/lid` / Engine holding the `/lid` indexes
38
+ * @param uid - Identificador crudo / Raw identifier
39
+ * @param socket - Socket vivo para el mapping de baileys, si hay / Live socket for the baileys mapping, if any
40
+ * @returns JID canónico, o null si es irresoluble / Canonical JID, or null when unresolvable
41
+ */
42
+ export declare const jid_of: (engine: Engine, uid: string, socket?: WASocket) => Promise<string | null>;
@@ -5,10 +5,11 @@
5
5
  * Store module barrel — re-exports Engine + drivers and provides serialization helpers.
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.SQLiteEngine = exports.S3Engine = exports.RedisEngine = exports.FileSystemEngine = void 0;
8
+ exports.jid_of = exports.SQLiteEngine = exports.S3Engine = exports.RedisEngine = exports.FileSystemEngine = void 0;
9
9
  exports.serialize = serialize;
10
10
  exports.deserialize = deserialize;
11
11
  const baileys_1 = require("baileys");
12
+ const baileys_2 = require("baileys");
12
13
  var engine_1 = require("../../lib/store/engine");
13
14
  Object.defineProperty(exports, "FileSystemEngine", { enumerable: true, get: function () { return engine_1.FileSystemEngine; } });
14
15
  Object.defineProperty(exports, "RedisEngine", { enumerable: true, get: function () { return engine_1.RedisEngine; } });
@@ -22,7 +23,7 @@ Object.defineProperty(exports, "SQLiteEngine", { enumerable: true, get: function
22
23
  * @returns String JSON / JSON string
23
24
  */
24
25
  function serialize(doc) {
25
- return JSON.stringify(doc, baileys_1.BufferJSON.replacer);
26
+ return JSON.stringify(doc, baileys_2.BufferJSON.replacer);
26
27
  }
27
28
  /**
28
29
  * Deserializa un string JSON a documento aplicando BufferJSON. Retorna null si la entrada es
@@ -40,9 +41,34 @@ function deserialize(raw) {
40
41
  return null;
41
42
  }
42
43
  try {
43
- return JSON.parse(raw, baileys_1.BufferJSON.reviver);
44
+ return JSON.parse(raw, baileys_2.BufferJSON.reviver);
44
45
  }
45
46
  catch {
46
47
  return null;
47
48
  }
48
49
  }
50
+ /**
51
+ * JID canónico de un teléfono, JID o LID: los grupos y JIDs pasan tal cual, el LID se mapea
52
+ * contra los índices `/lid` del engine (o contra baileys cuando hay socket) y el resto se
53
+ * trata como teléfono.
54
+ * Canonical JID for a phone, JID or LID: groups and JIDs pass through, the LID is mapped
55
+ * against the engine `/lid` indexes (or against baileys when a socket is given) and the rest
56
+ * is treated as a phone.
57
+ *
58
+ * @param engine - Motor con los índices `/lid` / Engine holding the `/lid` indexes
59
+ * @param uid - Identificador crudo / Raw identifier
60
+ * @param socket - Socket vivo para el mapping de baileys, si hay / Live socket for the baileys mapping, if any
61
+ * @returns JID canónico, o null si es irresoluble / Canonical JID, or null when unresolvable
62
+ */
63
+ const jid_of = async (engine, uid, socket) => {
64
+ if (uid.endsWith('@g.us') || uid.endsWith('@s.whatsapp.net'))
65
+ return uid;
66
+ const lid = uid.endsWith('@lid') ? (0, baileys_1.jidNormalizedUser)(uid) : '';
67
+ const mapped = lid
68
+ ? deserialize(await engine.get(`/lid/${lid}`))
69
+ ?? deserialize(await engine.get(`/lid/${lid.split('@')[0]}_reverse`))
70
+ ?? await socket?.signalRepository?.lidMapping?.getPNForLID(lid).catch(() => null)
71
+ : uid.replace(/\D/g, '');
72
+ return mapped ? (String(mapped).includes('@') ? (0, baileys_1.jidNormalizedUser)(String(mapped)) : `${mapped}@s.whatsapp.net`) : null;
73
+ };
74
+ exports.jid_of = jid_of;
@@ -1,87 +1,28 @@
1
- /**
2
- * @file whatsapp/index.ts
3
- * @description Orquestador principal del cliente WhatsApp v3.
4
- * Main orchestrator of the WhatsApp v3 client.
5
- */
6
- import { chat, Chat } from '../../lib/chat';
7
- import { contact, Contact } from '../../lib/contact';
8
- import { Audio, Document, Event, Image, Location, Message, Poll, Sticker, Text, VCard, Video } from '../../lib/message';
1
+ import { chat } from '../../lib/chat';
2
+ import { Account, contact } from '../../lib/contact';
3
+ import Message, { message } from '../../lib/message';
9
4
  import { Feed } from '../../lib/status';
10
5
  import { type Engine } from '../../lib/store';
11
- /**
12
- * Opciones del cliente WhatsApp.
13
- * WhatsApp client options.
14
- */
15
- /**
16
- * Configuración de reconexión automática tras cierres no-loggedOut.
17
- * - `true` (default): reintenta indefinidamente con 60s de intervalo.
18
- * - `false`: no reconecta.
19
- * - `number`: máximo N reintentos con 60s de intervalo.
20
- * - `{ max, interval }`: control explícito (interval en segundos).
21
- *
22
- * Automatic reconnection config for non-loggedOut closes.
23
- */
24
- export type ReconnectOption = boolean | number | {
25
- max?: number;
26
- interval?: number;
27
- };
28
- export interface IWhatsApp {
6
+ type ChatInstance = InstanceType<ReturnType<typeof chat>>;
7
+ type ContactInstance = InstanceType<ReturnType<typeof contact>>;
8
+ interface Options {
29
9
  /** Motor de almacenamiento. / Storage engine. */
30
10
  engine: Engine;
31
- /**
32
- * Teléfono de la cuenta. Su presencia habilita el emparejamiento por PIN; sin él la
33
- * vinculación es siempre por QR.
34
- * Account phone. Its presence enables PIN pairing; without it linking is always by QR.
35
- */
11
+ /** Teléfono de la cuenta: su presencia habilita el PIN; sin él la vinculación es por QR. / Account phone: its presence enables the PIN; without it linking is by QR. */
36
12
  phone?: number | string;
37
- /**
38
- * Elige el canal de vinculación **cuando hay `phone`**: `otp` (default) o `qr`. Sin
39
- * `phone` la opción se ignora, porque el PIN no puede pedirse sin número.
40
- * Picks the linking channel **when `phone` is set**: `otp` (default) or `qr`. Without
41
- * `phone` it is ignored, since a PIN cannot be requested without a number.
42
- */
13
+ /** Canal de vinculación cuando hay `phone`; sin `phone` se ignora. / Linking channel when `phone` is set; ignored without it. */
43
14
  method?: 'qr' | 'otp';
44
- /**
45
- * Si al recibir `loggedOut` debe limpiar todo el engine (default: `true`).
46
- * Si es `false`, solo elimina `/session/creds` y preserva historial.
47
- *
48
- * Whether to clear the entire engine on `loggedOut` (default: `true`).
49
- */
15
+ /** Vaciar el engine al recibir `loggedOut`; con `false` sólo borra las credenciales. / Clear the engine on `loggedOut`; with `false` it only drops the credentials. */
50
16
  autoclean?: boolean;
51
- /** Reconexión automática tras cierres no-loggedOut. Default: `true`. / Auto-reconnect on non-loggedOut closes. */
52
- reconnect?: ReconnectOption;
53
- /**
54
- * Descarga del historial de mensajes al vincular (default: `true`). Sólo afecta los
55
- * mensajes: contactos, credenciales, LID mappings y tctokens se sincronizan siempre
56
- * (rc13 los exige para enviar). `false` omite únicamente el historial de mensajes.
57
- *
58
- * Message-history download on link (default: `true`). Messages only: contacts,
59
- * credentials, LID mappings and tctokens always sync (rc13 requires them to send).
60
- */
17
+ /** Reintentos tras cierres no-loggedOut: `true` infinitos, un número como máximo, o el control explícito (`interval` en segundos). / Retries after non-loggedOut closes: `true` for endless, a number as the cap, or explicit control (`interval` in seconds). */
18
+ reconnect?: boolean | number | {
19
+ max?: number;
20
+ interval?: number;
21
+ };
22
+ /** Descargar el historial de mensajes al vincular; contactos, credenciales, LID mappings y tctokens se sincronizan siempre. / Download the message history on link; contacts, credentials, LID mappings and tctokens always sync. */
61
23
  sync?: boolean;
62
24
  }
63
- /**
64
- * Opciones de desconexión.
65
- * Disconnect options.
66
- */
67
- export interface DisconnectOptions {
68
- /** No emitir el evento `disconnected` de este cierre. / Suppress this close's `disconnected` event. */
69
- silent?: boolean;
70
- /** Vaciar el engine tras cerrar. / Clear the engine after closing. */
71
- destroy?: boolean;
72
- }
73
- /** Argumentos de un estático de envío sin el cliente ni el cid. / Send-static arguments without client and cid. */
74
- type Tail<P extends unknown[]> = P extends [unknown, unknown, ...infer R] ? R : never;
75
- type MessageInstance = Message;
76
- type ChatInstance = InstanceType<ReturnType<typeof chat>>;
77
- type ContactInstance = InstanceType<ReturnType<typeof contact>>;
78
- /**
79
- * Mapa de eventos emitidos por el cliente. Cada listener recibe el artefacto principal seguido
80
- * de la instancia del cliente como último argumento.
81
- * Map of events emitted by the client. Each listener receives the primary payload followed by
82
- * the client instance as the last argument.
83
- */
84
- interface WhatsAppEventMap {
25
+ interface EventMap {
85
26
  connected: [WhatsApp];
86
27
  disconnected: [WhatsApp];
87
28
  'contact:created': [ContactInstance, ChatInstance, WhatsApp];
@@ -94,151 +35,42 @@ interface WhatsAppEventMap {
94
35
  'chat:unarchived': [ChatInstance, WhatsApp];
95
36
  'chat:muted': [ChatInstance, WhatsApp];
96
37
  'chat:unmuted': [ChatInstance, WhatsApp];
97
- 'message:created': [MessageInstance, ChatInstance, WhatsApp];
98
- 'message:updated': [MessageInstance, ChatInstance, WhatsApp];
99
- 'message:deleted': [MessageInstance, ChatInstance, WhatsApp];
100
- 'message:reacted': [MessageInstance, ChatInstance, string, WhatsApp];
101
- 'message:starred': [MessageInstance, ChatInstance, WhatsApp];
102
- 'message:unstarred': [MessageInstance, ChatInstance, WhatsApp];
103
- 'message:forwarded': [MessageInstance, ChatInstance, WhatsApp];
104
- 'message:seen': [MessageInstance, ChatInstance, WhatsApp];
38
+ 'message:created': [Message, ChatInstance, WhatsApp];
39
+ 'message:updated': [Message, ChatInstance, WhatsApp];
40
+ 'message:deleted': [Message, ChatInstance, WhatsApp];
41
+ 'message:reacted': [Message, ChatInstance, string, WhatsApp];
42
+ 'message:starred': [Message, ChatInstance, WhatsApp];
43
+ 'message:unstarred': [Message, ChatInstance, WhatsApp];
44
+ 'message:forwarded': [Message, ChatInstance, WhatsApp];
45
+ 'message:seen': [Message, ChatInstance, WhatsApp];
105
46
  'feed:created': [Feed, WhatsApp];
106
47
  'feed:updated': [Feed, WhatsApp];
107
48
  'feed:deleted': [Feed, WhatsApp];
108
49
  }
109
- /**
110
- * Cliente principal de WhatsApp. No inicia la conexión al instanciar.
111
- * Main WhatsApp client. Does not connect on instantiation.
112
- *
113
- * @example
114
- * const wa = new WhatsApp({ engine: new FileSystemEngine(__dirname), phone: 5491112345678 });
115
- * wa.on('message:created', (msg) => console.log(msg.caption));
116
- * await wa.connect((code) => console.log(code));
117
- */
118
- export declare class WhatsApp {
50
+ export default class WhatsApp {
119
51
  #private;
120
- /** Motor de almacenamiento de la sesión. / Session storage engine. */
121
52
  readonly engine: Engine;
122
- /** Entidad `Contact` ligada a este cliente. / `Contact` entity bound to this client. */
123
- readonly Contact: ReturnType<typeof contact>;
124
- /** Entidad `Chat` ligada a este cliente. / `Chat` entity bound to this client. */
125
- readonly Chat: ReturnType<typeof chat>;
126
- /**
127
- * Entidad `Message` ligada a este cliente: los mismos estáticos de `Message` sin repetir
128
- * la instancia, más las subclases para `instanceof`.
129
- * `Message` entity bound to this client: the same `Message` statics without repeating the
130
- * instance, plus the subclasses for `instanceof`.
131
- */
132
- readonly Message: {
133
- get: (cid: string, mid: string) => ReturnType<typeof Message.get>;
134
- list: (cid: string, offset?: number, limit?: number) => ReturnType<typeof Message.list>;
135
- text: (cid: string, ...rest: Tail<Parameters<typeof Message.text>>) => ReturnType<typeof Message.text>;
136
- image: (cid: string, ...rest: Tail<Parameters<typeof Message.image>>) => ReturnType<typeof Message.image>;
137
- video: (cid: string, ...rest: Tail<Parameters<typeof Message.video>>) => ReturnType<typeof Message.video>;
138
- audio: (cid: string, ...rest: Tail<Parameters<typeof Message.audio>>) => ReturnType<typeof Message.audio>;
139
- location: (cid: string, ...rest: Tail<Parameters<typeof Message.location>>) => ReturnType<typeof Message.location>;
140
- poll: (cid: string, ...rest: Tail<Parameters<typeof Message.poll>>) => ReturnType<typeof Message.poll>;
141
- document: (cid: string, ...rest: Tail<Parameters<typeof Message.document>>) => ReturnType<typeof Message.document>;
142
- vcard: (cid: string, ...rest: Tail<Parameters<typeof Message.vcard>>) => ReturnType<typeof Message.vcard>;
143
- event: (cid: string, ...rest: Tail<Parameters<typeof Message.event>>) => ReturnType<typeof Message.event>;
144
- react: (cid: string, mid: string, emoji: string) => Promise<boolean>;
145
- star: (cid: string, mid: string, value: boolean) => Promise<boolean>;
146
- seen: (cid: string, mid: string) => Promise<boolean>;
147
- edit: (cid: string, mid: string, caption: string) => Promise<boolean>;
148
- forward: (cid: string, mid: string, target: string | Chat | Contact) => Promise<boolean>;
149
- delete: (cid: string, mid: string, all?: boolean) => Promise<boolean>;
150
- reactions: (cid: string, mid: string) => Promise<{
151
- emoji: string;
152
- count: number;
153
- }[]>;
154
- Text: typeof Text;
155
- Image: typeof Image;
156
- Video: typeof Video;
157
- Audio: typeof Audio;
158
- Sticker: typeof Sticker;
159
- Document: typeof Document;
160
- Location: typeof Location;
161
- Poll: typeof Poll;
162
- VCard: typeof VCard;
163
- Event: typeof Event;
164
- };
165
- constructor(options: IWhatsApp);
166
- /**
167
- * Contacto de la cuenta autenticada, o null mientras no hay sesión abierta.
168
- * Authenticated account's contact, or null while there is no open session.
169
- */
170
- get contact(): InstanceType<ReturnType<typeof contact>> | null;
171
- /**
172
- * Emite un evento del cliente. Lo usan las entidades de la librería para propagar los
173
- * cambios que provocan; el consumidor puede emitir los suyos para pruebas.
174
- * Emits a client event. Library entities use it to propagate the changes they cause;
175
- * consumers may emit their own for testing.
176
- *
177
- * @param event - Nombre del evento / Event name
178
- * @param args - Argumentos del evento / Event arguments
179
- * @returns true si había listeners / true when listeners were present
180
- */
181
- emit<E extends keyof WhatsAppEventMap>(event: E, ...args: WhatsAppEventMap[E]): boolean;
182
- /**
183
- * Registra un listener de evento. Retorna función para desuscribirse.
184
- * Registers an event listener. Returns an unsubscribe function.
185
- */
186
- on<E extends keyof WhatsAppEventMap>(event: E, handler: (...args: WhatsAppEventMap[E]) => void): () => void;
187
- /**
188
- * Quita un listener previamente registrado.
189
- * Removes a previously registered listener.
190
- */
191
- off<E extends keyof WhatsAppEventMap>(event: E, handler: (...args: WhatsAppEventMap[E]) => void): this;
192
- /**
193
- * Registra un listener one-shot. Retorna función para desuscribirse antes de que dispare.
194
- * Registers a one-shot listener. Returns an unsubscribe function.
195
- */
196
- once<E extends keyof WhatsAppEventMap>(event: E, handler: (...args: WhatsAppEventMap[E]) => void): () => void;
197
- /**
198
- * Inicia la conexión. El callback recibe el PIN (string) si se configuró `phone`, o el QR (Buffer PNG) si no.
199
- * Resuelve cuando la sesión sincroniza; reintenta automáticamente en cierres no-loggedOut.
200
- *
201
- * Starts the connection. Callback receives the PIN (string) when `phone` is configured, or the QR (PNG Buffer) otherwise.
202
- * Resolves once the session is synced; retries on non-loggedOut disconnects.
203
- */
53
+ Contact: ReturnType<typeof contact>;
54
+ Chat: ReturnType<typeof chat>;
55
+ /** Entidad `Message`, publicada al conectar. / `Message` entity, published on connect. */
56
+ Message: ReturnType<typeof message>;
57
+ /** Cuenta autenticada, publicada al conectar; null mientras no hay usuario. / Authenticated account, published on connect; null while there is no user. */
58
+ account: () => Promise<Account | null>;
59
+ constructor(options: Options);
60
+ emit<E extends keyof EventMap>(event: E, ...args: EventMap[E]): boolean;
61
+ on<E extends keyof EventMap>(event: E, handler: (...args: EventMap[E]) => void): () => void;
62
+ once<E extends keyof EventMap>(event: E, handler: (...args: EventMap[E]) => void): () => void;
63
+ off<E extends keyof EventMap>(event: E, handler: (...args: EventMap[E]) => void): this;
204
64
  connect(callback: (auth: string | Buffer) => void | Promise<void>): Promise<void>;
205
65
  /**
206
- * Actualiza el perfil de la cuenta en WhatsApp: nombre público, bio y/o foto. Sólo se
207
- * envía lo que llega en el parche; `photo: null` elimina la foto actual.
208
- * Updates the account profile on WhatsApp: public name, bio and/or picture. Only the
209
- * given fields are sent; `photo: null` removes the current picture.
66
+ * Cierra la sesión: cancela el reintento pendiente y termina el socket.
67
+ * Closes the session: cancels the pending retry and ends the socket.
210
68
  *
211
- * @param patch - Campos a actualizar / Fields to update
212
- * @returns true si todo lo pedido se envió / true when everything requested was sent
213
- * @throws ERR_PROFILE_PICTURE_LIB si falta `sharp` o `jimp` para procesar la foto / when `sharp` or `jimp` is missing to process the picture
214
- */
215
- profile(patch: {
216
- name?: string;
217
- content?: string;
218
- photo?: string | Buffer | null;
219
- }): Promise<boolean>;
220
- /**
221
- * Publica un estado (status broadcast). Con sólo `caption` publica texto; con `content`
222
- * publica imagen o video (el tipo se deduce del binario) usando `caption` como pie.
223
- * `contacts` es la audiencia: WhatsApp no reparte el estado a quien no esté en la lista.
224
- * Publishes a status broadcast. With only `caption` it posts text; with `content` it
225
- * posts an image or video (type inferred from the binary) using `caption` as its footer.
226
- * `contacts` is the audience: WhatsApp does not deliver the status to anyone outside it.
227
- *
228
- * @param post - Contenido, pie y audiencia / Content, caption and audience
229
- * @returns Publicación creada, o null si no hay sesión / Created post, or null without a session
230
- * @throws ERR_FEED_EMPTY sin `content` ni `caption` / when neither `content` nor `caption` is given
231
- * @throws ERR_FEED_MEDIA si el binario no es imagen ni video / when the binary is neither image nor video
232
- */
233
- feed(post: {
234
- content?: Buffer;
235
- caption?: string;
236
- contacts: (string | number)[];
237
- }): Promise<Feed | null>;
238
- /**
239
- * Cierra la conexión. Con `destroy: true` vacía el engine completo.
240
- * Closes the connection. With `destroy: true` clears the engine entirely.
69
+ * @param options - `silent` calla el evento `disconnected`; `destroy` vacía el engine / `silent` mutes the `disconnected` event; `destroy` clears the engine
241
70
  */
242
- disconnect(options?: DisconnectOptions): Promise<void>;
71
+ disconnect(options?: {
72
+ silent?: boolean;
73
+ destroy?: boolean;
74
+ }): Promise<void>;
243
75
  }
244
- export default WhatsApp;
76
+ export {};