@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,649 @@
1
+ import { promisify } from 'node:util'
2
+ import { inflate } from 'node:zlib'
3
+ import { randomBytes } from 'node:crypto'
4
+ import { Boom } from '../foundation/boom.js'
5
+ import * as constants from './wa-binary-constants.js'
6
+
7
+ /* ------------------------------------------------------------------ */
8
+ /* JID utilities */
9
+ /* ------------------------------------------------------------------ */
10
+
11
+ export const S_WHATSAPP_NET = '@s.whatsapp.net'
12
+ export const OFFICIAL_BIZ_JID = '16505361212@c.us'
13
+ export const SERVER_JID = 'server@c.us'
14
+ export const PSA_WID = '0@c.us'
15
+ export const STORIES_JID = 'status@broadcast'
16
+ export const META_AI_JID = '13135550002@c.us'
17
+
18
+ export const WAJIDDomains = {
19
+ WHATSAPP: 0,
20
+ LID: 1,
21
+ HOSTED: 128,
22
+ HOSTED_LID: 129
23
+ }
24
+
25
+ export const getServerFromDomainType = (initialServer, domainType) => {
26
+ switch (domainType) {
27
+ case WAJIDDomains.LID:
28
+ return 'lid'
29
+ case WAJIDDomains.HOSTED:
30
+ return 'hosted'
31
+ case WAJIDDomains.HOSTED_LID:
32
+ return 'hosted.lid'
33
+ case WAJIDDomains.WHATSAPP:
34
+ default:
35
+ return initialServer
36
+ }
37
+ }
38
+
39
+ export const jidEncode = (user, server, device, agent) =>
40
+ `${user || ''}${agent ? `_${agent}` : ''}${device ? `:${device}` : ''}@${server || 'lid'}`
41
+
42
+ export const jidDecode = jid => {
43
+ const sepIdx = typeof jid === 'string' ? jid.indexOf('@') : -1
44
+ if (sepIdx < 0) return undefined
45
+
46
+ const server = jid.slice(sepIdx + 1)
47
+ const userCombined = jid.slice(0, sepIdx)
48
+ const [userAgent, device] = userCombined.split(':')
49
+ const [user, agent] = userAgent.split('_')
50
+
51
+ let domainType = WAJIDDomains.WHATSAPP
52
+ if (server === 'lid') domainType = WAJIDDomains.LID
53
+ else if (server === 'hosted') domainType = WAJIDDomains.HOSTED
54
+ else if (server === 'hosted.lid') domainType = WAJIDDomains.HOSTED_LID
55
+ else if (agent) domainType = parseInt(agent)
56
+
57
+ return { server, user, domainType, device: device ? +device : undefined }
58
+ }
59
+
60
+ export const areJidsSameUser = (jid1, jid2) => jidDecode(jid1)?.user === jidDecode(jid2)?.user
61
+ export const isJidMetaAI = jid => jid?.endsWith('@bot')
62
+ export const isPnUser = jid => jid?.endsWith('@s.whatsapp.net')
63
+ export const isLidUser = jid => jid?.endsWith('@lid')
64
+ export const isJidBroadcast = jid => jid?.endsWith('@broadcast')
65
+ export const isJidGroup = jid => jid?.endsWith('@g.us')
66
+ export const isJidStatusBroadcast = jid => jid === 'status@broadcast'
67
+ export const isJidNewsletter = jid => jid?.endsWith('@newsletter')
68
+ export const isHostedPnUser = jid => jid?.endsWith('@hosted')
69
+ export const isHostedLidUser = jid => jid?.endsWith('@hosted.lid')
70
+
71
+ const BOT_JID_RE = /^1313555\d{4}$|^131655500\d{2}$/
72
+ export const isJidBot = jid => jid && BOT_JID_RE.test(jid.split('@')[0]) && jid.endsWith('@c.us')
73
+
74
+ export const jidNormalizedUser = jid => {
75
+ const result = jidDecode(jid)
76
+ if (!result) return ''
77
+ const { user, server } = result
78
+ return jidEncode(user, server === 'c.us' ? 's.whatsapp.net' : server)
79
+ }
80
+
81
+ export const transferDevice = (fromJid, toJid) => {
82
+ const fromDecoded = jidDecode(fromJid)
83
+ const deviceId = fromDecoded?.device || 0
84
+ const { server, user } = jidDecode(toJid)
85
+ return jidEncode(user, server, deviceId)
86
+ }
87
+
88
+ /* ------------------------------------------------------------------ */
89
+ /* Binary node encode */
90
+ /* ------------------------------------------------------------------ */
91
+
92
+ export const encodeBinaryNode = (node, opts = constants, buffer = [0]) => {
93
+ const encoded = encodeBinaryNodeInner(node, opts, buffer)
94
+ return Buffer.from(encoded)
95
+ }
96
+
97
+ const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
98
+ const { TAGS, TOKEN_MAP } = opts
99
+
100
+ const pushByte = value => buffer.push(value & 0xff)
101
+ const pushInt = (value, n, littleEndian = false) => {
102
+ for (let i = 0; i < n; i++) {
103
+ const curShift = littleEndian ? i : n - 1 - i
104
+ buffer.push((value >> (curShift * 8)) & 0xff)
105
+ }
106
+ }
107
+ const pushBytes = bytes => {
108
+ for (const b of bytes) buffer.push(b)
109
+ }
110
+ const pushInt16 = value => pushBytes([(value >> 8) & 0xff, value & 0xff])
111
+ const pushInt20 = value => pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
112
+
113
+ const writeByteLength = length => {
114
+ if (length >= 4294967296) throw new Error('string too large to encode: ' + length)
115
+ if (length >= 1 << 20) {
116
+ pushByte(TAGS.BINARY_32)
117
+ pushInt(length, 4)
118
+ } else if (length >= 256) {
119
+ pushByte(TAGS.BINARY_20)
120
+ pushInt20(length)
121
+ } else {
122
+ pushByte(TAGS.BINARY_8)
123
+ pushByte(length)
124
+ }
125
+ }
126
+
127
+ const writeStringRaw = str => {
128
+ const bytes = Buffer.from(str, 'utf-8')
129
+ writeByteLength(bytes.length)
130
+ pushBytes(bytes)
131
+ }
132
+
133
+ const writeJid = ({ domainType, device, user, server }) => {
134
+ if (typeof device !== 'undefined') {
135
+ pushByte(TAGS.AD_JID)
136
+ pushByte(domainType || 0)
137
+ pushByte(device || 0)
138
+ writeString(user)
139
+ } else {
140
+ pushByte(TAGS.JID_PAIR)
141
+ if (user.length) writeString(user)
142
+ else pushByte(TAGS.LIST_EMPTY)
143
+ writeString(server)
144
+ }
145
+ }
146
+
147
+ const packNibble = char => {
148
+ switch (char) {
149
+ case '-':
150
+ return 10
151
+ case '.':
152
+ return 11
153
+ case '\0':
154
+ return 15
155
+ default:
156
+ if (char >= '0' && char <= '9') return char.charCodeAt(0) - '0'.charCodeAt(0)
157
+ throw new Error(`invalid byte for nibble "${char}"`)
158
+ }
159
+ }
160
+
161
+ const packHex = char => {
162
+ if (char >= '0' && char <= '9') return char.charCodeAt(0) - '0'.charCodeAt(0)
163
+ if (char >= 'A' && char <= 'F') return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0)
164
+ if (char >= 'a' && char <= 'f') return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
165
+ if (char === '\0') return 15
166
+ throw new Error(`Invalid hex char "${char}"`)
167
+ }
168
+
169
+ const writePackedBytes = (str, type) => {
170
+ if (str.length > TAGS.PACKED_MAX) throw new Error('Too many bytes to pack')
171
+ pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
172
+ let roundedLength = Math.ceil(str.length / 2.0)
173
+ if (str.length % 2 !== 0) roundedLength |= 128
174
+ pushByte(roundedLength)
175
+ const packFunction = type === 'nibble' ? packNibble : packHex
176
+ const packBytePair = (v1, v2) => (packFunction(v1) << 4) | packFunction(v2)
177
+ const strLengthHalf = Math.floor(str.length / 2)
178
+ for (let i = 0; i < strLengthHalf; i++) pushByte(packBytePair(str[2 * i], str[2 * i + 1]))
179
+ if (str.length % 2 !== 0) pushByte(packBytePair(str[str.length - 1], '\x00'))
180
+ }
181
+
182
+ const isNibble = str => {
183
+ if (!str || str.length > TAGS.PACKED_MAX) return false
184
+ for (const char of str) {
185
+ const isInNibbleRange = char >= '0' && char <= '9'
186
+ if (!isInNibbleRange && char !== '-' && char !== '.') return false
187
+ }
188
+ return true
189
+ }
190
+
191
+ const isHex = str => {
192
+ if (!str || str.length > TAGS.PACKED_MAX) return false
193
+ for (const char of str) {
194
+ const isInNibbleRange = char >= '0' && char <= '9'
195
+ if (!isInNibbleRange && !(char >= 'A' && char <= 'F')) return false
196
+ }
197
+ return true
198
+ }
199
+
200
+ const writeString = str => {
201
+ if (str === undefined || str === null) {
202
+ pushByte(TAGS.LIST_EMPTY)
203
+ return
204
+ }
205
+ if (str === '') {
206
+ writeStringRaw(str)
207
+ return
208
+ }
209
+ const tokenIndex = TOKEN_MAP[str]
210
+ if (tokenIndex) {
211
+ if (typeof tokenIndex.dict === 'number') pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
212
+ pushByte(tokenIndex.index)
213
+ } else if (isNibble(str)) {
214
+ writePackedBytes(str, 'nibble')
215
+ } else if (isHex(str)) {
216
+ writePackedBytes(str, 'hex')
217
+ } else {
218
+ const decodedJid = jidDecode(str)
219
+ if (decodedJid) writeJid(decodedJid)
220
+ else writeStringRaw(str)
221
+ }
222
+ }
223
+
224
+ const writeListStart = listSize => {
225
+ if (listSize === 0) pushByte(TAGS.LIST_EMPTY)
226
+ else if (listSize < 256) pushBytes([TAGS.LIST_8, listSize])
227
+ else {
228
+ pushByte(TAGS.LIST_16)
229
+ pushInt16(listSize)
230
+ }
231
+ }
232
+
233
+ if (!tag) throw new Error('Invalid node: tag cannot be undefined')
234
+
235
+ const validAttributes = Object.keys(attrs || {}).filter(k => typeof attrs[k] !== 'undefined' && attrs[k] !== null)
236
+ writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
237
+ writeString(tag)
238
+ for (const key of validAttributes) {
239
+ if (typeof attrs[key] === 'string') {
240
+ writeString(key)
241
+ writeString(attrs[key])
242
+ }
243
+ }
244
+
245
+ if (typeof content === 'string') {
246
+ writeString(content)
247
+ } else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
248
+ writeByteLength(content.length)
249
+ pushBytes(content)
250
+ } else if (Array.isArray(content)) {
251
+ const validContent = content.filter(
252
+ item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string')
253
+ )
254
+ writeListStart(validContent.length)
255
+ for (const item of validContent) encodeBinaryNodeInner(item, opts, buffer)
256
+ } else if (typeof content === 'undefined') {
257
+ // no children
258
+ } else {
259
+ throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
260
+ }
261
+
262
+ return buffer
263
+ }
264
+
265
+ /* ------------------------------------------------------------------ */
266
+ /* Binary node decode */
267
+ /* ------------------------------------------------------------------ */
268
+
269
+ const inflatePromise = promisify(inflate)
270
+
271
+ export const decompressingIfRequired = async buffer => {
272
+ if (2 & buffer.readUInt8()) {
273
+ buffer = await inflatePromise(buffer.slice(1))
274
+ } else {
275
+ buffer = buffer.slice(1) // uncompressed nodes have a 0x00 prefix, strip it
276
+ }
277
+ return buffer
278
+ }
279
+
280
+ export const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) => {
281
+ const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
282
+
283
+ const checkEOS = length => {
284
+ if (indexRef.index + length > buffer.length) throw new Error('end of stream')
285
+ }
286
+ const next = () => {
287
+ const value = buffer[indexRef.index]
288
+ indexRef.index += 1
289
+ return value
290
+ }
291
+ const readByte = () => {
292
+ checkEOS(1)
293
+ return next()
294
+ }
295
+ const readBytes = n => {
296
+ checkEOS(n)
297
+ const value = buffer.slice(indexRef.index, indexRef.index + n)
298
+ indexRef.index += n
299
+ return value
300
+ }
301
+ const readStringFromChars = length => readBytes(length).toString('utf-8')
302
+ const readInt = (n, littleEndian = false) => {
303
+ checkEOS(n)
304
+ let val = 0
305
+ for (let i = 0; i < n; i++) {
306
+ const shift = littleEndian ? i : n - 1 - i
307
+ val |= next() << (shift * 8)
308
+ }
309
+ return val
310
+ }
311
+ const readInt20 = () => {
312
+ checkEOS(3)
313
+ return ((next() & 15) << 16) + (next() << 8) + next()
314
+ }
315
+
316
+ const unpackHex = value => {
317
+ if (value >= 0 && value < 16) return value < 10 ? '0'.charCodeAt(0) + value : 'A'.charCodeAt(0) + value - 10
318
+ throw new Error('invalid hex: ' + value)
319
+ }
320
+ const unpackNibble = value => {
321
+ if (value >= 0 && value <= 9) return '0'.charCodeAt(0) + value
322
+ switch (value) {
323
+ case 10:
324
+ return '-'.charCodeAt(0)
325
+ case 11:
326
+ return '.'.charCodeAt(0)
327
+ case 15:
328
+ return '\0'.charCodeAt(0)
329
+ default:
330
+ throw new Error('invalid nibble: ' + value)
331
+ }
332
+ }
333
+ const unpackByte = (tag, value) => {
334
+ if (tag === TAGS.NIBBLE_8) return unpackNibble(value)
335
+ if (tag === TAGS.HEX_8) return unpackHex(value)
336
+ throw new Error('unknown tag: ' + tag)
337
+ }
338
+ const readPacked8 = tag => {
339
+ const startByte = readByte()
340
+ let value = ''
341
+ for (let i = 0; i < (startByte & 127); i++) {
342
+ const curByte = readByte()
343
+ value += String.fromCharCode(unpackByte(tag, (curByte & 0xf0) >> 4))
344
+ value += String.fromCharCode(unpackByte(tag, curByte & 0x0f))
345
+ }
346
+ if (startByte >> 7 !== 0) value = value.slice(0, -1)
347
+ return value
348
+ }
349
+
350
+ const isListTag = tag => tag === TAGS.LIST_EMPTY || tag === TAGS.LIST_8 || tag === TAGS.LIST_16
351
+ const readListSize = tag => {
352
+ switch (tag) {
353
+ case TAGS.LIST_EMPTY:
354
+ return 0
355
+ case TAGS.LIST_8:
356
+ return readByte()
357
+ case TAGS.LIST_16:
358
+ return readInt(2)
359
+ default:
360
+ throw new Error('invalid tag for list size: ' + tag)
361
+ }
362
+ }
363
+
364
+ const readJidPair = () => {
365
+ const i = readString(readByte())
366
+ const j = readString(readByte())
367
+ if (j) return (i || '') + '@' + j
368
+ throw new Error('invalid jid pair: ' + i + ', ' + j)
369
+ }
370
+ const readAdJid = () => {
371
+ const domainType = Number(readByte())
372
+ const device = readByte()
373
+ const user = readString(readByte())
374
+ let server = 's.whatsapp.net'
375
+ if (domainType === WAJIDDomains.LID) server = 'lid'
376
+ else if (domainType === WAJIDDomains.HOSTED) server = 'hosted'
377
+ else if (domainType === WAJIDDomains.HOSTED_LID) server = 'hosted.lid'
378
+ return jidEncode(user, server, device)
379
+ }
380
+ const readFbJid = () => {
381
+ const user = readString(readByte())
382
+ const device = readInt(2)
383
+ const server = readString(readByte())
384
+ return `${user}:${device}@${server}`
385
+ }
386
+ const readInteropJid = () => {
387
+ const user = readString(readByte())
388
+ const device = readInt(2)
389
+ const integrator = readInt(2)
390
+ let server = 'interop'
391
+ const beforeServer = indexRef.index
392
+ try {
393
+ server = readString(readByte())
394
+ } catch {
395
+ indexRef.index = beforeServer
396
+ }
397
+ return `${integrator}-${user}:${device}@${server}`
398
+ }
399
+
400
+ const readString = tag => {
401
+ if (tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) return SINGLE_BYTE_TOKENS[tag] || ''
402
+ switch (tag) {
403
+ case TAGS.DICTIONARY_0:
404
+ case TAGS.DICTIONARY_1:
405
+ case TAGS.DICTIONARY_2:
406
+ case TAGS.DICTIONARY_3:
407
+ return getTokenDouble(tag - TAGS.DICTIONARY_0, readByte())
408
+ case TAGS.LIST_EMPTY:
409
+ return ''
410
+ case TAGS.BINARY_8:
411
+ return readStringFromChars(readByte())
412
+ case TAGS.BINARY_20:
413
+ return readStringFromChars(readInt20())
414
+ case TAGS.BINARY_32:
415
+ return readStringFromChars(readInt(4))
416
+ case TAGS.JID_PAIR:
417
+ return readJidPair()
418
+ case TAGS.FB_JID:
419
+ return readFbJid()
420
+ case TAGS.INTEROP_JID:
421
+ return readInteropJid()
422
+ case TAGS.AD_JID:
423
+ return readAdJid()
424
+ case TAGS.HEX_8:
425
+ case TAGS.NIBBLE_8:
426
+ return readPacked8(tag)
427
+ default:
428
+ throw new Error('invalid string with tag: ' + tag)
429
+ }
430
+ }
431
+
432
+ const readList = tag => {
433
+ const items = []
434
+ const size = readListSize(tag)
435
+ for (let i = 0; i < size; i++) items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
436
+ return items
437
+ }
438
+
439
+ const getTokenDouble = (index1, index2) => {
440
+ const dict = DOUBLE_BYTE_TOKENS[index1]
441
+ if (!dict) throw new Error(`Invalid double token dict (${index1})`)
442
+ const value = dict[index2]
443
+ if (typeof value === 'undefined') throw new Error(`Invalid double token (${index2})`)
444
+ return value
445
+ }
446
+
447
+ const listSize = readListSize(readByte())
448
+ const header = readString(readByte())
449
+ if (!listSize || !header.length) throw new Error('invalid node')
450
+
451
+ const attrs = {}
452
+ let data
453
+
454
+ const attributesLength = (listSize - 1) >> 1
455
+ for (let i = 0; i < attributesLength; i++) {
456
+ const key = readString(readByte())
457
+ const value = readString(readByte())
458
+ attrs[key] = value
459
+ }
460
+
461
+ if (listSize % 2 === 0) {
462
+ const tag = readByte()
463
+ if (isListTag(tag)) {
464
+ data = readList(tag)
465
+ } else {
466
+ switch (tag) {
467
+ case TAGS.BINARY_8:
468
+ data = readBytes(readByte())
469
+ break
470
+ case TAGS.BINARY_20:
471
+ data = readBytes(readInt20())
472
+ break
473
+ case TAGS.BINARY_32:
474
+ data = readBytes(readInt(4))
475
+ break
476
+ default:
477
+ data = readString(tag)
478
+ break
479
+ }
480
+ }
481
+ }
482
+
483
+ return { tag: header, attrs, content: data }
484
+ }
485
+
486
+ export const decodeBinaryNode = async buff => {
487
+ const decompBuff = await decompressingIfRequired(buff)
488
+ return decodeDecompressedBinaryNode(decompBuff, constants)
489
+ }
490
+
491
+ /* ------------------------------------------------------------------ */
492
+ /* Generic node helpers */
493
+ /* ------------------------------------------------------------------ */
494
+
495
+ const indexCache = new WeakMap()
496
+
497
+ export const getBinaryNodeChildren = (node, childTag) => {
498
+ if (!node || !Array.isArray(node.content)) return []
499
+ let index = indexCache.get(node)
500
+ if (!index) {
501
+ index = new Map()
502
+ for (const child of node.content) {
503
+ let arr = index.get(child.tag)
504
+ if (!arr) index.set(child.tag, (arr = []))
505
+ arr.push(child)
506
+ }
507
+ indexCache.set(node, index)
508
+ }
509
+ return index.get(childTag) || []
510
+ }
511
+
512
+ export const getBinaryNodeChild = (node, childTag) => getBinaryNodeChildren(node, childTag)[0]
513
+
514
+ export const getAllBinaryNodeChildren = ({ content }) => (Array.isArray(content) ? content : [])
515
+
516
+ export const getBinaryNodeChildBuffer = (node, childTag) => {
517
+ const child = getBinaryNodeChild(node, childTag)?.content
518
+ if (Buffer.isBuffer(child) || child instanceof Uint8Array) return child
519
+ }
520
+
521
+ export const getBinaryNodeChildString = (node, childTag) => {
522
+ const child = getBinaryNodeChild(node, childTag)?.content
523
+ if (Buffer.isBuffer(child) || child instanceof Uint8Array) return Buffer.from(child).toString('utf-8')
524
+ if (typeof child === 'string') return child
525
+ }
526
+
527
+ const bufferToUInt = (e, t) => {
528
+ let a = 0
529
+ for (let i = 0; i < t; i++) a = 256 * a + e[i]
530
+ return a
531
+ }
532
+
533
+ export const getBinaryNodeChildUInt = (node, childTag, length) => {
534
+ const buff = getBinaryNodeChildBuffer(node, childTag)
535
+ if (buff) return bufferToUInt(buff, length)
536
+ }
537
+
538
+ export const assertNodeErrorFree = node => {
539
+ const errNode = getBinaryNodeChild(node, 'error')
540
+ if (errNode) throw new Boom(errNode.attrs.text || 'Unknown error', { data: +errNode.attrs.code })
541
+ }
542
+
543
+ export const reduceBinaryNodeToDictionary = (node, tag) => {
544
+ const nodes = getBinaryNodeChildren(node, tag)
545
+ return nodes.reduce((dict, { attrs }) => {
546
+ if (typeof attrs.name === 'string') dict[attrs.name] = attrs.value || attrs.config_value
547
+ else dict[attrs.config_code] = attrs.value || attrs.config_value
548
+ return dict
549
+ }, {})
550
+ }
551
+
552
+ /** `proto` is passed in by the message decode call site to avoid a hard import cycle here. */
553
+ export const getBinaryNodeMessages = ({ content }, proto) => {
554
+ const msgs = []
555
+ if (Array.isArray(content)) {
556
+ for (const item of content) {
557
+ if (item.tag === 'message') msgs.push(proto.WebMessageInfo.decode(item.content).toJSON())
558
+ }
559
+ }
560
+ return msgs
561
+ }
562
+
563
+ const tabs = n => '\t'.repeat(n)
564
+ export function binaryNodeToString(node, i = 0) {
565
+ if (!node) return node
566
+ if (typeof node === 'string') return tabs(i) + node
567
+ if (node instanceof Uint8Array) return tabs(i) + Buffer.from(node).toString('hex')
568
+ if (Array.isArray(node)) return node.map(x => tabs(i + 1) + binaryNodeToString(x, i + 1)).join('\n')
569
+
570
+ const children = binaryNodeToString(node.content, i + 1)
571
+ const tag = `<${node.tag} ${Object.entries(node.attrs || {})
572
+ .filter(([, v]) => v !== undefined)
573
+ .map(([k, v]) => `${k}='${v}'`)
574
+ .join(' ')}`
575
+ const content = children ? `>\n${children}\n${tabs(i)}</${node.tag}>` : '/>'
576
+ return tag + content
577
+ }
578
+
579
+ /**
580
+ * Produce the binary node (WABinary-like JSON shape) required for the specific
581
+ * interactive button / list type. Compatible with observed official client traffic.
582
+ * NOTE: the "v" (version) / "name" values are empirically derived from real traffic.
583
+ */
584
+ const FLOWS_MAP = {
585
+ mpm: true,
586
+ cta_catalog: true,
587
+ send_location: true,
588
+ call_permission_request: true,
589
+ wa_payment_transaction_details: true,
590
+ automated_greeting_message_view_catalog: true
591
+ }
592
+ const DECISION_SOURCE_CONTENT = [{ tag: 'decision_source', attrs: { value: 'df' } }]
593
+ const LIST_TYPE_CONTENT = { tag: 'list', attrs: { v: '2', type: 'product_list' } }
594
+ const NATIVE_FLOW_ATTRIBUTE = { type: 'native_flow', v: '1' }
595
+ const MIXED_NATIVE_FLOW = {
596
+ tag: 'interactive',
597
+ attrs: NATIVE_FLOW_ATTRIBUTE,
598
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
599
+ }
600
+
601
+ export const getBizBinaryNode = message => {
602
+ const flowMsg = message.interactiveMessage?.nativeFlowMessage
603
+ const firstButtonName = flowMsg?.buttons?.[0]?.name
604
+ const qualityContent = {
605
+ tag: 'quality_control',
606
+ attrs: {
607
+ decision_id: randomBytes(20).toString('hex'),
608
+ source_type: 'third_party'
609
+ },
610
+ content: DECISION_SOURCE_CONTENT
611
+ }
612
+ const bizAttributes = {
613
+ actual_actors: '2',
614
+ host_storage: '2',
615
+ privacy_mode_ts: `${(Date.now() / 1_000) | 0}`
616
+ }
617
+
618
+ if (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info') {
619
+ bizAttributes.native_flow_name = firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
620
+ return { tag: 'biz', attrs: bizAttributes, content: [qualityContent] }
621
+ }
622
+
623
+ if (firstButtonName && FLOWS_MAP[firstButtonName]) {
624
+ return {
625
+ tag: 'biz',
626
+ attrs: bizAttributes,
627
+ content: [
628
+ {
629
+ tag: 'interactive',
630
+ attrs: NATIVE_FLOW_ATTRIBUTE,
631
+ content: [{ tag: 'native_flow', attrs: { v: '2', name: firstButtonName } }]
632
+ },
633
+ qualityContent
634
+ ]
635
+ }
636
+ }
637
+
638
+ if (flowMsg || message.buttonsMessage || message.templateMessage) {
639
+ return { tag: 'biz', attrs: bizAttributes, content: [MIXED_NATIVE_FLOW, qualityContent] }
640
+ }
641
+
642
+ if (message.listMessage) {
643
+ return { tag: 'biz', attrs: bizAttributes, content: [LIST_TYPE_CONTENT, qualityContent] }
644
+ }
645
+
646
+ return { tag: 'biz', attrs: bizAttributes, content: [qualityContent] }
647
+ }
648
+
649
+ export { constants as WA_BINARY_CONSTANTS }