@itznomo/baileys 0.0.0-stage → 0.0.3

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 (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,654 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ const MESSAGE_EDIT_TYPE = 14
4
+
5
+ const newLayout = (name, data, extra = {}) => ({
6
+ ...extra,
7
+ view_model: { [Array.isArray(data) ? 'primitives' : 'primitive']: data, __typename: `GenAI${name}LayoutViewModel` }
8
+ })
9
+
10
+ const extractInlineEntities = (text, { hyperlink = true, citation = true, latex = true } = {}) => {
11
+ const toEntity = (type, ie) => {
12
+ if (type === 'hyperlink') {
13
+ return { key: ie.key, metadata: { display_name: ie.text, is_trusted: ie.is_trusted, url: ie.url, __typename: 'GenAIInlineLinkItem' } }
14
+ }
15
+ if (type === 'citation') {
16
+ return {
17
+ key: ie.key,
18
+ metadata: { reference_id: ie.reference_id, reference_url: ie.url, reference_title: ie.url, reference_display_name: ie.url, sources: [], __typename: 'GenAISearchCitationItem' }
19
+ }
20
+ }
21
+ if (type === 'latex') {
22
+ return {
23
+ key: ie.key,
24
+ metadata: {
25
+ latex_expression: ie.text,
26
+ latex_image: { url: ie.url, width: Number(ie.width) || 100, height: Number(ie.height) || 100 },
27
+ font_height: Number(ie.font_height) || 83.333333333333,
28
+ padding: Number(ie.padding) || 15,
29
+ __typename: 'GenAILatexItem'
30
+ }
31
+ }
32
+ }
33
+ }
34
+
35
+ const inline_entities = []
36
+ let result = ''
37
+ let last = 0
38
+ let citationIndex = 1
39
+ let hyperlinkIndex = 0
40
+ let latexIndex = 0
41
+ const stack = []
42
+
43
+ for (let i = 0; i < text.length; i++) {
44
+ if (text[i] === '[' && text[i - 1] !== '\\') {
45
+ stack.push(i)
46
+ continue
47
+ }
48
+ if (text[i] === ']' && (text[i + 1] === '(' || text[i + 1] === '<')) {
49
+ const start = stack.pop()
50
+ if (start == null) continue
51
+ const open = text[i + 1]
52
+ const close = open === '(' ? ')' : '>'
53
+ const kind = open === '(' ? 'link' : 'latex'
54
+ let end = i + 2
55
+ let depth = 1
56
+ while (end < text.length && depth) {
57
+ if (text[end] === open && text[end - 1] !== '\\') depth++
58
+ else if (text[end] === close && text[end - 1] !== '\\') depth--
59
+ end++
60
+ }
61
+ if (depth) continue
62
+
63
+ const raw = text.slice(start + 1, i).trim()
64
+ const url = text.slice(i + 2, end - 1).trim()
65
+ let key, tag, type, ie
66
+
67
+ if (kind === 'latex') {
68
+ if (!latex) continue
69
+ const [txt = '', width = null, height = null, fontHeight = null, padding = null] = raw.split('|')
70
+ key = `_LATEX_${latexIndex++}`
71
+ tag = `{{${key}}}${txt || 'image'}{{/${key}}}`
72
+ type = 'latex'
73
+ ie = { key, text: txt, url, width, height, font_height: fontHeight, padding }
74
+ } else if (raw) {
75
+ if (!hyperlink) continue
76
+ const trusted = !url.startsWith('!')
77
+ key = `_HYPERLINK_${hyperlinkIndex++}`
78
+ tag = `{{${key}}}${trusted ? url : url.slice(1)}{{/${key}}}`
79
+ type = 'hyperlink'
80
+ ie = { key, text: raw, url: trusted ? url : url.slice(1), is_trusted: trusted }
81
+ } else {
82
+ if (!citation) continue
83
+ key = `_CITATION_${citationIndex - 1}`
84
+ tag = `{{${key}}}${url}{{/${key}}}`
85
+ type = 'citation'
86
+ ie = { reference_id: citationIndex++, key, text: '', url }
87
+ }
88
+
89
+ result += text.slice(last, start) + tag
90
+ last = end
91
+ const entity = toEntity(type, ie)
92
+ if (entity) inline_entities.push(entity)
93
+ i = end - 1
94
+ }
95
+ }
96
+ result += text.slice(last)
97
+ return { text: result, inline_entities }
98
+ }
99
+
100
+ const toTableMetadata = (rows, { hyperlink = true, citation = true, latex = true } = {}) => {
101
+ if (!Array.isArray(rows) || !rows.every(row => Array.isArray(row) && row.every(cell => typeof cell === 'string'))) {
102
+ throw new TypeError('Table must be a nested array of strings')
103
+ }
104
+ const [header, ...body] = rows
105
+ const maxLen = Math.max(header.length, ...body.map(r => r.length))
106
+ const normalize = r => [...r, ...Array(maxLen - r.length).fill('')]
107
+
108
+ const unifiedRows = [{ is_header: true, cells: normalize(header) }, ...body.map(r => ({ is_header: false, cells: normalize(r) }))].map(row => {
109
+ const markdownCells = row.cells.map(cell => {
110
+ const extracted = extractInlineEntities(cell, { hyperlink, citation, latex })
111
+ return { text: extracted.text, ...(extracted.inline_entities.length ? { inline_entities: extracted.inline_entities } : {}) }
112
+ })
113
+ return { ...row, ...(markdownCells.some(c => c.inline_entities?.length) ? { markdown_cells: markdownCells } : {}) }
114
+ })
115
+
116
+ return {
117
+ title: '',
118
+ rows: unifiedRows.map(r => ({ items: r.cells, ...(r.is_header ? { isHeading: true } : {}) })),
119
+ unifiedRows
120
+ }
121
+ }
122
+
123
+ const KEYWORD_SETS = {
124
+ javascript: new Set(['break','case','catch','continue','debugger','delete','do','else','finally','for','function','if','in','instanceof','new','return','switch','this','throw','typeof','var','void','while','with','true','false','null','undefined','class','const','let','super','extends','export','import','yield','static','async','await','get','set']),
125
+ typescript: new Set(['abstract','any','as','asserts','bigint','boolean','declare','enum','implements','infer','interface','is','keyof','module','namespace','never','readonly','require','number','object','override','private','protected','public','satisfies','string','symbol','type','unknown','using','from','break','case','catch','continue','do','else','finally','for','function','if','new','return','switch','this','throw','try','var','void','while','class','const','let','extends','import','export','async','await']),
126
+ python: new Set(['False','None','True','and','as','assert','async','await','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']),
127
+ java: new Set(['abstract','assert','boolean','break','byte','case','catch','char','class','const','continue','default','do','double','else','enum','extends','final','finally','float','for','goto','if','implements','import','instanceof','int','interface','long','native','new','package','private','protected','public','return','short','static','strictfp','super','switch','synchronized','this','throw','throws','transient','try','void','volatile','while']),
128
+ go: new Set(['break','case','chan','const','continue','default','defer','else','fallthrough','for','func','go','goto','if','import','interface','map','package','range','return','select','struct','switch','type','var']),
129
+ golang: new Set(['break','case','chan','const','continue','default','defer','else','fallthrough','for','func','go','goto','if','import','interface','map','package','range','return','select','struct','switch','type','var']),
130
+ c: new Set(['auto','break','case','char','const','continue','default','do','double','else','enum','extern','float','for','goto','if','int','long','register','return','short','signed','sizeof','static','struct','switch','typedef','union','unsigned','void','volatile','while']),
131
+ cpp: new Set(['alignas','alignof','and','auto','bool','break','case','catch','class','const','constexpr','continue','delete','do','double','else','enum','explicit','export','extern','false','float','for','friend','if','inline','int','long','mutable','namespace','new','noexcept','nullptr','operator','private','protected','public','return','short','signed','sizeof','static','struct','switch','template','this','throw','true','try','typedef','typename','union','unsigned','using','virtual','void','while']),
132
+ php: new Set(['abstract','and','array','as','break','callable','case','catch','class','clone','const','continue','declare','default','do','echo','else','elseif','empty','enddeclare','endfor','endforeach','endif','endswitch','endwhile','extends','final','finally','fn','for','foreach','function','global','goto','if','implements','include','include_once','instanceof','interface','match','namespace','new','null','or','private','protected','public','require','require_once','return','static','switch','throw','trait','try','use','var','while','yield']),
133
+ rust: new Set(['as','break','const','continue','crate','else','enum','extern','false','fn','for','if','impl','in','let','loop','match','mod','move','mut','pub','ref','return','self','Self','static','struct','super','trait','true','type','unsafe','use','where','while']),
134
+ html: new Set(['html','head','body','div','span','p','a','img','video','audio','script','style','link','meta','form','input','button','table','tr','td','th','ul','ol','li','section','article','header','footer','nav','main']),
135
+ bash: new Set(['if','then','else','elif','fi','for','while','do','done','case','esac','function','in','select','until','break','continue','return','export','readonly','local','declare'])
136
+ }
137
+ const HL = { DEFAULT: 0, KEYWORD: 1, METHOD: 2, STRING: 3, NUMBER: 4, COMMENT: 5 }
138
+ const HL_NAME = ['DEFAULT', 'KEYWORD', 'METHOD', 'STR', 'NUMBER', 'COMMENT']
139
+
140
+ export const tokenizeAIRichCode = (code, lang = 'javascript') => {
141
+ const key = (lang || '').toLowerCase()
142
+ if (!key || key === 'txt' || key === 'text' || key === 'plaintext') return [{ codeContent: code, highlightType: HL.DEFAULT }]
143
+
144
+ const keywords = KEYWORD_SETS[key] || new Set()
145
+ const tokens = []
146
+ const isIdentifier = c => (key === 'css' ? /[a-zA-Z0-9_$-]/.test(c) : key === 'html' ? /[a-zA-Z0-9_$:-]/.test(c) : /[a-zA-Z0-9_$]/.test(c))
147
+ const push = (content, type) => {
148
+ if (!content) return
149
+ const last = tokens[tokens.length - 1]
150
+ if (last && last.highlightType === type) last.codeContent += content
151
+ else tokens.push({ codeContent: content, highlightType: type })
152
+ }
153
+
154
+ let i = 0
155
+ while (i < code.length) {
156
+ const c = code[i]
157
+ if (/\s/.test(c)) {
158
+ const s = i
159
+ while (i < code.length && /\s/.test(code[i])) i++
160
+ push(code.slice(s, i), HL.DEFAULT)
161
+ continue
162
+ }
163
+ if ((c === '/' && code[i + 1] === '/') || (c === '#' && (key === 'python' || key === 'bash'))) {
164
+ const s = i
165
+ while (i < code.length && code[i] !== '\n') i++
166
+ push(code.slice(s, i), HL.COMMENT)
167
+ continue
168
+ }
169
+ if (c === '"' || c === "'" || c === '`') {
170
+ const s = i
171
+ const q = c
172
+ i++
173
+ while (i < code.length) {
174
+ if (code[i] === '\\' && i + 1 < code.length) i += 2
175
+ else if (code[i] === q) {
176
+ i++
177
+ break
178
+ } else i++
179
+ }
180
+ push(code.slice(s, i), HL.STRING)
181
+ continue
182
+ }
183
+ if (/[0-9]/.test(c)) {
184
+ const s = i
185
+ while (i < code.length && /[0-9._]/.test(code[i])) i++
186
+ push(code.slice(s, i), HL.NUMBER)
187
+ continue
188
+ }
189
+ if (/[a-zA-Z_$]/.test(c)) {
190
+ const s = i
191
+ while (i < code.length && isIdentifier(code[i])) i++
192
+ const word = code.slice(s, i)
193
+ let type = HL.DEFAULT
194
+ if (keywords.has(word)) type = HL.KEYWORD
195
+ else {
196
+ let j = i
197
+ while (j < code.length && /\s/.test(code[j])) j++
198
+ if (code[j] === '(') type = HL.METHOD
199
+ }
200
+ push(word, type)
201
+ continue
202
+ }
203
+ push(c, HL.DEFAULT)
204
+ i++
205
+ }
206
+ return tokens
207
+ }
208
+
209
+ const mediaUrl = value => {
210
+ if (Buffer.isBuffer(value)) return `data:application/octet-stream;base64,${value.toString('base64')}`
211
+ if (value && typeof value === 'object' && typeof value.url === 'string') return value.url
212
+ return typeof value === 'string' ? value : undefined
213
+ }
214
+
215
+ export class AIRichBuilder {
216
+
217
+ constructor(client) {
218
+ this._client = client
219
+ this._title = ''
220
+ this._footer = ''
221
+ this._contextInfo = {}
222
+ this._submessages = []
223
+ this._sections = []
224
+ this._richResponseSources = []
225
+ this._embeddedScreens = []
226
+ }
227
+
228
+ setTitle(title) {
229
+ if (typeof title !== 'string') throw new TypeError('Title must be a string')
230
+ this._title = title
231
+ return this
232
+ }
233
+
234
+ setFooter(footer) {
235
+ if (typeof footer !== 'string') throw new TypeError('Footer must be a string')
236
+ this._footer = footer
237
+ return this
238
+ }
239
+
240
+ setContextInfo(obj) {
241
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new TypeError('ContextInfo must be a plain object')
242
+ this._contextInfo = obj
243
+ return this
244
+ }
245
+
246
+ addText(text, { hyperlink = true, citation = true, latex = true } = {}) {
247
+ if (typeof text !== 'string') throw new TypeError('Text must be a string')
248
+ const { text: extractedText, inline_entities } = extractInlineEntities(text, { hyperlink, citation, latex })
249
+ this._submessages.push({ messageType: 2, messageText: extractedText })
250
+ this._sections.push(newLayout('Single', { text: extractedText, ...(inline_entities.length ? { inline_entities } : {}), __typename: 'GenAIMarkdownTextUXPrimitive' }))
251
+ return this
252
+ }
253
+
254
+ addCode(language, code) {
255
+ if (typeof language !== 'string' || typeof code !== 'string') throw new TypeError('Language and code must be a string')
256
+ const codeBlocks = tokenizeAIRichCode(code, language)
257
+ this._submessages.push({ messageType: 5, codeMetadata: { codeLanguage: language, codeBlocks } })
258
+ this._sections.push(
259
+ newLayout('Single', {
260
+ language,
261
+ code_blocks: codeBlocks.map(b => ({ content: b.codeContent, type: HL_NAME[b.highlightType] })),
262
+ __typename: 'GenAICodeUXPrimitive'
263
+ })
264
+ )
265
+ return this
266
+ }
267
+
268
+ addTable(table, { hyperlink = true, citation = true, latex = true } = {}) {
269
+ if (!Array.isArray(table)) throw new TypeError('Table must be an array')
270
+ const meta = toTableMetadata(table, { hyperlink, citation, latex })
271
+ this._submessages.push({ messageType: 4, tableMetadata: { title: meta.title, rows: meta.rows } })
272
+ this._sections.push(newLayout('Single', { rows: meta.unifiedRows, __typename: 'GenATableUXPrimitive' }))
273
+ return this
274
+ }
275
+
276
+ addImage(image) {
277
+ if (!(typeof image === 'string' || Buffer.isBuffer(image) || (Array.isArray(image) && image.every(v => typeof v === 'string' || Buffer.isBuffer(v))))) {
278
+ throw new TypeError('image must be a string | buffer | array of string/buffer')
279
+ }
280
+ const list = (Array.isArray(image) ? image : [image]).map(mediaUrl).filter(Boolean)
281
+ this._submessages.push({ messageType: 1, gridImageMetadata: { gridImageUrl: { imagePreviewUrl: list[0] }, imageUrls: list.map(u => ({ imagePreviewUrl: u, imageHighResUrl: u, sourceUrl: u })) } })
282
+ for (const url of list) this._sections.push(newLayout('Single', { media: { url, mime_type: 'image/png' }, imagine_type: 'IMAGE', status: { status: 'READY' }, __typename: 'GenAIImaginePrimitive' }))
283
+ return this
284
+ }
285
+
286
+ addVideo(video) {
287
+ const items = Array.isArray(video) ? video : [video]
288
+ this._submessages.push({ messageType: 2, messageText: '[ VIDEO ]' })
289
+ for (const item of items) {
290
+ const isObj = item && typeof item === 'object' && !Buffer.isBuffer(item)
291
+ const url = mediaUrl(isObj ? item.url : item)
292
+ this._sections.push(
293
+ newLayout('Single', {
294
+ media: { url, mime_type: (isObj && item.mimeType) || 'video/mp4', file_length: (isObj && item.fileLength) || 0, duration: (isObj && item.duration) || 0 },
295
+ imagine_type: 'ANIMATE',
296
+ status: { status: 'READY' },
297
+ thumbnail: { raw_media: isObj ? item.thumbnail : undefined },
298
+ __typename: 'GenAIImaginePrimitive'
299
+ })
300
+ )
301
+ }
302
+ return this
303
+ }
304
+
305
+ addSource(sources = []) {
306
+ const isFlat = Array.isArray(sources) && sources.every(item => typeof item === 'string')
307
+ const list = isFlat ? [sources] : sources
308
+ if (!(Array.isArray(list) && list.every(item => Array.isArray(item) && item.every(v => typeof v === 'string')))) {
309
+ throw new TypeError('Sources must be a string array or an array of string arrays')
310
+ }
311
+ const mapped = list.map(([icon, url, text]) => ({
312
+ source_type: 'THIRD_PARTY',
313
+ source_display_name: text ?? '',
314
+ source_subtitle: 'AI',
315
+ source_url: url ?? '',
316
+ favicon: { url: icon ?? '', mime_type: 'image/jpeg', width: 16, height: 16 }
317
+ }))
318
+ this._sections.push(newLayout('Single', { sources: mapped, __typename: 'GenAISearchResultPrimitive' }))
319
+ return this
320
+ }
321
+
322
+ addProduct(data = {}) {
323
+ const items = Array.isArray(data) ? data : [data]
324
+ this._submessages.push({ messageType: 2, messageText: '[ PRODUCT ]' })
325
+ const products = items.map(item => ({
326
+ title: item.title,
327
+ brand: item.brand,
328
+ price: item.price,
329
+ sale_price: item.sale_price,
330
+ product_url: item.product_url ?? item.url,
331
+ image: { url: mediaUrl(item.image_url ?? item.image) },
332
+ additional_images: [{ url: mediaUrl(item.icon_url ?? item.icon) }],
333
+ __typename: 'GenAIProductItemCardPrimitive'
334
+ }))
335
+ this._sections.push(newLayout(Array.isArray(data) ? 'HScroll' : 'Single', Array.isArray(data) ? products : products[0]))
336
+ return this
337
+ }
338
+
339
+ addPost(data = {}) {
340
+ const posts = Array.isArray(data) ? data : [data]
341
+ this._submessages.push({ messageType: 2, messageText: '[ POST ]' })
342
+ const primitives = posts.map(p => ({
343
+ title: p.title ?? '',
344
+ subtitle: p.subtitle ?? '',
345
+ username: p.username ?? '',
346
+ profile_picture_url: mediaUrl(p.profile_picture_url ?? p.profile_url ?? p.profile),
347
+ is_verified: !!(p.is_verified || p.verified),
348
+ thumbnail_url: mediaUrl(p.thumbnail_url ?? p.thumbnail),
349
+ post_caption: p.post_caption ?? p.caption ?? '',
350
+ likes_count: p.likes_count ?? p.like ?? 0,
351
+ comments_count: p.comments_count ?? p.comment ?? 0,
352
+ shares_count: p.shares_count ?? p.share ?? 0,
353
+ post_url: p.post_url ?? p.url ?? '',
354
+ post_deeplink: p.post_deeplink ?? p.deeplink ?? '',
355
+ source_app: p.source_app || p.source || 'INSTAGRAM',
356
+ footer_label: p.footer_label ?? p.footer ?? '',
357
+ footer_icon: mediaUrl(p.footer_icon ?? p.icon),
358
+ is_carousel: posts.length > 1,
359
+ orientation: p.orientation ?? 'LANDSCAPE',
360
+ post_type: p.post_type ?? 'VIDEO',
361
+ __typename: 'GenAIPostPrimitive'
362
+ }))
363
+ this._sections.push(newLayout('HScroll', primitives))
364
+ return this
365
+ }
366
+
367
+ addReels(data = []) {
368
+ const items = Array.isArray(data) ? data : [data]
369
+ const reels = items.map(item => ({ ...item, _avatar: mediaUrl(item.profileIconUrl ?? item.profile_url ?? item.profile), _thumbnail: mediaUrl(item.thumbnailUrl ?? item.thumbnail) }))
370
+ this._submessages.push({
371
+ messageType: 9,
372
+ contentItemsMetadata: { contentType: 1, itemsMetadata: reels.map(item => ({ reelItem: { title: item.username ?? '', profileIconUrl: item._avatar, thumbnailUrl: item._thumbnail, videoUrl: item.videoUrl ?? item.url ?? '' } })) }
373
+ })
374
+ reels.forEach((item, idx) =>
375
+ this._richResponseSources.push({ thumbnailCdnUrl: item._thumbnail, sourceProviderUrl: item.videoUrl ?? item.url ?? '', sourceQuery: '', faviconCdnUrl: item._avatar, citationNumber: idx + 1, sourceTitle: item.username ?? '' })
376
+ )
377
+ this._sections.push(
378
+ newLayout(
379
+ 'HScroll',
380
+ reels.map(item => ({
381
+ reels_url: item.videoUrl ?? item.url ?? '',
382
+ thumbnail_url: item._thumbnail,
383
+ creator: item.username ?? item.title ?? '',
384
+ avatar_url: item._avatar,
385
+ reels_title: item.reels_title ?? item.title ?? '',
386
+ likes_count: item.likes_count ?? item.like ?? 0,
387
+ shares_count: item.shares_count ?? item.share ?? 0,
388
+ view_count: item.view_count ?? item.view ?? 0,
389
+ reel_source: item.reel_source ?? item.source ?? 'IG',
390
+ is_verified: !!(item.is_verified || item.verified),
391
+ __typename: 'GenAIReelPrimitive'
392
+ }))
393
+ )
394
+ )
395
+ return this
396
+ }
397
+
398
+ addTip(text) {
399
+ this._submessages.push({ messageType: 2, messageText: text })
400
+ this._sections.push(newLayout('Single', { text, __typename: 'GenAIMetadataTextPrimitive' }))
401
+ return this
402
+ }
403
+
404
+ addSuggest(suggestion, { scroll = true, layout } = {}) {
405
+ if (!(typeof suggestion === 'string' || (Array.isArray(suggestion) && suggestion.every(v => typeof v === 'string')))) {
406
+ throw new TypeError('Suggestion must be a string or array of strings')
407
+ }
408
+ const items = (Array.isArray(suggestion) ? suggestion : [suggestion]).map(text => ({ prompt_text: text, prompt_type: 'SUGGESTED_PROMPT', __typename: 'GenAIFollowUpSuggestionPillPrimitive' }))
409
+ const type = layout ?? (items.length === 1 ? 'Single' : scroll ? 'HScroll' : 'ActionRow')
410
+ this._sections.push(newLayout(type, type === 'Single' ? items[0] : items, { __typename: 'GenAIUnifiedResponseSection' }))
411
+ return this
412
+ }
413
+
414
+ addProcess(title) {
415
+ if (typeof title !== 'string') throw new TypeError('Process title must be a string')
416
+ this._submessages.push({ messageType: 2, messageText: title })
417
+ this._sections.push(newLayout('Single', { icon: null, is_in_progress: true, meta_search_apps: null, target_secondary_screen_id: null, target_secondary_screen_tab_id: null, title, __typename: 'GenAIBotProgressStatusPrimitive' }))
418
+ return this
419
+ }
420
+
421
+ addHtml(...args) {
422
+ let options = {}
423
+ if (args.length && typeof args[args.length - 1] === 'object' && !Array.isArray(args[args.length - 1])) options = args.pop()
424
+ const url = options.url ?? ''
425
+ const trustedSources = options.trustedSources ?? []
426
+
427
+ if (args.length === 1 && typeof args[0] === 'string') {
428
+ this._submessages.push({ messageType: 2, messageText: '[ HTML ]' })
429
+ this._sections.push(newLayout('Single', { payload: args[0], url, trusted_sources: trustedSources, __typename: 'GenAIaeacdsnwHtmlPrimitive' }))
430
+ return this
431
+ }
432
+ if (!args.every(item => Array.isArray(item) && typeof item[0] === 'string')) {
433
+ throw new TypeError('addHtml() expects a single HTML string, or one or more [html, title] pairs, with an optional trailing options object')
434
+ }
435
+ if (!this._embeddedScreens.length) this._embeddedScreens.push({ title: 'Preview', content: [{ __typename: 'FOAIDNixelButtonSheets', tabs: [] }] })
436
+ const tabs = this._embeddedScreens[0].content[0].tabs
437
+ this._submessages.push({ messageType: 2, messageText: '[ HTML ]' })
438
+ for (const [payload, title] of args) {
439
+ tabs.push({
440
+ id: `tab_${tabs.length}`,
441
+ tab_header: title ?? `Tab ${tabs.length + 1}`,
442
+ sections: [newLayout('Single', { payload, url, trusted_sources: trustedSources, __typename: 'GenAIaeacdsnwHtmlPrimitive' }, { __typename: 'GenAIUnifiedResponseSection' })],
443
+ step_entries: []
444
+ })
445
+ }
446
+ return this
447
+ }
448
+
449
+ build({ forwarded = true, quoted, quotedParticipant, botJid = '0@bot' } = {}) {
450
+ const forward = forwarded ? { forwardingScore: 1, isForwarded: true, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 } : {}
451
+ const qObj = quoted
452
+ ? { stanzaId: quoted?.key?.id || quoted?.id, participant: quotedParticipant || quoted?.key?.participant || quoted?.key?.remoteJid, quotedType: 0, quotedMessage: quoted?.message ?? quoted }
453
+ : {}
454
+
455
+ const sections = this._footer ? [...this._sections, newLayout('Single', { text: this._footer, __typename: 'GenAIMetadataTextPrimitive' })] : this._sections
456
+ const responseData = { response_id: randomUUID(), sections }
457
+ if (this._embeddedScreens.length) responseData.embedded_screens = this._embeddedScreens
458
+
459
+ const hasRenderableContent = sections.length > 0 || this._embeddedScreens.length > 0
460
+ const richResponseMessage = { messageType: 1, submessages: this._submessages, contextInfo: { ...forward, ...qObj, ...this._contextInfo } }
461
+ if (hasRenderableContent) richResponseMessage.unifiedResponse = { data: Buffer.from(JSON.stringify(responseData)).toString('base64') }
462
+
463
+ return {
464
+ messageContextInfo: { deviceListMetadata: {}, deviceListMetadataVersion: 2, botMetadata: { messageDisclaimerText: this._title, richResponseSourcesMetadata: { sources: this._richResponseSources } } },
465
+ botForwardedMessage: { message: { richResponseMessage } }
466
+ }
467
+ }
468
+
469
+ buildEdit(jid, targetKey, editedMessage) {
470
+ if (!jid) throw new Error('A jid is required to edit an aiRich message')
471
+ if (!targetKey?.id) throw new Error('A target message id is required to edit an aiRich message')
472
+ if (!editedMessage) throw new Error('editedMessage does not contain an aiRich response')
473
+ return {
474
+ botForwardedMessage: {
475
+ message: {
476
+ protocolMessage: {
477
+ key: { remoteJid: jid, fromMe: true, id: targetKey.id },
478
+ type: MESSAGE_EDIT_TYPE,
479
+ editedMessage,
480
+ timestampMs: Date.now()
481
+ }
482
+ }
483
+ }
484
+ }
485
+ }
486
+
487
+ async send(jid, { forwarded, quoted, quotedParticipant, botJid, bypassDownload = true, ...sendOptions } = {}) {
488
+ if (!this._client) throw new Error('AIRichBuilder.send() needs a client — use sock.aiRich() or new AIRichBuilder(sock)')
489
+ return this._client.sendMessage(jid, { aiRich: this, forwarded, quoted, quotedParticipant, botJid }, { ...sendOptions, bypassDownload })
490
+ }
491
+ }
492
+
493
+ const isPlainObject = v => !!v && typeof v === 'object' && !Array.isArray(v) && !Buffer.isBuffer(v)
494
+
495
+ // spec.html accepts: 'html' | ['html', 'Tab title'] | [['html', 'Tab 1'], ['html', 'Tab 2']]
496
+ // optionally with spec.htmlOptions = { url, trustedSources }, or a trailing/second options object.
497
+ // Before, the options had no way in through the spec form and trusted_sources was always [].
498
+ const addHtmlFromSpec = (builder, html, htmlOptions) => {
499
+ let options = isPlainObject(htmlOptions) ? { ...htmlOptions } : {}
500
+ let items
501
+ if (!Array.isArray(html)) {
502
+ items = [html]
503
+ } else if (Array.isArray(html[0])) {
504
+ items = [...html]
505
+ } else if (html.length === 2 && typeof html[0] === 'string' && isPlainObject(html[1])) {
506
+ items = [html[0]]
507
+ options = { ...html[1], ...options }
508
+ } else {
509
+ items = [html]
510
+ }
511
+ if (isPlainObject(items[items.length - 1])) options = { ...items.pop(), ...options }
512
+ builder.addHtml(...items, options)
513
+ }
514
+
515
+ export const aiRichBuilderFromSpec = spec => {
516
+ const b = new AIRichBuilder()
517
+ if (spec.title) b.setTitle(spec.title)
518
+ if (spec.footer) b.setFooter(spec.footer)
519
+ if (spec.contextInfo) b.setContextInfo(spec.contextInfo)
520
+ if (spec.text) b.addText(spec.text, spec.textOptions)
521
+ if (spec.code) b.addCode(spec.code.language, spec.code.code)
522
+ if (spec.table) b.addTable(spec.table, spec.tableOptions)
523
+ if (spec.image) b.addImage(spec.image)
524
+ if (spec.video) b.addVideo(spec.video)
525
+ if (spec.source) b.addSource(spec.source)
526
+ if (spec.product) b.addProduct(spec.product)
527
+ if (spec.post) b.addPost(spec.post)
528
+ if (spec.reels) b.addReels(spec.reels)
529
+ if (spec.tip) b.addTip(spec.tip)
530
+ if (spec.suggest) b.addSuggest(spec.suggest, spec.suggestOptions)
531
+ if (spec.process) b.addProcess(spec.process)
532
+ if (spec.html) addHtmlFromSpec(b, spec.html, spec.htmlOptions)
533
+ return b
534
+ }
535
+
536
+ // ─── AIRich alias ─────────────────────────────────────────────────────────────
537
+ // Expose upstream-compatible `AIRich` alias for socket-builder.js
538
+ export { AIRichBuilder as AIRich }
539
+
540
+ // ─── aiRichFromObject ─────────────────────────────────────────────────────────
541
+ export function aiRichFromObject(client, jid, data, opts = {}) {
542
+ const { _r, ...sendOpts } = opts
543
+ const r = _r ?? new AIRichBuilder(client, { botJid: data.botJid })
544
+ const isChild = !!_r
545
+ if (!isChild && (data.title ?? data.disclaimerText)) r.setTitle(data.title ?? data.disclaimerText)
546
+ if (data.parts) {
547
+ for (const p of data.parts) {
548
+ const code = Array.isArray(p.code) ? p.code.map(c => c.codeContent ?? c.content ?? '').join('\n') : p.code
549
+ const table = Array.isArray(p.table) ? p.table.map(row => Array.isArray(row) ? row : (row.items ?? row.cells ?? [])) : p.table
550
+ aiRichFromObject(client, jid, { ...p, ...(code ? { code } : {}), ...(table ? { table } : {}) }, { ...sendOpts, _r: r })
551
+ }
552
+ return isChild ? r : r.send(jid, sendOpts)
553
+ }
554
+ if (data.texts) data.texts.forEach(t => r.addText(t))
555
+ else if (data.text) r.addText(data.text)
556
+ if (data.codes) data.codes.forEach(c => r.addCode(c.language ?? data.language ?? '', c.code ?? c.content))
557
+ else if (data.code) {
558
+ const c = typeof data.code === 'string' ? data.code : (data.code.code ?? data.code.content)
559
+ const lang = typeof data.code === 'string' ? (data.language ?? '') : (data.code.language ?? data.language ?? '')
560
+ r.addCode(lang, c)
561
+ }
562
+ if (data.table) r.addTable(data.table, data.tableTitle)
563
+ else if (data.headers && data.rows) r.addTable([data.headers, ...data.rows], data.tableTitle)
564
+ if (data.images) data.images.forEach(img => r.addImage(img.url ?? img))
565
+ if (data.image) r.addImage(data.image.url ?? data.image)
566
+ if (data.reels) r.addReels(data.reels)
567
+ if (data.sources) r.addSource(data.sources)
568
+ if (data.suggest) r.addSuggest(data.suggest)
569
+ if (data.tip) r.addTip(data.tip)
570
+ if (data.footer) r.setFooter(data.footer)
571
+ return isChild ? r : r.send(jid, sendOpts)
572
+ }
573
+
574
+ // ─── attachAIRich ─────────────────────────────────────────────────────────────
575
+ // Attaches all AIRich, sendRich*, aiPrompt, and sendAsMimic methods to result.
576
+ // Returns a Proxy that provides helpful suggestions for misspelled method names.
577
+ export function attachAIRich(result, config = {}) {
578
+ const sock = result
579
+ const STATUS_JID = 'status@broadcast'
580
+
581
+ result.airich = opts => new AIRichBuilder(result, opts)
582
+
583
+ result.captureAiRich = msg => {
584
+ const rich = msg?.botForwardedMessage?.message?.richResponseMessage ?? msg?.richResponseMessage
585
+ if (!rich?.unifiedResponse?.data) return null
586
+ return {
587
+ submessages: rich.submessages ?? [],
588
+ sections: JSON.parse(Buffer.isBuffer(rich.unifiedResponse.data) ? rich.unifiedResponse.data.toString() : Buffer.from(rich.unifiedResponse.data, 'base64').toString()),
589
+ contextInfo: rich.contextInfo ?? {},
590
+ messageType: rich.messageType ?? 1
591
+ }
592
+ }
593
+
594
+ result.relayAiRich = (jid, captured, opts = {}) => {
595
+ const r = new AIRichBuilder(result)
596
+ return r.send(jid, opts)
597
+ }
598
+
599
+ result.sendRichFromObject = (jid, data, opts = {}) => aiRichFromObject(result, jid, data, opts)
600
+ result.sendRichMessage = (jid, data, quoted, opts = {}) => result.sendMessage(jid, { aiRich: data }, { ...(quoted ? { quoted } : {}), ...opts })
601
+ result.sendCodeBlock = (jid, code, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { code, language: opts.language ?? 'javascript', title: opts.title } }, quoted ? { quoted } : {})
602
+ result.sendTable = (jid, title, headers, rows, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { title, table: [headers, ...rows] } }, quoted ? { quoted } : {})
603
+ result.sendList = (jid, title, items, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { title, table: [['Key', 'Value'], ...items] } }, quoted ? { quoted } : {})
604
+ result.sendLink = (jid, text, links, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { text, sources: links.map(url => ({ url, title: url })) } }, quoted ? { quoted } : {})
605
+ result.sendLatex = (jid, expressions, quoted, opts = {}) => result.sendMessage(jid, { aiRich: { text: opts.text, latex: expressions } }, quoted ? { quoted } : {})
606
+
607
+ result.sendRichMap = (jid, mapOpts, options = {}) => { const r = new AIRichBuilder(result); return r.send(jid, options) }
608
+ result.sendDynamic = (jid, dynOpts, options = {}) => { const r = new AIRichBuilder(result); return r.send(jid, options) }
609
+ result.sendBotPromptSuggestions = (jid, content = {}, options = {}) => {
610
+ const { text, suggestions = [] } = content
611
+ const r = new AIRichBuilder(result)
612
+ if (text) r.addText(text)
613
+ if (r.addSuggest) r.addSuggest(suggestions)
614
+ return r.send(jid, options)
615
+ }
616
+ result.sendBotSources = (jid, content = {}, options = {}) => {
617
+ const { text, sources = [] } = content
618
+ const r = new AIRichBuilder(result)
619
+ if (text) r.addText(text)
620
+ r.addSource(sources)
621
+ return r.send(jid, options)
622
+ }
623
+ result.sendInstagramProfile = (jid, data, options = {}) => { const r = new AIRichBuilder(result); return r.send(jid, options) }
624
+ result.sendUnifiedResponse = (jid, sections, submessages = [], options = {}) => { const r = new AIRichBuilder(result); return r.send(jid, options) }
625
+ result.sendRichButtonGrid = async (jid, grid, options = {}) => {
626
+ const { text, footer, cards = [] } = grid || {}
627
+ if (!Array.isArray(cards) || cards.length === 0) throw new Error('sendRichButtonGrid expects at least one card')
628
+ return result.sendMessage(jid, { ...(text ? { text } : {}), ...(footer ? { footer } : {}), cards }, options)
629
+ }
630
+
631
+ result.sendStatus = async (content, options = {}) => {
632
+ const provided = options.statusJidList || content?.statusJidList || sock.statusJidList || []
633
+ if (!provided.length) throw new Error('sendStatus requires statusJidList')
634
+ return result.sendMessage(STATUS_JID, { ...content, status: true }, { ...options, broadcast: true, statusJidList: provided })
635
+ }
636
+
637
+ // Fuzzy proxy for misspelled method names
638
+ const normalize = s => s.toLowerCase().replace(/[^a-z]/g, '')
639
+ const knownKeys = Object.keys(result).filter(k => typeof result[k] === 'function')
640
+ const normalizedMap = new Map(knownKeys.map(k => [normalize(k), k]))
641
+
642
+ return new Proxy(result, {
643
+ get(target, prop, receiver) {
644
+ if (prop in target) return Reflect.get(target, prop, receiver)
645
+ if (typeof prop !== 'string') return undefined
646
+ const match = normalizedMap.get(normalize(prop))
647
+ if (match) {
648
+ target.logger?.warn?.(`[DanuZz] Unknown method "${prop}" — did you mean "${match}"? Calling it.`)
649
+ return target[match]
650
+ }
651
+ return undefined
652
+ }
653
+ })
654
+ }