@yui-bails/yui-bails 1.3.0 → 1.4.2

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 (73) hide show
  1. package/README.md +243 -1
  2. package/lib/Socket/connect-bot.d.ts +88 -0
  3. package/lib/Socket/connect-bot.d.ts.map +1 -1
  4. package/lib/Socket/connect-bot.js +1 -0
  5. package/lib/Socket/connect-bot.js.map +1 -1
  6. package/lib/Socket/index.d.ts +56 -12
  7. package/lib/Socket/index.d.ts.map +1 -1
  8. package/lib/Socket/index.js +37 -1
  9. package/lib/Socket/index.js.map +1 -1
  10. package/lib/Socket/messages-send.js +1 -1
  11. package/lib/Socket/messages-send.js.map +1 -1
  12. package/lib/Socket/session-manager.d.ts +44 -0
  13. package/lib/Socket/session-manager.d.ts.map +1 -1
  14. package/lib/Types/Message.d.ts +16 -0
  15. package/lib/Types/Message.d.ts.map +1 -1
  16. package/lib/Types/Socket.d.ts +7 -0
  17. package/lib/Types/Socket.d.ts.map +1 -1
  18. package/lib/Types/Socket.js.map +1 -1
  19. package/lib/Utils/banner.d.ts +4 -2
  20. package/lib/Utils/banner.d.ts.map +1 -1
  21. package/lib/Utils/banner.js +6 -4
  22. package/lib/Utils/banner.js.map +1 -1
  23. package/lib/Utils/channel.d.ts +9 -0
  24. package/lib/Utils/channel.d.ts.map +1 -0
  25. package/lib/Utils/channel.js +17 -0
  26. package/lib/Utils/channel.js.map +1 -0
  27. package/lib/Utils/group-fetch.d.ts +7 -2
  28. package/lib/Utils/group-fetch.d.ts.map +1 -1
  29. package/lib/Utils/group-fetch.js +12 -2
  30. package/lib/Utils/group-fetch.js.map +1 -1
  31. package/lib/Utils/helpers.d.ts +20 -1
  32. package/lib/Utils/helpers.d.ts.map +1 -1
  33. package/lib/Utils/helpers.js +32 -5
  34. package/lib/Utils/helpers.js.map +1 -1
  35. package/lib/Utils/html-format.d.ts +12 -0
  36. package/lib/Utils/html-format.d.ts.map +1 -0
  37. package/lib/Utils/html-format.js +344 -0
  38. package/lib/Utils/html-format.js.map +1 -0
  39. package/lib/Utils/index.d.ts +8 -0
  40. package/lib/Utils/index.d.ts.map +1 -1
  41. package/lib/Utils/index.js +8 -0
  42. package/lib/Utils/index.js.map +1 -1
  43. package/lib/Utils/messages.d.ts.map +1 -1
  44. package/lib/Utils/messages.js +31 -1
  45. package/lib/Utils/messages.js.map +1 -1
  46. package/lib/Utils/pretty-log.d.ts.map +1 -1
  47. package/lib/Utils/pretty-log.js +7 -3
  48. package/lib/Utils/pretty-log.js.map +1 -1
  49. package/lib/Utils/reconnect.d.ts +53 -0
  50. package/lib/Utils/reconnect.d.ts.map +1 -0
  51. package/lib/Utils/reconnect.js +82 -0
  52. package/lib/Utils/reconnect.js.map +1 -0
  53. package/lib/Utils/send-extras.d.ts +155 -0
  54. package/lib/Utils/send-extras.d.ts.map +1 -0
  55. package/lib/Utils/send-extras.js +253 -0
  56. package/lib/Utils/send-extras.js.map +1 -0
  57. package/lib/Utils/send-retry.d.ts +21 -0
  58. package/lib/Utils/send-retry.d.ts.map +1 -0
  59. package/lib/Utils/send-retry.js +28 -0
  60. package/lib/Utils/send-retry.js.map +1 -0
  61. package/lib/Utils/session-backup.d.ts +21 -0
  62. package/lib/Utils/session-backup.d.ts.map +1 -0
  63. package/lib/Utils/session-backup.js +61 -0
  64. package/lib/Utils/session-backup.js.map +1 -0
  65. package/lib/Utils/timed-poll.d.ts +71 -0
  66. package/lib/Utils/timed-poll.d.ts.map +1 -0
  67. package/lib/Utils/timed-poll.js +101 -0
  68. package/lib/Utils/timed-poll.js.map +1 -0
  69. package/lib/Utils/use-single-file-auth-state.d.ts +21 -0
  70. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  71. package/lib/Utils/use-single-file-auth-state.js +134 -0
  72. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  73. package/package.json +1 -1
