@zervonexx/baileys 5.0.0 → 5.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 (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,50 +1,50 @@
1
- import { proto } from '../../WAProto/index.js'
2
- import { generateWAMessageFromContent, generateWAMessageContent, SCALAR_KINDS, SAFE_MSG_TYPES, USER_MEDIA_KEYS } from '../Utils/index.js'
3
- import { getBizBinaryNode } from '../WABinary/index.js'
4
- import { BaseBuilder } from './base.js'
5
-
6
- export const buildAutoBuilders = handBuiltKeys => {
7
- const result = []
8
- for (const [fieldName, fd] of Object.entries(proto.Message.fields)) {
9
- if (fd.type !== 'msg') continue
10
- const sub = proto.Message[fd.msgType]
11
- if (!sub?.fields) continue
12
- if (sub.fields?.message?.msgType === 'Message') continue
13
- const inputKey = fieldName.replace(/Message$/, '')
14
- if (handBuiltKeys.has(inputKey) || handBuiltKeys.has(fieldName) || USER_MEDIA_KEYS.has(inputKey)) continue
15
- const isScalar = Object.values(sub.fields).every(f =>
16
- SCALAR_KINDS.has(f.type) || (f.type === 'msg' && SAFE_MSG_TYPES.has(f.msgType))
17
- )
18
- if (!isScalar) continue
19
- const className = inputKey.charAt(0).toUpperCase() + inputKey.slice(1)
20
- const BuilderClass = class extends BaseBuilder {
21
- static dispatchKeys = [fieldName, ...(fieldName !== inputKey ? [inputKey] : [])]
22
- async send(jid, opts = {}) {
23
- const content = await generateWAMessageContent(
24
- { [fieldName]: this.data },
25
- { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer, jid }
26
- )
27
- const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
28
- const bizNode = getBizBinaryNode(msg.message)
29
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
30
- return msg
31
- }
32
- }
33
- Object.defineProperty(BuilderClass, 'name', { value: className })
34
- result.push(BuilderClass)
35
- }
36
- return result
37
- }
38
-
39
- let _autoBuilders = null
40
- export const getAutoBuilders = (handBuilt, messageHandlerKeys = []) => {
41
- if (_autoBuilders) return _autoBuilders
42
- const handBuiltKeys = new Set([
43
- ...messageHandlerKeys,
44
- ...handBuilt.flatMap(B =>
45
- B?.dispatchKeys?.length ? B.dispatchKeys : B?.name ? [B.name.replace(/Builder$/, '').toLowerCase()] : []
46
- )
47
- ])
48
- _autoBuilders = buildAutoBuilders(handBuiltKeys)
49
- return _autoBuilders
1
+ import { proto } from '../../WAProto/index.js'
2
+ import { generateWAMessageFromContent, generateWAMessageContent, SCALAR_KINDS, SAFE_MSG_TYPES, USER_MEDIA_KEYS } from '../Utils/index.js'
3
+ import { getBizBinaryNode } from '../WABinary/index.js'
4
+ import { BaseBuilder } from './base.js'
5
+
6
+ export const buildAutoBuilders = handBuiltKeys => {
7
+ const result = []
8
+ for (const [fieldName, fd] of Object.entries(proto.Message.fields)) {
9
+ if (fd.type !== 'msg') continue
10
+ const sub = proto.Message[fd.msgType]
11
+ if (!sub?.fields) continue
12
+ if (sub.fields?.message?.msgType === 'Message') continue
13
+ const inputKey = fieldName.replace(/Message$/, '')
14
+ if (handBuiltKeys.has(inputKey) || handBuiltKeys.has(fieldName) || USER_MEDIA_KEYS.has(inputKey)) continue
15
+ const isScalar = Object.values(sub.fields).every(f =>
16
+ SCALAR_KINDS.has(f.type) || (f.type === 'msg' && SAFE_MSG_TYPES.has(f.msgType))
17
+ )
18
+ if (!isScalar) continue
19
+ const className = inputKey.charAt(0).toUpperCase() + inputKey.slice(1)
20
+ const BuilderClass = class extends BaseBuilder {
21
+ static dispatchKeys = [fieldName, ...(fieldName !== inputKey ? [inputKey] : [])]
22
+ async send(jid, opts = {}) {
23
+ const content = await generateWAMessageContent(
24
+ { [fieldName]: this.data },
25
+ { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer, jid }
26
+ )
27
+ const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
28
+ const bizNode = getBizBinaryNode(msg.message)
29
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
30
+ return msg
31
+ }
32
+ }
33
+ Object.defineProperty(BuilderClass, 'name', { value: className })
34
+ result.push(BuilderClass)
35
+ }
36
+ return result
37
+ }
38
+
39
+ let _autoBuilders = null
40
+ export const getAutoBuilders = (handBuilt, messageHandlerKeys = []) => {
41
+ if (_autoBuilders) return _autoBuilders
42
+ const handBuiltKeys = new Set([
43
+ ...messageHandlerKeys,
44
+ ...handBuilt.flatMap(B =>
45
+ B?.dispatchKeys?.length ? B.dispatchKeys : B?.name ? [B.name.replace(/Builder$/, '').toLowerCase()] : []
46
+ )
47
+ ])
48
+ _autoBuilders = buildAutoBuilders(handBuiltKeys)
49
+ return _autoBuilders
50
50
  }
@@ -1,145 +1,145 @@
1
- import crypto from 'crypto'
2
- import { proto } from '../../WAProto/index.js'
3
- import { generateWAMessage, generateWAMessageFromContent, getUrlInfo, prepareWAMessageMedia, resolveNativeFlowButtons } from '../Utils/index.js'
4
-
5
- export const getRandomHex = () => '#' + Array.from(crypto.getRandomValues(new Uint8Array(3)), b => b.toString(16).padStart(2, '0')).join('')
6
-
7
- export const norm = (data, opts = {}) => {
8
- if (!data) return { ...opts }
9
- if (Array.isArray(data)) return { stickers: data, ...opts }
10
- if (typeof data !== 'object') return { ...opts }
11
- const keys = Object.keys(data)
12
- const base = keys.length && keys.every(k => !isNaN(k)) ? { stickers: Object.values(data) } : { ...data }
13
- return { ...base, ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v != null)) }
14
- }
15
-
16
- export class BaseBuilder {
17
- #client; #data = {}
18
- constructor(client) {
19
- if (!client) throw new Error('Socket client is required')
20
- this.#client = client
21
- }
22
- from(data, opts = {}) { this.#data = norm(data, opts); return this }
23
- get data() { return this.#data }
24
- get client() { return this.#client }
25
- }
26
-
27
- export const buildDispatch = (builders, handlers = {}) => ({
28
- ...Object.fromEntries(builders.flatMap(B => (B.dispatchKeys ?? []).map(key => [key, (sock, jid, content, opts) => {
29
- const { relay, upload, waUploadToServer, logger, ...safeOpts } = opts ?? {}
30
- const b = new B(sock)
31
- return (typeof b.from === 'function' ? b.from(content[key], safeOpts) : b).send(jid, opts)
32
- }]))),
33
- ...handlers
34
- })
35
-
36
- // orderMessage → "order" | stickerPack → "stickerpack"
37
- const toFactoryName = key => key.replace(/(?:Message|Pack|Packet)$/i, '').toLowerCase()
38
- // orderMessage → "sendOrderMessage" | already starts with "send" → unchanged
39
- const toSendName = key => key.toLowerCase().startsWith('send') ? key : 'send' + key.charAt(0).toUpperCase() + key.slice(1)
40
-
41
- export const buildPlugins = (builders, extra = {}) => {
42
- const seen = new Set()
43
- const entries = []
44
-
45
- for (const B of builders) {
46
- // 1. explicit static shortcuts win first
47
- for (const [name, factory] of Object.entries(B.shortcuts ?? {})) {
48
- if (!seen.has(name)) { seen.add(name); entries.push([name, factory]) }
49
- }
50
- // 2. auto-derive factory + send shortcut from each dispatchKey
51
- for (const key of B.dispatchKeys ?? []) {
52
- const factoryName = toFactoryName(key)
53
- const sendName = toSendName(key)
54
- if (!seen.has(factoryName)) { seen.add(factoryName); entries.push([factoryName, sock => opts => new B(sock, opts)]) }
55
- if (!seen.has(sendName)) { seen.add(sendName); entries.push([sendName, sock => (jid, data, opts = {}) => new B(sock).from(data, opts).send(jid, opts)]) }
56
- }
57
- // 3. fallback: factory from class name (covers builders with no dispatchKeys)
58
- const className = B.name?.toLowerCase()
59
- if (className && !seen.has(className)) { seen.add(className); entries.push([className, sock => opts => new B(sock, opts)]) }
60
- }
61
-
62
- // 4. extra always wins — overrides any earlier registration
63
- for (const [name, factory] of Object.entries(extra)) {
64
- const idx = entries.findIndex(([n]) => n === name)
65
- if (idx === -1) { seen.add(name); entries.push([name, factory]) }
66
- else entries[idx] = [name, factory]
67
- }
68
-
69
- return Object.fromEntries(entries)
70
- }
71
-
72
- export async function handleGroupStatus(sock, jid, content, config) {
73
- const needsBackground = !content.image && !content.video
74
- const msg = await generateWAMessage(jid, content, {
75
- logger: sock.logger, userJid: sock.user?.id, upload: sock.waUploadToServer,
76
- getUrlInfo: text => getUrlInfo(text, { thumbnailWidth: config?.linkPreviewImageThumbnailWidth, fetchOpts: { timeout: 4000, ...(config?.options ?? {}) }, logger: sock.logger, uploadImage: config?.generateHighQualityLinkPreview ? sock.waUploadToServer : undefined }),
77
- ...(needsBackground && {
78
- font: content.font ?? Math.floor(Math.random() * 9),
79
- textColor: content.textColor || getRandomHex(),
80
- backgroundColor: content.backgroundColor || getRandomHex()
81
- })
82
- })
83
- return sock.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: [{ tag: 'meta', attrs: { is_group_status: 'true' }, content: undefined }] })
84
- }
85
-
86
- export async function handleStatusMention(sock, jid, d, config) {
87
- const userJid = sock.user?.id
88
- const mediaType = d.image ? 'image' : 'video'
89
- const media = await prepareWAMessageMedia({ [mediaType]: d.image ?? d.video }, { upload: sock.waUploadToServer })
90
- const statusMsg = await sock.relayMessage('status@broadcast', { ...media }, {
91
- statusJidList: [d.mentions, userJid].filter(Boolean),
92
- additionalNodes: [{ tag: 'meta', attrs: {}, content: [{ tag: 'mentioned_users', attrs: {}, content: [{ tag: 'to', attrs: { jid: d.mentions }, content: undefined }] }] }]
93
- })
94
- const mentionMsg = await generateWAMessageFromContent(jid, {
95
- statusMentionMessage: proto.Message.StatusMentionMessage.create({
96
- message: { protocolMessage: proto.Message.ProtocolMessage.create({ messageId: statusMsg?.key?.id ?? d.mentions, type: proto.Message.ProtocolMessage.Type.STATUS_MENTION_MESSAGE }) }
97
- })
98
- }, { userJid })
99
- return sock.relayMessage(jid, mentionMsg.message, { messageId: mentionMsg.key.id, additionalNodes: [{ tag: 'meta', attrs: { is_status_mention: 'true' }, content: undefined }] })
100
- }
101
-
102
- export async function handlePollResult(sock, jid, p) {
103
- const msg = await generateWAMessageFromContent(jid, {
104
- pollResultSnapshotMessage: proto.Message.PollResultSnapshotMessage.create({
105
- name: p.name,
106
- pollVotes: (p.pollVotes ?? []).map(v => proto.Message.PollResultSnapshotMessage.PollVote.create({ optionName: v.optionName, optionVoteCount: String(v.optionVoteCount ?? 0) })),
107
- contextInfo: proto.ContextInfo.create({ isForwarded: true, forwardingScore: 1 })
108
- })
109
- }, { userJid: sock.user?.id })
110
- await sock.relayMessage(jid, msg.message, { messageId: msg.key.id })
111
- return msg
112
- }
113
-
114
- export const q = quoted => quoted ? { quoted } : {}
115
-
116
- export async function handleNativeFlow(sock, jid, content, opts = {}) {
117
- const rawButtons = content.nativeFlow
118
- const resolved = resolveNativeFlowButtons(rawButtons)
119
- const offerParams = content.offerText ? { limited_time_offer: { text: content.offerText, url: content.offerUrl || '', copy_code: content.offerCode || '', expiration_time: content.offerExpiration ? Math.floor(content.offerExpiration / 1000) : 0 } } : {}
120
- const messageParams = { ...offerParams }
121
- if (content.optionText) messageParams.bottom_sheet = { in_thread_buttons_limit: 1, divider_indices: Array.from({ length: resolved.length }, (_, i) => i), list_title: content.optionTitle || content.optionText, button_title: content.optionText }
122
- if (content.interactiveAsTemplate) return sock.sendMessage(jid, { ...content, nativeFlow: undefined, interactiveButtons: undefined, templateButtons: resolved.map(b => { const p = JSON.parse(b.buttonParamsJson ?? '{}'); return b.name === 'cta_url' ? { text: p.display_text, url: p.url } : b.name === 'cta_call' ? { text: p.display_text, call: p.phone_number } : { text: p.display_text, id: p.id } }) }, opts)
123
- return sock.sendMessage(jid, { ...content, nativeFlow: undefined, interactiveButtons: resolved, ...(Object.keys(messageParams).length ? { messageParamsJson: JSON.stringify(messageParams) } : {}) }, opts)
124
- }
125
-
126
- export const PRIMITIVE_SHORTCUTS = {
127
- sendText: sock => (jid, text, opts = {}) => sock.sendMessage(jid, { text }, opts),
128
- sendImage: sock => (jid, image, caption = '', opts = {}) => sock.sendMessage(jid, { image, caption }, opts),
129
- sendVideo: sock => (jid, video, caption = '', opts = {}) => sock.sendMessage(jid, { video, caption }, opts),
130
- sendDocument: sock => (jid, document, caption = '', opts = {}) => sock.sendMessage(jid, { document, caption }, opts),
131
- sendAudio: sock => (jid, audio, opts = {}) => sock.sendMessage(jid, { audio, ptt: opts.ptt ?? false, ...opts }),
132
- sendSticker: sock => (jid, sticker, opts = {}) => sock.sendMessage(jid, { sticker }, opts),
133
- sendLocation: sock => (jid, location, opts = {}) => sock.sendMessage(jid, { location }, opts),
134
- sendContact: sock => (jid, contact, opts = {}) => sock.sendMessage(jid, { contacts: { displayName: contact.name ?? '', contacts: [contact] } }, opts),
135
- sendReaction: sock => (jid, key, emoji, opts = {}) => sock.sendMessage(jid, { react: { text: emoji, key } }, opts),
136
- sendForward: sock => (jid, message, opts = {}) => sock.sendMessage(jid, { forward: message, force: opts.force }, opts)
137
- }
138
-
139
- export const HANDLER_SHORTCUTS = {
140
- sendStatusMentionMessage: (sock, config) => (jid, data) => handleStatusMention(sock, jid, norm(data), config),
141
- sendStatusMentions: (sock, config) => (jid, data) => handleStatusMention(sock, jid, norm(data), config),
142
- sendPollResultMessage: sock => (jid, data) => handlePollResult(sock, jid, norm(data)),
143
- sendGroupStatusMessage: (sock, config) => (jid, content, opts = {}) => handleGroupStatus(sock, jid, norm(content), config),
144
- sendNativeFlow: sock => (jid, content, opts = {}) => handleNativeFlow(sock, jid, norm(content), opts)
1
+ import crypto from 'crypto'
2
+ import { proto } from '../../WAProto/index.js'
3
+ import { generateWAMessage, generateWAMessageFromContent, getUrlInfo, prepareWAMessageMedia, resolveNativeFlowButtons } from '../Utils/index.js'
4
+
5
+ export const getRandomHex = () => '#' + Array.from(crypto.getRandomValues(new Uint8Array(3)), b => b.toString(16).padStart(2, '0')).join('')
6
+
7
+ export const norm = (data, opts = {}) => {
8
+ if (!data) return { ...opts }
9
+ if (Array.isArray(data)) return { stickers: data, ...opts }
10
+ if (typeof data !== 'object') return { ...opts }
11
+ const keys = Object.keys(data)
12
+ const base = keys.length && keys.every(k => !isNaN(k)) ? { stickers: Object.values(data) } : { ...data }
13
+ return { ...base, ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v != null)) }
14
+ }
15
+
16
+ export class BaseBuilder {
17
+ #client; #data = {}
18
+ constructor(client) {
19
+ if (!client) throw new Error('Socket client is required')
20
+ this.#client = client
21
+ }
22
+ from(data, opts = {}) { this.#data = norm(data, opts); return this }
23
+ get data() { return this.#data }
24
+ get client() { return this.#client }
25
+ }
26
+
27
+ export const buildDispatch = (builders, handlers = {}) => ({
28
+ ...Object.fromEntries(builders.flatMap(B => (B.dispatchKeys ?? []).map(key => [key, (sock, jid, content, opts) => {
29
+ const { relay, upload, waUploadToServer, logger, ...safeOpts } = opts ?? {}
30
+ const b = new B(sock)
31
+ return (typeof b.from === 'function' ? b.from(content[key], safeOpts) : b).send(jid, opts)
32
+ }]))),
33
+ ...handlers
34
+ })
35
+
36
+ // orderMessage → "order" | stickerPack → "stickerpack"
37
+ const toFactoryName = key => key.replace(/(?:Message|Pack|Packet)$/i, '').toLowerCase()
38
+ // orderMessage → "sendOrderMessage" | already starts with "send" → unchanged
39
+ const toSendName = key => key.toLowerCase().startsWith('send') ? key : 'send' + key.charAt(0).toUpperCase() + key.slice(1)
40
+
41
+ export const buildPlugins = (builders, extra = {}) => {
42
+ const seen = new Set()
43
+ const entries = []
44
+
45
+ for (const B of builders) {
46
+ // 1. explicit static shortcuts win first
47
+ for (const [name, factory] of Object.entries(B.shortcuts ?? {})) {
48
+ if (!seen.has(name)) { seen.add(name); entries.push([name, factory]) }
49
+ }
50
+ // 2. auto-derive factory + send shortcut from each dispatchKey
51
+ for (const key of B.dispatchKeys ?? []) {
52
+ const factoryName = toFactoryName(key)
53
+ const sendName = toSendName(key)
54
+ if (!seen.has(factoryName)) { seen.add(factoryName); entries.push([factoryName, sock => opts => new B(sock, opts)]) }
55
+ if (!seen.has(sendName)) { seen.add(sendName); entries.push([sendName, sock => (jid, data, opts = {}) => new B(sock).from(data, opts).send(jid, opts)]) }
56
+ }
57
+ // 3. fallback: factory from class name (covers builders with no dispatchKeys)
58
+ const className = B.name?.toLowerCase()
59
+ if (className && !seen.has(className)) { seen.add(className); entries.push([className, sock => opts => new B(sock, opts)]) }
60
+ }
61
+
62
+ // 4. extra always wins — overrides any earlier registration
63
+ for (const [name, factory] of Object.entries(extra)) {
64
+ const idx = entries.findIndex(([n]) => n === name)
65
+ if (idx === -1) { seen.add(name); entries.push([name, factory]) }
66
+ else entries[idx] = [name, factory]
67
+ }
68
+
69
+ return Object.fromEntries(entries)
70
+ }
71
+
72
+ export async function handleGroupStatus(sock, jid, content, config) {
73
+ const needsBackground = !content.image && !content.video
74
+ const msg = await generateWAMessage(jid, content, {
75
+ logger: sock.logger, userJid: sock.user?.id, upload: sock.waUploadToServer,
76
+ getUrlInfo: text => getUrlInfo(text, { thumbnailWidth: config?.linkPreviewImageThumbnailWidth, fetchOpts: { timeout: 4000, ...(config?.options ?? {}) }, logger: sock.logger, uploadImage: config?.generateHighQualityLinkPreview ? sock.waUploadToServer : undefined }),
77
+ ...(needsBackground && {
78
+ font: content.font ?? Math.floor(Math.random() * 9),
79
+ textColor: content.textColor || getRandomHex(),
80
+ backgroundColor: content.backgroundColor || getRandomHex()
81
+ })
82
+ })
83
+ return sock.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: [{ tag: 'meta', attrs: { is_group_status: 'true' }, content: undefined }] })
84
+ }
85
+
86
+ export async function handleStatusMention(sock, jid, d, config) {
87
+ const userJid = sock.user?.id
88
+ const mediaType = d.image ? 'image' : 'video'
89
+ const media = await prepareWAMessageMedia({ [mediaType]: d.image ?? d.video }, { upload: sock.waUploadToServer })
90
+ const statusMsg = await sock.relayMessage('status@broadcast', { ...media }, {
91
+ statusJidList: [d.mentions, userJid].filter(Boolean),
92
+ additionalNodes: [{ tag: 'meta', attrs: {}, content: [{ tag: 'mentioned_users', attrs: {}, content: [{ tag: 'to', attrs: { jid: d.mentions }, content: undefined }] }] }]
93
+ })
94
+ const mentionMsg = await generateWAMessageFromContent(jid, {
95
+ statusMentionMessage: proto.Message.StatusMentionMessage.create({
96
+ message: { protocolMessage: proto.Message.ProtocolMessage.create({ messageId: statusMsg?.key?.id ?? d.mentions, type: proto.Message.ProtocolMessage.Type.STATUS_MENTION_MESSAGE }) }
97
+ })
98
+ }, { userJid })
99
+ return sock.relayMessage(jid, mentionMsg.message, { messageId: mentionMsg.key.id, additionalNodes: [{ tag: 'meta', attrs: { is_status_mention: 'true' }, content: undefined }] })
100
+ }
101
+
102
+ export async function handlePollResult(sock, jid, p) {
103
+ const msg = await generateWAMessageFromContent(jid, {
104
+ pollResultSnapshotMessage: proto.Message.PollResultSnapshotMessage.create({
105
+ name: p.name,
106
+ pollVotes: (p.pollVotes ?? []).map(v => proto.Message.PollResultSnapshotMessage.PollVote.create({ optionName: v.optionName, optionVoteCount: String(v.optionVoteCount ?? 0) })),
107
+ contextInfo: proto.ContextInfo.create({ isForwarded: true, forwardingScore: 1 })
108
+ })
109
+ }, { userJid: sock.user?.id })
110
+ await sock.relayMessage(jid, msg.message, { messageId: msg.key.id })
111
+ return msg
112
+ }
113
+
114
+ export const q = quoted => quoted ? { quoted } : {}
115
+
116
+ export async function handleNativeFlow(sock, jid, content, opts = {}) {
117
+ const rawButtons = content.nativeFlow
118
+ const resolved = resolveNativeFlowButtons(rawButtons)
119
+ const offerParams = content.offerText ? { limited_time_offer: { text: content.offerText, url: content.offerUrl || '', copy_code: content.offerCode || '', expiration_time: content.offerExpiration ? Math.floor(content.offerExpiration / 1000) : 0 } } : {}
120
+ const messageParams = { ...offerParams }
121
+ if (content.optionText) messageParams.bottom_sheet = { in_thread_buttons_limit: 1, divider_indices: Array.from({ length: resolved.length }, (_, i) => i), list_title: content.optionTitle || content.optionText, button_title: content.optionText }
122
+ if (content.interactiveAsTemplate) return sock.sendMessage(jid, { ...content, nativeFlow: undefined, interactiveButtons: undefined, templateButtons: resolved.map(b => { const p = JSON.parse(b.buttonParamsJson ?? '{}'); return b.name === 'cta_url' ? { text: p.display_text, url: p.url } : b.name === 'cta_call' ? { text: p.display_text, call: p.phone_number } : { text: p.display_text, id: p.id } }) }, opts)
123
+ return sock.sendMessage(jid, { ...content, nativeFlow: undefined, interactiveButtons: resolved, ...(Object.keys(messageParams).length ? { messageParamsJson: JSON.stringify(messageParams) } : {}) }, opts)
124
+ }
125
+
126
+ export const PRIMITIVE_SHORTCUTS = {
127
+ sendText: sock => (jid, text, opts = {}) => sock.sendMessage(jid, { text }, opts),
128
+ sendImage: sock => (jid, image, caption = '', opts = {}) => sock.sendMessage(jid, { image, caption }, opts),
129
+ sendVideo: sock => (jid, video, caption = '', opts = {}) => sock.sendMessage(jid, { video, caption }, opts),
130
+ sendDocument: sock => (jid, document, caption = '', opts = {}) => sock.sendMessage(jid, { document, caption }, opts),
131
+ sendAudio: sock => (jid, audio, opts = {}) => sock.sendMessage(jid, { audio, ptt: opts.ptt ?? false, ...opts }),
132
+ sendSticker: sock => (jid, sticker, opts = {}) => sock.sendMessage(jid, { sticker }, opts),
133
+ sendLocation: sock => (jid, location, opts = {}) => sock.sendMessage(jid, { location }, opts),
134
+ sendContact: sock => (jid, contact, opts = {}) => sock.sendMessage(jid, { contacts: { displayName: contact.name ?? '', contacts: [contact] } }, opts),
135
+ sendReaction: sock => (jid, key, emoji, opts = {}) => sock.sendMessage(jid, { react: { text: emoji, key } }, opts),
136
+ sendForward: sock => (jid, message, opts = {}) => sock.sendMessage(jid, { forward: message, force: opts.force }, opts)
137
+ }
138
+
139
+ export const HANDLER_SHORTCUTS = {
140
+ sendStatusMentionMessage: (sock, config) => (jid, data) => handleStatusMention(sock, jid, norm(data), config),
141
+ sendStatusMentions: (sock, config) => (jid, data) => handleStatusMention(sock, jid, norm(data), config),
142
+ sendPollResultMessage: sock => (jid, data) => handlePollResult(sock, jid, norm(data)),
143
+ sendGroupStatusMessage: (sock, config) => (jid, content, opts = {}) => handleGroupStatus(sock, jid, norm(content), config),
144
+ sendNativeFlow: sock => (jid, content, opts = {}) => handleNativeFlow(sock, jid, norm(content), opts)
145
145
  }