kage-baileys 25.0.6 → 25.0.8

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.
@@ -5,9 +5,11 @@ const Defaults_1 = require("../Defaults");
5
5
  const business_1 = require("./communities");
6
6
 
7
7
  /**
8
- * makeWASocket – versión 25.0.3
9
- * - Sin wrappers __kageModule corruptos
10
- * - MessageBuilder sin tocar objetos no extensibles (bound functions)
8
+ * makeWASocket – kage-baileys 25.0.10-compat
9
+ * - MessageBuilder seguro (objetos no extensibles)
10
+ * - AIRich integrado (sin lib externa)
11
+ * - Media: base64 / Buffer / URL / path + jimp/sharp opcional
12
+ * - Relay optimizado para pintar mensajes al instante (sin salir del chat)
11
13
  */
12
14
  const makeWASocket = (config = {}) => {
13
15
  try {
@@ -25,14 +27,37 @@ const makeWASocket = (config = {}) => {
25
27
  finalConfig.shouldSyncHistoryMessage = () => !!finalConfig.syncFullHistory;
26
28
  }
27
29
 
28
- const socket = (0, business_1.makeCommunitiesSocket)(finalConfig);
30
+ const origDefineProperty = Object.defineProperty;
31
+ let definePatched = false;
32
+ try {
33
+ Object.defineProperty = function (obj, prop, desc) {
34
+ try {
35
+ if (prop === 'MessageBuilder' && typeof obj === 'function' && !Object.isExtensible(obj)) {
36
+ return obj;
37
+ }
38
+ return origDefineProperty(obj, prop, desc);
39
+ } catch (e) {
40
+ if (prop === 'MessageBuilder') return obj;
41
+ throw e;
42
+ }
43
+ };
44
+ definePatched = true;
45
+ } catch (_) {}
46
+
47
+ let socket;
48
+ try {
49
+ socket = (0, business_1.makeCommunitiesSocket)(finalConfig);
50
+ } finally {
51
+ if (definePatched) {
52
+ Object.defineProperty = origDefineProperty;
53
+ }
54
+ }
29
55
 
30
56
  try { require('../Extensions').installExtensions(socket, finalConfig); } catch (_) {}
31
57
  try { require('../Utils/interactive-compat').installKageInteractiveTools(socket); } catch (_) {}
32
58
  try { require('../Utils/profile-tools').installProfileTools(socket, config); } catch (_) {}
33
59
 
34
60
  // ---- MessageBuilder (seguro) ----
35
- // Nunca hacemos: boundFn.MessageBuilder = ... (bound functions no son extensibles)
36
61
  try {
37
62
  const { MessageBuilder } = require('../Utils/message-builder');
38
63
  let moddedFn = null;
@@ -41,7 +66,6 @@ const makeWASocket = (config = {}) => {
41
66
  moddedFn = typeof mod === 'function' ? mod : (mod && mod.default);
42
67
  } catch (_) {}
43
68
 
44
- // Función usable: messageBuilder(...)
45
69
  const builderFn = function (...args) {
46
70
  if (typeof moddedFn === 'function') {
47
71
  try { return moddedFn.apply(socket, args); } catch (_) {}
@@ -49,16 +73,138 @@ const makeWASocket = (config = {}) => {
49
73
  return new MessageBuilder(socket, ...args);
50
74
  };
51
75
 
52
- // Objeto extensible que también es invocable
53
76
  const mb = Object.assign(builderFn, {
54
- MessageBuilder, // clase disponible sin romper extensibility
55
- create: () => new MessageBuilder(socket)
77
+ MessageBuilder,
78
+ create: () => new MessageBuilder(socket),
79
+ VERSION: '4.9-instant'
56
80
  });
57
81
 
58
- socket.messageBuilder = mb;
59
- socket.createMessageBuilder = () => new MessageBuilder(socket);
60
- socket.MessageBuilder = MessageBuilder;
61
- } catch (_) {}
82
+ try { socket.messageBuilder = mb; } catch (_) {
83
+ try {
84
+ Object.defineProperty(socket, 'messageBuilder', { value: mb, writable: true, configurable: true, enumerable: true });
85
+ } catch (_) {}
86
+ }
87
+ try { socket.createMessageBuilder = () => new MessageBuilder(socket); } catch (_) {}
88
+ try { socket.MessageBuilder = MessageBuilder; } catch (_) {
89
+ try {
90
+ Object.defineProperty(socket, 'MessageBuilder', { value: MessageBuilder, writable: true, configurable: true, enumerable: true });
91
+ } catch (_) {}
92
+ }
93
+ } catch (e) {
94
+ if (config && config.logger) {
95
+ try { config.logger.warn?.({ err: e }, 'MessageBuilder attach failed (non-fatal)'); } catch (_) {}
96
+ }
97
+ }
98
+
99
+ // ---- AIRich + media integrados (estilo zapo, nativo kage) ----
100
+ try {
101
+ const { KageAIRich, AIRich, createAIRich } = require('../Utils/kage-airich');
102
+ const media = require('../Utils/kage-media-resolve');
103
+
104
+ const attach = (key, value) => {
105
+ try {
106
+ socket[key] = value;
107
+ } catch (_) {
108
+ try {
109
+ Object.defineProperty(socket, key, {
110
+ value,
111
+ writable: true,
112
+ configurable: true,
113
+ enumerable: true
114
+ });
115
+ } catch (_) {}
116
+ }
117
+ };
118
+
119
+ attach('AIRich', AIRich);
120
+ attach('KageAIRich', KageAIRich);
121
+ attach('createAIRich', () => createAIRich(socket));
122
+ attach('airich', () => createAIRich(socket));
123
+ attach('resolveMedia', (src, opts) => media.toBuffer(src, opts));
124
+ attach('resolveRichImage', (src, opts) => media.resolveRichImage(socket, src, opts));
125
+ attach('resolvePublicImageUrl', (src, opts) => media.resolvePublicImageUrl(socket, src, opts));
126
+ attach('resolveImageForSend', (src, opts) => media.resolveImageForSend(socket, src, opts));
127
+ attach('DEFAULT_IMAGE', media.DEFAULT_IMAGE);
128
+ attach('toBuffer', (src, opts) => media.toBuffer(src, opts));
129
+ try { require('../Utils/kage-send-table').installSendTable(socket); } catch (_) {}
130
+ try { require('../Utils/kage-rich-methods').installRichMethods(socket); } catch (_) {}
131
+
132
+
133
+ // sendMessage: acepta base64, data-URI, path, Buffer en image/video/audio/document/sticker
134
+ const origSend = socket.sendMessage?.bind(socket);
135
+ if (typeof origSend === 'function') {
136
+ const normalizeField = async (val) => {
137
+ if (val == null) return val;
138
+ if (Buffer.isBuffer(val) || val instanceof Uint8Array) return Buffer.from(val);
139
+ if (typeof val === 'string') {
140
+ // URL http: Baileys descarga solo; base64/data-URI/path → Buffer
141
+ if (/^https?:\/\//i.test(val)) return { url: val };
142
+ const buf = await media.toBuffer(val);
143
+ return buf || val;
144
+ }
145
+ if (typeof val === 'object') {
146
+ if (val.url || val.stream) return val;
147
+ if (val.base64) {
148
+ const buf = await media.toBuffer(val.base64);
149
+ return buf || val;
150
+ }
151
+ }
152
+ return val;
153
+ };
154
+ socket.sendMessage = async (jid, content, options = {}) => {
155
+ try {
156
+ if (content && typeof content === 'object') {
157
+ for (const key of ['image', 'video', 'audio', 'document', 'sticker']) {
158
+ if (content[key] != null) {
159
+ content = { ...content, [key]: await normalizeField(content[key]) };
160
+ }
161
+ }
162
+ }
163
+ } catch (_) {}
164
+ return origSend(jid, content, options);
165
+ };
166
+ }
167
+
168
+ // Helpers directos en sock
169
+ attach('toBuffer', (src, opts) => media.toBuffer(src, opts));
170
+ attach('uploadPublicImage', async (src, opts) => {
171
+ const buf = await media.toBuffer(src, opts);
172
+ if (!buf) return media.DEFAULT_IMAGE;
173
+ const resized = await media.maybeResize(buf, opts);
174
+ return media.DEFAULT_IMAGE;
175
+ });
176
+ attach('prepareImage', (src, opts) => media.resolveImageForSend(socket, src, opts));
177
+
178
+ // relayMessage: asegurar options que ayudan a pintar al instante
179
+ const origRelay = socket.relayMessage?.bind(socket);
180
+ if (typeof origRelay === 'function') {
181
+ socket.relayMessage = async (jid, message, options = {}) => {
182
+ const opts = {
183
+ ...options,
184
+ // no retrasar por ack de historial
185
+ ...(options.status === undefined ? {} : { status: options.status }),
186
+ };
187
+ // messageSecret en rich ayuda a algunos clientes a renderizar sin reabrir
188
+ try {
189
+ if (message?.botForwardedMessage && !message.messageContextInfo) {
190
+ message = {
191
+ messageContextInfo: {
192
+ deviceListMetadata: {},
193
+ deviceListMetadataVersion: 2,
194
+ messageSecret: require('crypto').randomBytes(32),
195
+ },
196
+ ...message,
197
+ };
198
+ }
199
+ } catch (_) {}
200
+ return origRelay(jid, message, opts);
201
+ };
202
+ }
203
+ } catch (e) {
204
+ if (config && config.logger) {
205
+ try { config.logger.warn?.({ err: e }, 'AIRich/media attach failed (non-fatal)'); } catch (_) {}
206
+ }
207
+ }
62
208
 
63
209
  try {
64
210
  return require('../Utils/automation-tools').installKageTools(socket, config.kageTools || {});
@@ -0,0 +1,398 @@
1
+ /**
2
+ * Kage AIRich — rich messages nativos desde kage-baileys
3
+ * - Un solo relay (contenido completo) → se ve al instante sin salir del chat
4
+ * - Imágenes product con URL pública (evita blanco)
5
+ * - Sin dependencia externa de chiaki-builder / zapo
6
+ */
7
+ 'use strict';
8
+
9
+ const crypto = require('crypto');
10
+ const messages = require('./messages.js');
11
+ const generics = require('./generics.js');
12
+ const { resolvePublicImageUrl, resolveRichImage, DEFAULT_IMAGE } = require('./kage-media-resolve.js');
13
+
14
+ let genFromContent = messages.generateWAMessageFromContent;
15
+ let genId = generics.generateMessageIDV2 || messages.generateMessageIDV2;
16
+ if (typeof genId !== 'function') {
17
+ genId = () => crypto.randomBytes(8).toString('hex').toUpperCase();
18
+ }
19
+
20
+ const TN = {
21
+ TEXT: 'GenAIMarkdownTextUXPrimitive',
22
+ PRODUCT: 'GenAIProductUXPrimitive',
23
+ METADATA: 'GenAIMarkdownMetadataTextUXPrimitive',
24
+ FOOTER_ACTION: 'GenAIFooterActionUXPrimitive',
25
+ SUGGEST: 'GenAISuggestionPillUXPrimitive',
26
+ TABLE: 'GenAITableUXPrimitive',
27
+ HTML: 'GenAIaeacdsnwHtmlPrimitive',
28
+ };
29
+
30
+ function layout(name, data) {
31
+ if (Array.isArray(data)) {
32
+ return {
33
+ view_model: {
34
+ primitives: data,
35
+ __typename: `GenAI${name}LayoutViewModel`,
36
+ },
37
+ };
38
+ }
39
+ return {
40
+ view_model: {
41
+ primitive: data,
42
+ __typename: `GenAI${name}LayoutViewModel`,
43
+ },
44
+ };
45
+ }
46
+
47
+ function stringifyEscaped(obj) {
48
+ return JSON.stringify(obj).replace(
49
+ /[\u007f-\uffff]/g,
50
+ (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')
51
+ );
52
+ }
53
+
54
+ class KageAIRich {
55
+ constructor(sock) {
56
+ if (!sock || typeof sock.relayMessage !== 'function') {
57
+ throw new TypeError('KageAIRich requiere un socket Baileys con relayMessage');
58
+ }
59
+ this.sock = sock;
60
+ this._title = '';
61
+ this._footer = '';
62
+ this._sections = [];
63
+ this._submessages = [];
64
+ this._contextInfo = {};
65
+ this._lastKey = null;
66
+ }
67
+
68
+ setTitle(t) {
69
+ this._title = String(t || '');
70
+ return this;
71
+ }
72
+
73
+ setFooter(t) {
74
+ this._footer = String(t || '');
75
+ return this;
76
+ }
77
+
78
+ setContextInfo(ci) {
79
+ if (ci && typeof ci === 'object') this._contextInfo = { ...this._contextInfo, ...ci };
80
+ return this;
81
+ }
82
+
83
+ addText(text) {
84
+ const t = String(text ?? '');
85
+ this._sections.push(
86
+ layout('Single', { text: t, __typename: TN.TEXT })
87
+ );
88
+ this._submessages.push({ messageType: 2, messageText: t });
89
+ return this;
90
+ }
91
+
92
+ addTable(rows) {
93
+ if (!Array.isArray(rows)) throw new TypeError('Table must be array');
94
+ // Formato simple: filas de celdas string
95
+ const cells = rows.map((r) =>
96
+ (Array.isArray(r) ? r : [r]).map((c) => String(c ?? ''))
97
+ );
98
+ this._sections.push(
99
+ layout('Single', {
100
+ __typename: TN.TABLE,
101
+ rows: cells,
102
+ table: cells,
103
+ })
104
+ );
105
+ this._submessages.push({
106
+ messageType: 2,
107
+ messageText: cells.map((r) => r.join(' | ')).join('\n'),
108
+ });
109
+ return this;
110
+ }
111
+
112
+ /**
113
+ * Product cards — image debe ser URL http pública (no pps.whatsapp.net)
114
+ * Acepta string URL, o se normaliza con resolvePublicImageUrl en send()
115
+ */
116
+ addProduct(data) {
117
+ const items = Array.isArray(data) ? data : [data];
118
+ this._pendingProducts = this._pendingProducts || [];
119
+ this._pendingProducts.push(...items);
120
+ return this;
121
+ }
122
+
123
+ addSuggest(prompts) {
124
+ const list = Array.isArray(prompts) ? prompts : [prompts];
125
+ this._sections.push(
126
+ layout(
127
+ 'HScroll',
128
+ list.map((p) => ({
129
+ prompt_text: String(p),
130
+ category: 'ADD',
131
+ __typename: TN.SUGGEST,
132
+ }))
133
+ )
134
+ );
135
+ return this;
136
+ }
137
+
138
+ addFooterAction({ text, url, cta_text, cta_url } = {}) {
139
+ this._sections.push(
140
+ layout('Single', {
141
+ __typename: TN.FOOTER_ACTION,
142
+ cta_text: text || cta_text || 'Open',
143
+ cta_type: 'GENERATE_IMAGE',
144
+ cta_url: url || cta_url || '',
145
+ })
146
+ );
147
+ return this;
148
+ }
149
+
150
+ addMetadata(text) {
151
+ this._sections.push(
152
+ layout('Single', { text: String(text || ''), __typename: TN.METADATA })
153
+ );
154
+ this._submessages.push({ messageType: 2, messageText: String(text || '') });
155
+ return this;
156
+ }
157
+
158
+ /** HTML interactivo (juegos) */
159
+ addHtml(html, { title = 'Chiaki', url = 'https://chiaki.dev' } = {}) {
160
+ this._htmlPayload = { html: String(html || ''), title, url };
161
+ return this;
162
+ }
163
+
164
+ async #resolveProducts() {
165
+ if (!this._pendingProducts?.length) return;
166
+ const products = [];
167
+ for (const item of this._pendingProducts) {
168
+ const rawImg = item.image_url ?? item.image ?? DEFAULT_IMAGE;
169
+ let imgUrl = DEFAULT_IMAGE;
170
+ let thumb = null;
171
+ try {
172
+ const resolved = await resolveRichImage(this.sock, rawImg, { width: 640, height: 640 });
173
+ imgUrl = resolved.url || DEFAULT_IMAGE;
174
+ thumb = resolved.thumbBase64;
175
+ } catch {
176
+ try {
177
+ imgUrl = await resolvePublicImageUrl(this.sock, rawImg);
178
+ } catch {
179
+ imgUrl = DEFAULT_IMAGE;
180
+ }
181
+ }
182
+
183
+ const imageObj = { url: imgUrl || DEFAULT_IMAGE };
184
+ if (thumb) {
185
+ imageObj.thumbnail = thumb;
186
+ imageObj.jpegThumbnail = thumb;
187
+ }
188
+
189
+ products.push({
190
+ title: item.title || 'Item',
191
+ brand: item.brand || '',
192
+ price: item.price || '',
193
+ sale_price: item.sale_price || item.salePrice || '',
194
+ product_url: item.product_url ?? item.url ?? '',
195
+ image: imageObj,
196
+ additional_images: [],
197
+ __typename: TN.PRODUCT,
198
+ });
199
+ }
200
+ this._sections.unshift(
201
+ layout(products.length > 1 ? 'HScroll' : 'Single', products.length > 1 ? products : products[0])
202
+ );
203
+ this._pendingProducts = [];
204
+ }
205
+
206
+ async build(jid, { quoted } = {}) {
207
+ await this.#resolveProducts();
208
+
209
+ let sections = [...this._sections];
210
+ let submessages = [...this._submessages];
211
+
212
+ // HTML game payload
213
+ if (this._htmlPayload?.html) {
214
+ const { html, title, url } = this._htmlPayload;
215
+ const responseId = `kage_${Date.now()}_${crypto.randomBytes(3).toString('hex')}`;
216
+ const payload = {
217
+ response_id: responseId,
218
+ sections: [
219
+ {
220
+ __typename: 'GenAIUnifiedResponseSection',
221
+ view_model: {
222
+ __typename: 'GenAISingleLayoutViewModel',
223
+ primitive: {
224
+ __typename: 'GenAIBotProgressStatusPrimitive',
225
+ title,
226
+ is_in_progress: true,
227
+ },
228
+ },
229
+ },
230
+ ],
231
+ embedded_screens: [
232
+ {
233
+ title,
234
+ content: [
235
+ {
236
+ __typename: 'FOAIDNixelButtonSheets',
237
+ tabs: [
238
+ {
239
+ id: 'tab_0',
240
+ tab_header: String(title).slice(0, 24),
241
+ sections: [
242
+ {
243
+ __typename: 'GenAIUnifiedResponseSection',
244
+ view_model: {
245
+ __typename: 'GenAISingleLayoutViewModel',
246
+ primitive: {
247
+ __typename: TN.HTML,
248
+ payload: html,
249
+ url: url || 'https://chiaki.dev',
250
+ trusted_sources: ['chiaki.dev'],
251
+ },
252
+ },
253
+ },
254
+ ],
255
+ },
256
+ ],
257
+ },
258
+ ],
259
+ step_entries: [],
260
+ },
261
+ ],
262
+ };
263
+
264
+ const contextInfo = {
265
+ forwardingScore: 1,
266
+ isForwarded: true,
267
+ forwardedAiBotMessageInfo: { botJid: '0@bot' },
268
+ forwardOrigin: 4,
269
+ ...this._contextInfo,
270
+ };
271
+ if (quoted?.key) {
272
+ contextInfo.stanzaId = quoted.key.id;
273
+ contextInfo.participant =
274
+ quoted.key.participant || quoted.participant || quoted.key.remoteJid;
275
+ contextInfo.quotedMessage = quoted.message;
276
+ }
277
+
278
+ return {
279
+ message: {
280
+ messageContextInfo: {
281
+ deviceListMetadata: {},
282
+ deviceListMetadataVersion: 2,
283
+ messageSecret: crypto.randomBytes(32),
284
+ botMetadata: {
285
+ messageDisclaimerText: title || this._title,
286
+ botResponseId: responseId,
287
+ },
288
+ },
289
+ botForwardedMessage: {
290
+ message: {
291
+ richResponseMessage: {
292
+ messageType: 1,
293
+ unifiedResponse: {
294
+ data: Buffer.from(JSON.stringify(payload)).toString('base64'),
295
+ },
296
+ contextInfo,
297
+ },
298
+ },
299
+ },
300
+ },
301
+ key: { remoteJid: jid, fromMe: true, id: genId() },
302
+ };
303
+ }
304
+
305
+ if (this._footer) {
306
+ sections.push(layout('Single', { text: this._footer, __typename: TN.TEXT }));
307
+ }
308
+
309
+ const responseId = crypto.randomUUID();
310
+ const botResponseId = crypto.randomUUID();
311
+
312
+ const contextInfo = {
313
+ forwardingScore: 1,
314
+ isForwarded: true,
315
+ forwardedAiBotMessageInfo: { botJid: '0@bot' },
316
+ forwardOrigin: 4,
317
+ ...this._contextInfo,
318
+ };
319
+ if (quoted?.key) {
320
+ contextInfo.stanzaId = quoted.key.id;
321
+ contextInfo.participant =
322
+ quoted.key.participant || quoted.participant || quoted.key.remoteJid;
323
+ contextInfo.quotedMessage = quoted.message;
324
+ }
325
+
326
+ const content = {
327
+ messageContextInfo: {
328
+ deviceListMetadata: {},
329
+ deviceListMetadataVersion: 2,
330
+ messageSecret: crypto.randomBytes(32),
331
+ botMetadata: {
332
+ messageDisclaimerText: this._title || '',
333
+ botResponseId,
334
+ },
335
+ },
336
+ botForwardedMessage: {
337
+ message: {
338
+ richResponseMessage: {
339
+ messageType: 1,
340
+ submessages,
341
+ unifiedResponse: {
342
+ data: Buffer.from(
343
+ stringifyEscaped({ response_id: responseId, sections })
344
+ ).toString('base64'),
345
+ },
346
+ contextInfo,
347
+ },
348
+ },
349
+ },
350
+ };
351
+
352
+ const messageId = genId();
353
+ if (typeof genFromContent === 'function') {
354
+ try {
355
+ const msg = genFromContent(jid, content, { messageId });
356
+ return msg;
357
+ } catch {}
358
+ }
359
+ return {
360
+ message: content,
361
+ key: { remoteJid: jid, fromMe: true, id: messageId },
362
+ };
363
+ }
364
+
365
+ /**
366
+ * Envío único — contenido completo de una vez (se ve al instante, sin reabrir chat)
367
+ * NO hace sendEdit (evita warning de seguridad y retrasos)
368
+ */
369
+ async send(jid, options = {}) {
370
+ const { quoted, mentions, additionalNodes = [] } = options;
371
+ if (mentions?.length) {
372
+ this._contextInfo.mentionedJid = mentions;
373
+ }
374
+ const msg = await this.build(jid, { quoted });
375
+ const messageId = msg.key?.id || genId();
376
+
377
+ await this.sock.relayMessage(jid, msg.message, {
378
+ messageId,
379
+ additionalNodes,
380
+ // ayuda a que el cliente pinte el mensaje de inmediato
381
+ status: 1,
382
+ });
383
+
384
+ this._lastKey = { remoteJid: jid, fromMe: true, id: messageId };
385
+ return { key: this._lastKey, message: msg.message };
386
+ }
387
+ }
388
+
389
+ function createAIRich(sock) {
390
+ return new KageAIRich(sock);
391
+ }
392
+
393
+ module.exports = {
394
+ KageAIRich,
395
+ AIRich: KageAIRich,
396
+ createAIRich,
397
+ DEFAULT_IMAGE,
398
+ };