@@ -0,0 +1,253 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { WAProto } from '../Types/index.js';
3
+ import { parseChannelKey } from './channel.js';
4
+ import { generateMessageIDV2 } from './generics.js';
5
+ import { htmlToWhatsApp } from './html-format.js';
6
+ const MAX_ALBUM = 10;
7
+ const KEYCAPS = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟'];
8
+ const toDate = (value, label) => {
9
+ const date = value instanceof Date ? value : new Date(value);
10
+ if (Number.isNaN(date.getTime()))
11
+ throw new Boom(`Invalid ${label} date "${String(value)}"`, { statusCode: 400 });
12
+ return date;
13
+ };
14
+ /** a vCard 3.0 with the `waid` that lets WhatsApp show "Message" / "Add to contacts" */
15
+ export const buildVCard = ({ name, number, organization }) => {
16
+ const digits = number.replace(/\D/g, '');
17
+ if (!digits)
18
+ throw new Boom('A contact needs a phone number with the country code', { statusCode: 400 });
19
+ const clean = (text) => text.replace(/[\r\n]+/g, ' ').replace(/([,;\\])/g, '\\$1');
20
+ return [
21
+ 'BEGIN:VCARD',
22
+ 'VERSION:3.0',
23
+ `FN:${clean(name)}`,
24
+ ...(organization ? [`ORG:${clean(organization)};`] : []),
25
+ `TEL;type=CELL;type=VOICE;waid=${digits}:+${digits}`,
26
+ 'END:VCARD'
27
+ ].join('\n');
28
+ };
29
+ /** splits a long text on paragraph, line or space boundaries, never in the middle of a word when avoidable */
30
+ export const splitText = (text, maxLength) => {
31
+ if (!Number.isInteger(maxLength) || maxLength < 10) {
32
+ throw new Boom('maxLength must be a whole number of at least 10', { statusCode: 400 });
33
+ }
34
+ const parts = [];
35
+ let rest = text.trim();
36
+ while (rest.length > maxLength) {
37
+ const window = rest.slice(0, maxLength + 1);
38
+ let cut = Math.max(window.lastIndexOf('\n\n'), 0);
39
+ if (cut < maxLength / 2)
40
+ cut = window.lastIndexOf('\n');
41
+ if (cut < maxLength / 2)
42
+ cut = window.lastIndexOf(' ');
43
+ if (cut < maxLength / 2)
44
+ cut = maxLength;
45
+ parts.push(rest.slice(0, cut).trimEnd());
46
+ rest = rest.slice(cut).trimStart();
47
+ }
48
+ if (rest)
49
+ parts.push(rest);
50
+ return parts;
51
+ };
52
+ /** shortcuts for the messages people ask for most: contacts, location, album, event and long text */
53
+ export const makeSendExtras = (sock, deps = {}) => {
54
+ const wait = deps.sleep || ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
55
+ const sendAlbum = async (jid, items, options) => {
56
+ if (!Array.isArray(items) || items.length < 2 || items.length > MAX_ALBUM) {
57
+ throw new Boom(`An album needs between 2 and ${MAX_ALBUM} items`, { statusCode: 400 });
58
+ }
59
+ const images = items.filter(item => 'image' in item).length;
60
+ const videos = items.length - images;
61
+ const album = await sock.sendMessage(jid, { album: { expectedImageCount: images, expectedVideoCount: videos } }, options);
62
+ if (!album?.key)
63
+ throw new Boom('WhatsApp did not accept the album', { statusCode: 500 });
64
+ const sent = [];
65
+ for (const item of items) {
66
+ sent.push(await sock.sendMessage(jid, { ...item, albumParentKey: album.key }, options));
67
+ }
68
+ return { album, items: sent };
69
+ };
70
+ return {
71
+ /** contact card(s). A text is taken as a number: `sendContact(jid, '5731…')` */
72
+ sendContact: (jid, contacts, options) => {
73
+ const list = typeof contacts === 'string'
74
+ ? [{ name: contacts, number: contacts }]
75
+ : Array.isArray(contacts)
76
+ ? contacts
77
+ : [contacts];
78
+ if (!list.length)
79
+ throw new Boom('sendContact needs at least one contact', { statusCode: 400 });
80
+ return sock.sendMessage(jid, {
81
+ contacts: {
82
+ displayName: list.length === 1 ? list[0].name : `${list.length} contactos`,
83
+ contacts: list.map(contact => ({ displayName: contact.name, vcard: buildVCard(contact) }))
84
+ }
85
+ }, options);
86
+ },
87
+ /** a map pin */
88
+ sendLocation: (jid, { latitude, longitude, name, address }, options) => {
89
+ if (!(latitude >= -90 && latitude <= 90) || !(longitude >= -180 && longitude <= 180)) {
90
+ throw new Boom('Invalid coordinates: latitude is -90 to 90 and longitude is -180 to 180', { statusCode: 400 });
91
+ }
92
+ return sock.sendMessage(jid, { location: { degreesLatitude: latitude, degreesLongitude: longitude, name, address } }, options);
93
+ },
94
+ /** 2 to 10 photos / videos that WhatsApp groups in one album */
95
+ sendAlbum,
96
+ /** an event invitation */
97
+ sendEvent: (jid, event, options) => {
98
+ if (!event?.name)
99
+ throw new Boom('An event needs a name', { statusCode: 400 });
100
+ const startDate = toDate(event.start, 'start');
101
+ const endDate = event.end === undefined ? undefined : toDate(event.end, 'end');
102
+ if (endDate && endDate < startDate)
103
+ throw new Boom('The event cannot end before it starts', { statusCode: 400 });
104
+ return sock.sendMessage(jid, {
105
+ event: {
106
+ name: event.name,
107
+ description: event.description,
108
+ startDate,
109
+ endDate,
110
+ location: event.location ? { name: event.location } : undefined,
111
+ call: event.call
112
+ }
113
+ }, options);
114
+ },
115
+ /** a long text split in several messages, in order. Only the first one quotes */
116
+ sendLong: async (jid, text, long = {}, options) => {
117
+ const parts = splitText(text, long.maxLength ?? 4000);
118
+ if (!parts.length)
119
+ throw new Boom('sendLong needs some text', { statusCode: 400 });
120
+ const sent = [];
121
+ for (const [index, part] of parts.entries()) {
122
+ if (index > 0 && long.delayMs)
123
+ await wait(long.delayMs);
124
+ // only the first part quotes the original message
125
+ const rest = { ...options };
126
+ delete rest.quoted;
127
+ sent.push(await sock.sendMessage(jid, { text: part }, index === 0 ? options : rest));
128
+ }
129
+ return sent;
130
+ },
131
+ /**
132
+ * A poll whose options have a picture. WhatsApp's own "poll with images" has no documented
133
+ * format, so this sends the pictures as an album (each one numbered with its option) and then
134
+ * a normal poll with the same options: it works on every version.
135
+ */
136
+ sendImagePoll: async (jid, poll, options) => {
137
+ const choices = poll?.options;
138
+ if (!Array.isArray(choices) || choices.length < 2 || choices.length > MAX_ALBUM) {
139
+ throw new Boom(`An image poll needs between 2 and ${MAX_ALBUM} options`, { statusCode: 400 });
140
+ }
141
+ const album = await sendAlbum(jid, choices.map((choice, index) => ({ image: choice.image, caption: `${KEYCAPS[index]} ${choice.text}` })), options);
142
+ const values = choices.map(choice => choice.text);
143
+ const sendPoll = deps.sendPoll ||
144
+ ((target, name, list, extra, opts) => sock.sendMessage(target, { poll: { name, values: list, selectableCount: 1, ...extra } }, opts));
145
+ const sent = await sendPoll(jid, poll.name, values, { selectableCount: poll.selectableCount ?? 1 }, options);
146
+ return { album, poll: sent };
147
+ },
148
+ /** an invitation to a call at a given time. Experimental: depends on the WhatsApp version that receives it */
149
+ sendScheduledCall: (jid, call, options) => {
150
+ if (!call?.title)
151
+ throw new Boom('A scheduled call needs a title', { statusCode: 400 });
152
+ return sock.sendMessage(jid, { scheduledCall: { title: call.title, startDate: toDate(call.start, 'start'), type: call.type } }, options);
153
+ },
154
+ /**
155
+ * Posts a status that mentions people, and tells each one. Experimental: it follows what other
156
+ * libraries do and has not been confirmed by Yui-Bails on real phones.
157
+ */
158
+ sendStatusMention: async (content, { mentions, backgroundColor, font }) => {
159
+ const targets = [...new Set((mentions || []).filter(Boolean))];
160
+ if (!targets.length)
161
+ throw new Boom('sendStatusMention needs at least one jid in `mentions`', { statusCode: 400 });
162
+ if (!sock.relayMessage)
163
+ throw new Boom('This socket cannot relay messages', { statusCode: 501 });
164
+ const mentionedUsers = {
165
+ tag: 'meta',
166
+ attrs: {},
167
+ content: [
168
+ {
169
+ tag: 'mentioned_users',
170
+ attrs: {},
171
+ content: targets.map(jid => ({ tag: 'to', attrs: { jid }, content: undefined }))
172
+ }
173
+ ]
174
+ };
175
+ const status = await sock.sendMessage('status@broadcast', { ...content, mentions: targets }, {
176
+ statusJidList: targets,
177
+ backgroundColor,
178
+ font,
179
+ additionalNodes: [mentionedUsers]
180
+ });
181
+ if (!status?.key)
182
+ throw new Boom('WhatsApp did not accept the status', { statusCode: 500 });
183
+ for (const jid of targets) {
184
+ await sock.relayMessage(jid, {
185
+ statusMentionMessage: {
186
+ message: {
187
+ protocolMessage: { key: status.key, type: WAProto.Message.ProtocolMessage.Type.STATUS_MENTION_MESSAGE }
188
+ }
189
+ }
190
+ }, {
191
+ messageId: generateMessageIDV2(),
192
+ additionalNodes: [{ tag: 'meta', attrs: { is_status_mention: 'true' }, content: undefined }]
193
+ });
194
+ }
195
+ return status;
196
+ },
197
+ /** Reads a channel from its link, invite code or id (`120363…@newsletter`). `null` when it does not exist. */
198
+ channelInfo: async (input) => {
199
+ if (!deps.newsletterMetadata)
200
+ throw new Boom('This socket cannot read channels', { statusCode: 501 });
201
+ const { type, key } = parseChannelKey(input);
202
+ return deps.newsletterMetadata(type, key);
203
+ },
204
+ /**
205
+ * Sends HTML as a WhatsApp message. WhatsApp has no HTML, so `<b>`, `<i>`, `<s>`, `<code>`, `<pre>`,
206
+ * lists, quotes, links and simple tables become its own formatting; anything else keeps only its text.
207
+ */
208
+ sendHtml: async (jid, html, options) => {
209
+ const text = htmlToWhatsApp(html);
210
+ if (!text)
211
+ throw new Boom('The HTML has no text to send', { statusCode: 400 });
212
+ return sock.sendMessage(jid, { text }, options);
213
+ },
214
+ /**
215
+ * Notifies the whole group with one message. With `members` (default) the text can be anything,
216
+ * even empty-looking, and every member is mentioned; with `all` it uses WhatsApp's "@all".
217
+ */
218
+ tagAll: async (jid, text, { mode = 'members' } = {}, options) => {
219
+ if (!jid.endsWith('@g.us'))
220
+ throw new Boom('tagAll only works in groups', { statusCode: 400 });
221
+ if (mode === 'all')
222
+ return sock.sendMessage(jid, { text, mentionAll: true }, options);
223
+ if (!deps.groupMetadata)
224
+ throw new Boom('This socket cannot read group members', { statusCode: 501 });
225
+ const group = await deps.groupMetadata(jid);
226
+ const mentions = [...new Set(group.participants.map(member => member.id))];
227
+ return sock.sendMessage(jid, { text, mentions }, options);
228
+ },
229
+ /**
230
+ * Sends a question and waits for the answer of the same person in that chat.
231
+ * Resolves the text, or `undefined` when time runs out. (A real question box has no documented
232
+ * format yet; this works everywhere.)
233
+ */
234
+ ask: async (to, question, { timeoutMs = 60000 } = {}) => {
235
+ if (!deps.awaitReply)
236
+ throw new Boom('This socket cannot wait for replies', { statusCode: 501 });
237
+ const jid = to.key.remoteJid;
238
+ if (!jid)
239
+ throw new Boom('The message has no chat', { statusCode: 400 });
240
+ await sock.sendMessage(jid, { text: question }, { quoted: to });
241
+ const answer = await deps.awaitReply(to, { timeoutMs });
242
+ if (!answer)
243
+ return undefined;
244
+ const content = answer.message;
245
+ return (content?.conversation ||
246
+ content?.extendedTextMessage?.text ||
247
+ content?.imageMessage?.caption ||
248
+ content?.videoMessage?.caption ||
249
+ '');
250
+ }
251
+ };
252
+ };
253
+ //# sourceMappingURL=send-extras.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send-extras.js","sourceRoot":"","sources":["../../src/Utils/send-extras.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAEjC,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAA;AAElC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAmG9C,MAAM,SAAS,GAAG,EAAE,CAAA;AACpB,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AAErF,MAAM,MAAM,GAAG,CAAC,KAA6B,EAAE,KAAa,EAAQ,EAAE;IACrE,MAAM,IAAI,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAA;IAC5D,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QAAE,MAAM,IAAI,IAAI,CAAC,WAAW,KAAK,UAAU,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,CAAA;IACjH,OAAO,IAAI,CAAA;AACZ,CAAC,C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AE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAA;YAC/D,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,CAAA;YACvD,IAAI,CAAC,MAAM;gBAAE,OAAO,SAAS,CAAA;YAE7B,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAA;YAC9B,OAAO,CACN,OAAO,EAAE,YAAY;gBACrB,OAAO,EAAE,mBAAmB,EAAE,IAAI;gBAClC,OAAO,EAAE,YAAY,EAAE,OAAO;gBAC9B,OAAO,EAAE,YAAY,EAAE,OAAO;gBAC9B,EAAE,CACF,CAAA;QACF,CAAC;KACD,CAAA;AACF,CAAC,CAAA"}
@@ -0,0 +1,21 @@
1
+ export type SendRetryOptions = {
2
+ /** extra tries after the first one. Default 2 */
3
+ retries?: number;
4
+ /** first wait in ms, doubled each retry. Default 1500 */
5
+ baseDelayMs?: number;
6
+ /** our own user id, used to make the message id */
7
+ userId?: () => string | undefined;
8
+ /** replaceable for tests */
9
+ sleep?: (ms: number) => Promise<void>;
10
+ onRetry?: (error: unknown, attempt: number) => void;
11
+ };
12
+ type SendFn = (jid: string, content: any, options?: any) => Promise<any>;
13
+ /**
14
+ * Retries a send that failed for a reason that usually passes (rate limit, timeout, empty answer).
15
+ *
16
+ * Every try uses the SAME message id, so if the first try actually reached WhatsApp and only its
17
+ * answer was lost, the retry is recognised as the same message and does not arrive twice.
18
+ */
19
+ export declare const withSendRetry: <F extends SendFn>(send: F, { retries, baseDelayMs, userId, sleep, onRetry }?: SendRetryOptions) => F;
20
+ export {};
21
+ //# sourceMappingURL=send-retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send-retry.d.ts","sourceRoot":"","sources":["../../src/Utils/send-retry.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,gBAAgB,GAAG;IAC9B,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,yDAAyD;IACzD,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,MAAM,GAAG,SAAS,CAAA;IACjC,4BAA4B;IAC5B,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACrC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;CACnD,CAAA;AAED,KAAK,MAAM,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAA;AAExE;;;;;GAKG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,MAAM,EAC7C,MAAM,CAAC,EACP,mDAA6D,gBAAqB,KAChF,CAmBF,CAAA"}
@@ -0,0 +1,28 @@
1
+ import { generateMessageIDV2 } from './generics.js';
2
+ import { isTransient } from './group-fetch.js';
3
+ /**
4
+ * Retries a send that failed for a reason that usually passes (rate limit, timeout, empty answer).
5
+ *
6
+ * Every try uses the SAME message id, so if the first try actually reached WhatsApp and only its
7
+ * answer was lost, the retry is recognised as the same message and does not arrive twice.
8
+ */
9
+ export const withSendRetry = (send, { retries = 2, baseDelayMs = 1500, userId, sleep, onRetry } = {}) => {
10
+ const wait = sleep || ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
11
+ const retrying = async (jid, content, options = {}) => {
12
+ const messageId = options.messageId || generateMessageIDV2(userId?.());
13
+ const tryOptions = { ...options, messageId };
14
+ for (let attempt = 0;; attempt++) {
15
+ try {
16
+ return await send(jid, content, tryOptions);
17
+ }
18
+ catch (error) {
19
+ if (attempt >= retries || !isTransient(error))
20
+ throw error;
21
+ onRetry?.(error, attempt + 1);
22
+ await wait(baseDelayMs * 2 ** attempt);
23
+ }
24
+ }
25
+ };
26
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,CAAC,IAAI,OAAO,CAAC,CAAA;YACvC,CAAC;QACF,CAAC;IACF,CAAC,CAAA;IAED,OAAO,QAAa,CAAA;AACrB,CAAC,CAAA"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Saves the login of a session (its auth folder) in ONE compressed file.
3
+ * The file holds the keys of the account: whoever has it can use the account. Keep it private.
4
+ */
5
+ export declare const backupSession: (authDir: string, file: string) => Promise<{
6
+ file: string;
7
+ files: number;
8
+ createdAt: string;
9
+ }>;
10
+ /**
11
+ * Restores a login saved with `backupSession`. It refuses to replace an existing login unless
12
+ * `overwrite` is true.
13
+ */
14
+ export declare const restoreSession: (file: string, authDir: string, { overwrite }?: {
15
+ overwrite?: boolean | undefined;
16
+ }) => Promise<{
17
+ authDir: string;
18
+ files: number;
19
+ createdAt: string;
20
+ }>;
21
+ //# sourceMappingURL=session-backup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-backup.d.ts","sourceRoot":"","sources":["../../src/Utils/session-backup.ts"],"names":[],"mappings":"AAsBA;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAU,SAAS,MAAM,EAAE,MAAM,MAAM;;;;EAkBhE,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,GAAU,MAAM,MAAM,EAAE,SAAS,MAAM,EAAE;;CAA0B;;;;EAkC7F,CAAA"}
@@ -0,0 +1,61 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { mkdir, readdir, readFile, stat, writeFile } from 'fs/promises';
3
+ import { dirname, join } from 'path';
4
+ import { promisify } from 'util';
5
+ import { gunzip, gzip } from 'zlib';
6
+ const gzipAsync = promisify(gzip);
7
+ const gunzipAsync = promisify(gunzip);
8
+ const FORMAT = 'yui-bails-session';
9
+ /** auth folders are flat: only plain file names are accepted, so a backup can never write elsewhere */
10
+ const isPlainName = (name) => /^[\w.@=+-]+$/.test(name) && name !== '.' && name !== '..';
11
+ /**
12
+ * Saves the login of a session (its auth folder) in ONE compressed file.
13
+ * The file holds the keys of the account: whoever has it can use the account. Keep it private.
14
+ */
15
+ export const backupSession = async (authDir, file) => {
16
+ const names = (await readdir(authDir).catch(() => [])).filter(isPlainName);
17
+ const files = {};
18
+ for (const name of names) {
19
+ const path = join(authDir, name);
20
+ if ((await stat(path)).isFile())
21
+ files[name] = (await readFile(path)).toString('base64');
22
+ }
23
+ if (!files['creds.json']) {
24
+ throw new Boom(`There is no login in "${authDir}" (creds.json is missing): nothing to back up`, { statusCode: 404 });
25
+ }
26
+ const data = { format: FORMAT, version: 1, createdAt: new Date().toISOString(), files };
27
+ await mkdir(dirname(file), { recursive: true });
28
+ await writeFile(file, await gzipAsync(Buffer.from(JSON.stringify(data))), { mode: 0o600 });
29
+ return { file, files: Object.keys(files).length, createdAt: data.createdAt };
30
+ };
31
+ /**
32
+ * Restores a login saved with `backupSession`. It refuses to replace an existing login unless
33
+ * `overwrite` is true.
34
+ */
35
+ export const restoreSession = async (file, authDir, { overwrite = false } = {}) => {
36
+ let data;
37
+ try {
38
+ data = JSON.parse((await gunzipAsync(await readFile(file))).toString());
39
+ }
40
+ catch {
41
+ throw new Boom('That is not a valid Yui-Bails session backup', { statusCode: 400 });
42
+ }
43
+ if (data?.format !== FORMAT || data.version !== 1 || typeof data.files !== 'object' || !data.files) {
44
+ throw new Boom('That is not a valid Yui-Bails session backup', { statusCode: 400 });
45
+ }
46
+ const entries = Object.entries(data.files);
47
+ if (entries.some(([name, content]) => !isPlainName(name) || typeof content !== 'string') ||
48
+ !data.files['creds.json']) {
49
+ throw new Boom('The backup has unsafe or missing files', { statusCode: 400 });
50
+ }
51
+ const existing = await stat(join(authDir, 'creds.json')).then(() => true, () => false);
52
+ if (existing && !overwrite) {
53
+ throw new Boom(`"${authDir}" already has a login: pass { overwrite: true } to replace it`, { statusCode: 409 });
54
+ }
55
+ await mkdir(authDir, { recursive: true, mode: 0o700 });
56
+ for (const [name, content] of entries) {
57
+ await writeFile(join(authDir, name), Buffer.from(content, 'base64'), { mode: 0o600 });
58
+ }
59
+ return { authDir, files: entries.length, createdAt: data.createdAt };
60
+ };
61
+ //# sourceMappingURL=session-backup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-backup.js","sourceRoot":"","sources":["../../src/Utils/session-backup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACjC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACvE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAA;AAChC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAEnC,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;AACjC,MAAM,WAAW,GAAG,SAAS,CAAC,MAAM,CAAC,CAAA;AAErC,MAAM,MAAM,GAAG,mBAAmB,CAAA;AAUlC,uGAAuG;AACvG,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,CAAA;AAEhG;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAAE,OAAe,EAAE,IAAY,EAAE,EAAE;IACpE,MAAM,KAAK,GAAG,CAAC,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAA;IAC1E,MAAM,KAAK,GAA2B,EAAE,CAAA;IAExC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;QAChC,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,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IAAI,EAAE,OAAO,CAAC,IAAI,OAAO,EAAE,CAAC;QACvC,MAAM,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAA;IACtF,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAA;AACrE,CAAC,CAAA"}
@@ -0,0 +1,71 @@
1
+ import type { MiscMessageGenerationOptions, WAMessage, WAMessageKey } from '../Types/index.js';
2
+ type PollVotes = Array<{
3
+ name: string;
4
+ voters: string[];
5
+ }>;
6
+ export type TimedPollDeps = {
7
+ sendPoll: (jid: string, name: string, values: string[], poll?: {
8
+ selectableCount?: number;
9
+ }, options?: MiscMessageGenerationOptions) => Promise<WAMessage | undefined>;
10
+ getPollVotes: (pollKey: WAMessageKey | string) => {
11
+ pollName: string;
12
+ votes: PollVotes;
13
+ } | undefined;
14
+ sendMessage: (jid: string, content: any, options?: MiscMessageGenerationOptions) => Promise<unknown>;
15
+ logger?: {
16
+ warn: (...args: any[]) => void;
17
+ };
18
+ /** replaceable for tests */
19
+ setTimer?: (fn: () => void, ms: number) => unknown;
20
+ clearTimer?: (timer: unknown) => void;
21
+ now?: () => number;
22
+ };
23
+ export type TimedPollOptions = {
24
+ /** how long the poll stays open: `'10m'`, `'2h'`, `'1d'`, ms, or the date it closes */
25
+ closeAfter: string | number | Date;
26
+ /** 1 by default */
27
+ selectableCount?: number;
28
+ /** show who voted what in the result. Default true; `false` shows only the counts */
29
+ showVoters?: boolean;
30
+ /** called with the final results when the poll closes */
31
+ onClose?: (result: TimedPollResult) => void | Promise<void>;
32
+ };
33
+ export type TimedPollResult = {
34
+ pollKey: WAMessageKey;
35
+ pollName: string;
36
+ total: number;
37
+ options: Array<{
38
+ name: string;
39
+ votes: number;
40
+ percent: number;
41
+ voters: string[];
42
+ }>;
43
+ /** the option(s) with the most votes (several when tied, none when nobody voted) */
44
+ winners: string[];
45
+ };
46
+ export declare const summarizeVotes: (pollKey: WAMessageKey, pollName: string, votes: PollVotes) => TimedPollResult;
47
+ /** the text sent when a poll closes */
48
+ export declare const formatResult: (result: TimedPollResult, showVoters: boolean) => string;
49
+ /**
50
+ * A poll that closes by itself: at the end time the bot sends the result (with or without names).
51
+ * WhatsApp has no real "closed" state for bots, so votes sent later are simply not counted in the
52
+ * result. The timer lives in memory: if the bot restarts before the end, nothing is sent.
53
+ */
54
+ export declare const makeTimedPolls: (deps: TimedPollDeps) => {
55
+ /** sends the poll and schedules its result. Resolves the sent message, when it closes and `cancel()` */
56
+ sendTimedPoll: (jid: string, name: string, values: string[], { closeAfter, selectableCount, showVoters, onClose }: TimedPollOptions, options?: MiscMessageGenerationOptions) => Promise<{
57
+ message: WAMessage;
58
+ closesAt: Date;
59
+ cancel: () => boolean;
60
+ }>;
61
+ /** polls still waiting to close */
62
+ openPolls: () => {
63
+ id: string;
64
+ jid: string;
65
+ name: string;
66
+ closesAt: Date;
67
+ }[];
68
+ };
69
+ export type TimedPolls = ReturnType<typeof makeTimedPolls>;
70
+ export {};
71
+ //# sourceMappingURL=timed-poll.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timed-poll.d.ts","sourceRoot":"","sources":["../../src/Utils/timed-poll.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,4BAA4B,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAGrF,KAAK,SAAS,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAAA;AAE1D,MAAM,MAAM,aAAa,GAAG;IAC3B,QAAQ,EAAE,CACT,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EAAE,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E,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC,CAAA;IAClF,oFAAoF;IACpF,OAAO,EAAE,MAAM,EAAE,CAAA;CACjB,CAAA;AAQD,eAAO,MAAM,cAAc,GAAI,SAAS,YAAY,EAAE,UAAU,MAAM,EAAE,OAAO,SAAS,KAAG,eAqB1F,CAAA;AAED,uCAAuC;AACvC,eAAO,MAAM,YAAY,GAAI,QAAQ,eAAe,EAAE,YAAY,OAAO,WAcxE,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,aAAa;IAsBhD,wGAAwG;yBAElG,MAAM,QACL,MAAM,UACJ,MAAM,EAAE,wDACiD,gBAAgB,YACvE,4BAA4B;;;;;IA0BvC,mCAAmC;;;;;;;CASpC,CAAA;AAED,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,cAAc,CAAC,CAAA"}
@@ -0,0 +1,101 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { parseDuration } from './scheduler.js';
3
+ /** longest wait of one timer (about 24 days); longer polls are not supported */
4
+ const MAX_MS = 2 ** 31 - 1;
5
+ const MIN_MS = 5000;
6
+ const phone = (jid) => `@${jid.split('@')[0].split(':')[0]}`;
7
+ export const summarizeVotes = (pollKey, pollName, votes) => {
8
+ const unique = (voters) => [...new Set(voters)];
9
+ const options = votes.map(option => ({
10
+ name: option.name,
11
+ voters: unique(option.voters),
12
+ votes: unique(option.voters).length
13
+ }));
14
+ const everyone = new Set(options.flatMap(option => option.voters));
15
+ const total = everyone.size;
16
+ const best = Math.max(0, ...options.map(option => option.votes));
17
+ return {
18
+ pollKey,
19
+ pollName,
20
+ total,
21
+ options: options.map(option => ({
22
+ ...option,
23
+ percent: total ? Math.round((option.votes / total) * 100) : 0
24
+ })),
25
+ winners: best ? options.filter(option => option.votes === best).map(option => option.name) : []
26
+ };
27
+ };
28
+ /** the text sent when a poll closes */
29
+ export const formatResult = (result, showVoters) => {
30
+ const lines = result.options.map(option => {
31
+ const bar = '█'.repeat(Math.round(option.percent / 10)).padEnd(10, '░');
32
+ const voters = showVoters && option.voters.length ? `\n ${option.voters.map(phone).join(' ')}` : '';
33
+ return `▢ *${option.name}*\n ${bar} ${option.votes} (${option.percent}%)${voters}`;
34
+ });
35
+ const verdict = !result.total
36
+ ? 'Nadie votó.'
37
+ : result.winners.length > 1
38
+ ? `🤝 Empate: ${result.winners.join(', ')}`
39
+ : `🏆 Ganó: *${result.winners[0]}*`;
40
+ return `📊 *Encuesta cerrada*\n${result.pollName}\n\n${lines.join('\n\n')}\n\n${verdict}\n👥 ${result.total} voto${result.total === 1 ? '' : 's'}`;
41
+ };
42
+ /**
43
+ * A poll that closes by itself: at the end time the bot sends the result (with or without names).
44
+ * WhatsApp has no real "closed" state for bots, so votes sent later are simply not counted in the
45
+ * result. The timer lives in memory: if the bot restarts before the end, nothing is sent.
46
+ */
47
+ export const makeTimedPolls = (deps) => {
48
+ const setTimer = deps.setTimer || ((fn, ms) => setTimeout(fn, ms));
49
+ const clearTimer = deps.clearTimer || (timer => clearTimeout(timer));
50
+ const now = deps.now || Date.now;
51
+ const open = new Map();
52
+ const close = async (id, showVoters, onClose, message) => {
53
+ const entry = open.get(id);
54
+ if (!entry)
55
+ return;
56
+ open.delete(id);
57
+ try {
58
+ const found = deps.getPollVotes(message.key);
59
+ const result = summarizeVotes(message.key, found?.pollName || entry.name, found?.votes || []);
60
+ await deps.sendMessage(entry.jid, { text: formatResult(result, showVoters) }, { quoted: message });
61
+ await onClose?.(result);
62
+ }
63
+ catch (error) {
64
+ deps.logger?.warn({ error }, 'could not send the result of a timed poll');
65
+ }
66
+ };
67
+ return {
68
+ /** sends the poll and schedules its result. Resolves the sent message, when it closes and `cancel()` */
69
+ sendTimedPoll: async (jid, name, values, { closeAfter, selectableCount = 1, showVoters = true, onClose }, options) => {
70
+ const ms = closeAfter instanceof Date ? closeAfter.getTime() - now() : parseDuration(closeAfter);
71
+ if (!Number.isFinite(ms) || ms < MIN_MS || ms > MAX_MS) {
72
+ throw new Boom('closeAfter must be between 5 seconds and 24 days', { statusCode: 400 });
73
+ }
74
+ const message = await deps.sendPoll(jid, name, values, { selectableCount }, options);
75
+ if (!message?.key?.id)
76
+ throw new Boom('WhatsApp did not accept the poll', { statusCode: 500 });
77
+ const id = message.key.id;
78
+ const timer = setTimer(() => void close(id, showVoters, onClose, message), ms);
79
+ timer?.unref?.();
80
+ open.set(id, { jid, name, closesAt: now() + ms, timer });
81
+ return {
82
+ message,
83
+ closesAt: new Date(now() + ms),
84
+ cancel: () => {
85
+ const entry = open.get(id);
86
+ if (entry)
87
+ clearTimer(entry.timer);
88
+ return open.delete(id);
89
+ }
90
+ };
91
+ },
92
+ /** polls still waiting to close */
93
+ openPolls: () => [...open.entries()].map(([id, entry]) => ({
94
+ id,
95
+ jid: entry.jid,
96
+ name: entry.name,
97
+ closesAt: new Date(entry.closesAt)
98
+ }))
99
+ };
100
+ };
101
+ //# sourceMappingURL=timed-poll.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timed-poll.js","sourceRoot":"","sources":["../../src/Utils/timed-poll.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAEjC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAyC3C,gFAAgF;AAChF,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;AAC1B,MAAM,MAAM,GAAG,IAAK,CAAA;AAEpB,MAAM,KAAK,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;AAErE,MAAM,CAAC,MAAM,cAAc,GAAG,CAA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