@pasqua-dev/baileys 0.0.0-stage → 2.8.11

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 (142) hide show
  1. package/README.md +2434 -2
  2. package/WAProto/V +1 -0
  3. package/WAProto/WAProto.proto +8051 -0
  4. package/WAProto/index.js +289292 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.js +158 -0
  7. package/lib/Signal/Group/ciphertext-message.js +11 -0
  8. package/lib/Signal/Group/group-session-builder.js +29 -0
  9. package/lib/Signal/Group/group_cipher.js +81 -0
  10. package/lib/Signal/Group/index.js +11 -0
  11. package/lib/Signal/Group/keyhelper.js +17 -0
  12. package/lib/Signal/Group/sender-chain-key.js +25 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  14. package/lib/Signal/Group/sender-key-message.js +65 -0
  15. package/lib/Signal/Group/sender-key-name.js +47 -0
  16. package/lib/Signal/Group/sender-key-record.js +40 -0
  17. package/lib/Signal/Group/sender-key-state.js +83 -0
  18. package/lib/Signal/Group/sender-message-key.js +25 -0
  19. package/lib/Signal/libsignal.js +428 -0
  20. package/lib/Signal/lid-mapping.js +280 -0
  21. package/lib/Socket/Client/index.js +2 -0
  22. package/lib/Socket/Client/types.js +10 -0
  23. package/lib/Socket/Client/websocket.js +53 -0
  24. package/lib/Socket/aigroups.js +315 -0
  25. package/lib/Socket/ban-checker.js +265 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1848 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +82 -0
  32. package/lib/Socket/interactive-handler.js +627 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2103 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1105 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/bug-payloads.js +485 -0
  70. package/lib/Utils/business.js +230 -0
  71. package/lib/Utils/chat-utils.js +885 -0
  72. package/lib/Utils/companion-reg-client-utils.js +55 -0
  73. package/lib/Utils/consumer-application.js +102 -0
  74. package/lib/Utils/crypto.js +117 -0
  75. package/lib/Utils/decode-wa-message.js +484 -0
  76. package/lib/Utils/event-buffer.js +589 -0
  77. package/lib/Utils/generics.js +388 -0
  78. package/lib/Utils/ghost-mode.js +150 -0
  79. package/lib/Utils/group-history.js +56 -0
  80. package/lib/Utils/history.js +130 -0
  81. package/lib/Utils/identity-chameleon.js +174 -0
  82. package/lib/Utils/identity-change-handler.js +48 -0
  83. package/lib/Utils/index.js +37 -0
  84. package/lib/Utils/jid-display-normalization.js +209 -0
  85. package/lib/Utils/link-preview.js +84 -0
  86. package/lib/Utils/logger.js +2 -0
  87. package/lib/Utils/lt-hash.js +7 -0
  88. package/lib/Utils/make-mutex.js +32 -0
  89. package/lib/Utils/message-composer.js +467 -0
  90. package/lib/Utils/message-inspect.js +67 -0
  91. package/lib/Utils/message-retry-manager.js +241 -0
  92. package/lib/Utils/messages-media.js +1006 -0
  93. package/lib/Utils/messages.js +1962 -0
  94. package/lib/Utils/meta-ai-msmsg.js +130 -0
  95. package/lib/Utils/meta-compositing.js +194 -0
  96. package/lib/Utils/noise-handler.js +200 -0
  97. package/lib/Utils/offline-node-processor.js +39 -0
  98. package/lib/Utils/pre-key-manager.js +105 -0
  99. package/lib/Utils/process-message.js +527 -0
  100. package/lib/Utils/reporting-utils.js +257 -0
  101. package/lib/Utils/rich-message-utils.js +434 -0
  102. package/lib/Utils/signal.js +200 -0
  103. package/lib/Utils/stanza-ack.js +37 -0
  104. package/lib/Utils/sync-action-utils.js +47 -0
  105. package/lib/Utils/tc-token-utils.js +162 -0
  106. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  107. package/lib/Utils/use-single-file-auth-state.js +96 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  109. package/lib/Utils/validate-connection.js +206 -0
  110. package/lib/Utils/voip-rekey.js +20 -0
  111. package/lib/Utils/welcome-flow.js +217 -0
  112. package/lib/WABinary/constants.js +1463 -0
  113. package/lib/WABinary/decode.js +261 -0
  114. package/lib/WABinary/encode.js +219 -0
  115. package/lib/WABinary/generic-utils.js +227 -0
  116. package/lib/WABinary/index.js +5 -0
  117. package/lib/WABinary/jid-utils.js +95 -0
  118. package/lib/WABinary/types.js +1 -0
  119. package/lib/WAM/BinaryInfo.js +9 -0
  120. package/lib/WAM/constants.js +22852 -0
  121. package/lib/WAM/encode.js +149 -0
  122. package/lib/WAM/index.js +3 -0
  123. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  124. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  125. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  126. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  127. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  128. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  129. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  130. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  131. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  132. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  133. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  134. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  135. package/lib/WAUSync/Protocols/index.js +12 -0
  136. package/lib/WAUSync/USyncQuery.js +201 -0
  137. package/lib/WAUSync/USyncUser.js +54 -0
  138. package/lib/WAUSync/index.js +3 -0
  139. package/lib/antiban.cjs +4726 -0
  140. package/lib/index.d.ts +286 -0
  141. package/lib/index.js +19 -0
  142. package/package.json +127 -4
@@ -0,0 +1,265 @@
1
+ import {
2
+ USyncQuery,
3
+ USyncUser
4
+ } from '../WAUSync/index.js';
5
+
6
+ // ────────────────────────────────────────────────────────────────────────
7
+ // PASQUA BAN CHECKER API — 4-factor WhatsApp ban-status detection
8
+ // ────────────────────────────────────────────────────────────────────────
9
+ //
10
+ // Usage:
11
+ // const result = await sock.checkBanStatus('1234567890');
12
+ // // or with @s.whatsapp.net suffix:
13
+ // const result = await sock.checkBanStatus('1234567890@s.whatsapp.net');
14
+ //
15
+ // Returned shape:
16
+ // {
17
+ // status : 'ACTIVE' | 'PROFILE_HIDDEN' | 'LIKELY_ACTIVE' | 'BANNED' |
18
+ // 'OFF_WHATSAPP' | 'UNKNOWN',
19
+ // emoji : '🟢' | '🟡' | '🔴' | '❓',
20
+ // confidence : 0..1,
21
+ // deviceCount: number | null, // identity-key probe result
22
+ // registryExists: boolean | null, // sock.onWhatsApp result
23
+ // pageVisible: boolean | null, // public send-page profile probe
24
+ // profileName: string | null // display name if visible
25
+ // }
26
+ //
27
+ // THE FOUR FACTORS (all exercised against WhatsApp's own servers):
28
+ // Factor A — Live registry (sock.onWhatsApp)
29
+ // Factor B — Public send-page (og:title / og:image on api.whatsapp.com)
30
+ // Factor C — Identity-key device (USync device-protocol probe — the
31
+ // strongest signal: banned numbers have their keys destroyed)
32
+ // Factor D — Device-count signature
33
+ // 2+ devices → real multi-device account → ACTIVE
34
+ // 1 device + generic → stale key mid-deletion → BANNED
35
+ // 0 devices → keys fully garbage-collected → BANNED/OFF-WHATSAPP
36
+ // null (probe failed) → falls back to Factors A + B
37
+
38
+ // ── Number normalization ───────────────────────────────────────────────
39
+ export function normalizeJidTarget(input) {
40
+ if (!input) return null;
41
+ let num = String(input).replace(/[^0-9+]/g, '');
42
+ if (!num) return null;
43
+ if (num.startsWith('+')) num = num.slice(1);
44
+ if (num.endsWith('@s.whatsapp.net')) {
45
+ num = num.replace('@s.whatsapp.net', '');
46
+ }
47
+ if (num.length < 8 || num.length > 15) return null;
48
+ return num;
49
+ }
50
+
51
+ // ── Factor B: public send-page profile probe ───────────────────────────
52
+ // Active account → og:title carries the display name
53
+ // AND og:image points to their profile picture (pps.whatsapp.net)
54
+ // Banned/offline → generic "Share on WhatsApp" title
55
+ // AND og:image is WhatsApp's default avatar (static.whatsapp.net)
56
+ const DEFAULT_AVATAR_DOMAIN = 'static.whatsapp.net';
57
+ const OWN_AVATAR_DOMAIN = 'pps.whatsapp.net';
58
+
59
+ export async function probeSendPage(num, fetchImpl) {
60
+ const impl = fetchImpl || globalThis.fetch;
61
+ if (!impl) return { ok: false, generic: null, title: null, hasOwnPic: false };
62
+ // Retry twice: WhatsApp's edge servers can return the generic page
63
+ // momentarily even for active numbers (eventual-consistency blip).
64
+ for (let attempt = 0; attempt < 3; attempt++) {
65
+ try {
66
+ const res = await impl(
67
+ `https://api.whatsapp.com/send?phone=${encodeURIComponent(num)}&type=phone_number&app_absent=0`,
68
+ {
69
+ headers: {
70
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
71
+ 'Accept-Language': 'en-US,en;q=0.9',
72
+ },
73
+ signal: AbortSignal.timeout(15000),
74
+ }
75
+ );
76
+ const html = await res.text();
77
+
78
+ // Decode the title (WhatsApp encodes fancy fonts as HTML entities)
79
+ const raw = ((html.match(/property="og:title" content="([^"]*)"/i) || [])[1] || '');
80
+ const title = raw.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)));
81
+ const generic = /share on whatsapp/i.test(title);
82
+
83
+ const avatar = ((html.match(/property="og:image" content="([^"]*)"/i) || [])[1] || '');
84
+ const hasOwnPic = !generic && new RegExp(OWN_AVATAR_DOMAIN, 'i').test(avatar);
85
+
86
+ // A real display name is a strong ACTIVE signal; bail early
87
+ if (!generic) {
88
+ return { ok: true, generic: false, title: title.trim(), hasOwnPic };
89
+ }
90
+ // Generic page — only consider it stable after the final retry
91
+ if (attempt === 2) {
92
+ return { ok: true, generic: true, title: null, hasOwnPic: false };
93
+ }
94
+ // Intermediate retries: wait before re-probing
95
+ await new Promise(r => setTimeout(r, 1500));
96
+ }
97
+ catch (_) {
98
+ if (attempt === 2) return { ok: false, generic: null, title: null, hasOwnPic: false };
99
+ await new Promise(r => setTimeout(r, 1500));
100
+ }
101
+ }
102
+ return { ok: false, generic: null, title: null, hasOwnPic: false };
103
+ }
104
+
105
+ // ── Factor C: identity-key (device) probe ──────────────────────────────
106
+ // The bot's own authenticated session can query any number's device list
107
+ // via USync device-protocol. A banned number's identity keys are destroyed
108
+ // on the server, so this query returns zero devices (or fails) for banned
109
+ // accounts while an active account returns its real device list.
110
+ export async function probeIdentityDevices(sock, target) {
111
+ try {
112
+ if (typeof sock.executeUSyncQuery !== 'function') return null;
113
+ const q = new USyncQuery()
114
+ .withDeviceProtocol()
115
+ .withUser(new USyncUser().withId(target + '@s.whatsapp.net'));
116
+ const devRes = await sock.executeUSyncQuery(q);
117
+ if (devRes && Array.isArray(devRes.list) && devRes.list.length > 0) {
118
+ const devInfo = devRes.list[0];
119
+ const dl = devInfo?.devices?.deviceList || devInfo?.devices?.device_list || null;
120
+ let devices = Array.isArray(dl) ? dl : null;
121
+ // NOTE: devRes shape depends on fork version; if we can't parse
122
+ // it, keep devices === null (probe failed)
123
+ if (devices === null && devInfo && devInfo.devices) {
124
+ const d = devInfo.devices;
125
+ for (const k of Object.keys(d)) {
126
+ if (Array.isArray(d[k])) { devices = d[k]; break; }
127
+ }
128
+ }
129
+ return devices === null ? null : devices.length;
130
+ }
131
+ // Parsed response but empty list → zero devices on the servers
132
+ return 0;
133
+ }
134
+ catch (_) { /* probe failed */ }
135
+ return null;
136
+ }
137
+
138
+ // ── Factor A: live registry ────────────────────────────────────────────
139
+ export async function probeRegistry(sock, target) {
140
+ try {
141
+ if (typeof sock.onWhatsApp !== 'function') return null;
142
+ const onWA = await sock.onWhatsApp(target + '@s.whatsapp.net');
143
+ return Array.isArray(onWA) && onWA.length > 0 && onWA[0].exists === true;
144
+ }
145
+ catch (_) { /* registry probe failed */ }
146
+ return null;
147
+ }
148
+
149
+ // ── The verdict ────────────────────────────────────────────────────────
150
+ export function buildVerdict(target, { devices, registry, page }) {
151
+ const profileName = page?.title || null;
152
+ const pageVisible = page?.ok === true && page.generic === false;
153
+ const pageGeneric = page?.ok === true && page.generic === true;
154
+
155
+ // Factor C/D (identity-key probe) is the strongest signal — use it first
156
+ if (devices !== null) {
157
+ if (devices >= 2 && page?.ok) {
158
+ return {
159
+ status: 'ACTIVE', emoji: '🟢', confidence: 0.99,
160
+ deviceCount: devices, registryExists: registry,
161
+ pageVisible, profileName
162
+ };
163
+ }
164
+ if (devices === 1 && pageGeneric) {
165
+ // The ban-decay signature: WhatsApp removes keys lazily,
166
+ // so a banned account often leaves ONE orphaned stale key
167
+ // with its public profile already stripped.
168
+ return {
169
+ status: 'BANNED', emoji: '🔴', confidence: 0.9,
170
+ deviceCount: devices, registryExists: registry,
171
+ pageVisible: false, profileName: null
172
+ };
173
+ }
174
+ if (devices === 1 && pageVisible) {
175
+ // Single device + name/photo visible: rare but possible
176
+ // (new install, no linked devices) — benefit of the doubt.
177
+ return {
178
+ status: 'ACTIVE', emoji: '🟢', confidence: 0.8,
179
+ deviceCount: devices, registryExists: registry,
180
+ pageVisible, profileName
181
+ };
182
+ }
183
+ if (devices === 0 && page?.ok) {
184
+ // Keys fully garbage-collected AND public profile gone
185
+ return {
186
+ status: pageGeneric ? 'BANNED' : 'OFF_WHATSAPP',
187
+ emoji: '🔴', confidence: 0.95,
188
+ deviceCount: devices, registryExists: registry,
189
+ pageVisible: false, profileName: null
190
+ };
191
+ }
192
+ if (devices === 0) {
193
+ return {
194
+ status: 'OFF_WHATSAPP', emoji: '🔴', confidence: 0.85,
195
+ deviceCount: devices, registryExists: registry,
196
+ pageVisible: false, profileName: null
197
+ };
198
+ }
199
+ }
200
+
201
+ // Device probe unavailable — fall back to Factors A + B
202
+ if (page?.ok) {
203
+ if (!pageGeneric && registry === true) {
204
+ return {
205
+ status: 'ACTIVE', emoji: '🟢', confidence: 0.98,
206
+ deviceCount: null, registryExists: registry,
207
+ pageVisible, profileName
208
+ };
209
+ }
210
+ if (pageGeneric && registry === true) {
211
+ // Account exists on the servers but its public profile is
212
+ // invisible: privacy mode OR a fresh ban mid-deletion.
213
+ return {
214
+ status: 'PROFILE_HIDDEN', emoji: '🟡', confidence: 0.6,
215
+ deviceCount: null, registryExists: registry,
216
+ pageVisible: false, profileName: null
217
+ };
218
+ }
219
+ if (pageGeneric && registry === false) {
220
+ return {
221
+ status: 'OFF_WHATSAPP', emoji: '🔴', confidence: 0.9,
222
+ deviceCount: null, registryExists: registry,
223
+ pageVisible: false, profileName: null
224
+ };
225
+ }
226
+ }
227
+
228
+ // Last resort: registry alone
229
+ if (registry === true) {
230
+ return {
231
+ status: 'LIKELY_ACTIVE', emoji: '🟡', confidence: 0.55,
232
+ deviceCount: null, registryExists: registry,
233
+ pageVisible: false, profileName: null
234
+ };
235
+ }
236
+ if (registry === false) {
237
+ return {
238
+ status: 'OFF_WHATSAPP', emoji: '🔴', confidence: 0.7,
239
+ deviceCount: null, registryExists: registry,
240
+ pageVisible: false, profileName: null
241
+ };
242
+ }
243
+ return {
244
+ status: 'UNKNOWN', emoji: '❓', confidence: 0,
245
+ deviceCount: null, registryExists: null,
246
+ pageVisible: null, profileName: null
247
+ };
248
+ }
249
+
250
+ // ── The exported socket method ─────────────────────────────────────────
251
+ export const makeBanCheckerSocket = (sock) => {
252
+ sock.checkBanStatus = async (input) => {
253
+ const target = normalizeJidTarget(input);
254
+ if (!target) {
255
+ throw new Error('checkBanStatus: invalid phone number (need 8-15 digits)');
256
+ }
257
+ const [devices, registry, page] = await Promise.all([
258
+ probeIdentityDevices(sock, target),
259
+ probeRegistry(sock, target),
260
+ probeSendPage(target)
261
+ ]);
262
+ return buildVerdict(target, { devices, registry, page });
263
+ };
264
+ return sock;
265
+ };
@@ -0,0 +1,407 @@
1
+ import { unlink } from 'node:fs/promises';
2
+ import { getRawMediaUploadData } from '../Utils/index.js';
3
+ import { parseCatalogNode, parseCollectionsNode, parseOrderDetailsNode, parseProductNode, toProductNode, uploadingNecessaryImagesOfProduct } from '../Utils/business.js';
4
+ import { jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
5
+ import { getBinaryNodeChild } from '../WABinary/generic-utils.js';
6
+ import { makeMessagesRecvSocket } from './messages-recv.js';
7
+ export const makeBusinessSocket = (config) => {
8
+ const sock = makeMessagesRecvSocket(config);
9
+ const { authState, query, waUploadToServer } = sock;
10
+ const updateBusinessProfile = async (args = {}) => {
11
+ const node = [];
12
+ const simpleFields = ['address', 'email', 'description'];
13
+ node.push(...simpleFields
14
+ .filter(key => args[key] !== undefined)
15
+ .map(key => {
16
+ if (args[key] !== null && typeof args[key] !== 'string') {
17
+ throw new TypeError(`${key} must be a string or null`);
18
+ }
19
+ return {
20
+ tag: key,
21
+ attrs: {},
22
+ content: args[key] ?? ''
23
+ };
24
+ }));
25
+ if (args.websites !== undefined) {
26
+ if (!Array.isArray(args.websites) || args.websites.some(website => typeof website !== 'string')) {
27
+ throw new TypeError('websites must be an array of strings');
28
+ }
29
+ node.push(...(args.websites.length ? args.websites : ['']).map(website => ({
30
+ tag: 'website',
31
+ attrs: {},
32
+ content: website
33
+ })));
34
+ }
35
+ if (args.hours !== undefined) {
36
+ if (!args.hours || typeof args.hours.timezone !== 'string' || !Array.isArray(args.hours.days)) {
37
+ throw new TypeError('hours must contain a timezone string and days array');
38
+ }
39
+ node.push({
40
+ tag: 'business_hours',
41
+ attrs: { timezone: args.hours.timezone },
42
+ content: args.hours.days.map(dayConfig => {
43
+ if (!dayConfig || typeof dayConfig.day !== 'string' || typeof dayConfig.mode !== 'string') {
44
+ throw new TypeError('each business-hours day requires string day and mode values');
45
+ }
46
+ const base = {
47
+ tag: 'business_hours_config',
48
+ attrs: {
49
+ day_of_week: dayConfig.day,
50
+ mode: dayConfig.mode
51
+ }
52
+ };
53
+ if (dayConfig.mode === 'specific_hours') {
54
+ const { openTimeInMinutes, closeTimeInMinutes } = dayConfig;
55
+ if (!Number.isInteger(openTimeInMinutes) || !Number.isInteger(closeTimeInMinutes)) {
56
+ throw new TypeError('specific_hours requires integer openTimeInMinutes and closeTimeInMinutes');
57
+ }
58
+ return {
59
+ ...base,
60
+ attrs: {
61
+ ...base.attrs,
62
+ open_time: String(openTimeInMinutes),
63
+ close_time: String(closeTimeInMinutes)
64
+ }
65
+ };
66
+ }
67
+ return base;
68
+ })
69
+ });
70
+ }
71
+ const result = await query({
72
+ tag: 'iq',
73
+ attrs: {
74
+ to: S_WHATSAPP_NET,
75
+ type: 'set',
76
+ xmlns: 'w:biz'
77
+ },
78
+ content: [
79
+ {
80
+ tag: 'business_profile',
81
+ attrs: {
82
+ v: '3',
83
+ mutation_type: 'delta'
84
+ },
85
+ content: node
86
+ }
87
+ ]
88
+ });
89
+ return result;
90
+ };
91
+ const updateCoverPhoto = async (photo) => {
92
+ const { fileSha256, filePath } = await getRawMediaUploadData(photo, 'biz-cover-photo', config.logger);
93
+ try {
94
+ const fileSha256B64 = fileSha256.toString('base64');
95
+ const upload = await waUploadToServer(filePath, {
96
+ fileEncSha256B64: fileSha256B64,
97
+ mediaType: 'biz-cover-photo'
98
+ });
99
+ const { meta_hmac, fbid, ts } = upload || {};
100
+ if (fbid === undefined || fbid === null || !meta_hmac || ts === undefined || ts === null) {
101
+ throw new Error('Business cover photo upload returned incomplete metadata');
102
+ }
103
+ await query({
104
+ tag: 'iq',
105
+ attrs: {
106
+ to: S_WHATSAPP_NET,
107
+ type: 'set',
108
+ xmlns: 'w:biz'
109
+ },
110
+ content: [
111
+ {
112
+ tag: 'business_profile',
113
+ attrs: {
114
+ v: '3',
115
+ mutation_type: 'delta'
116
+ },
117
+ content: [
118
+ {
119
+ tag: 'cover_photo',
120
+ attrs: { id: String(fbid), op: 'update', token: String(meta_hmac), ts: String(ts) }
121
+ }
122
+ ]
123
+ }
124
+ ]
125
+ });
126
+ return fbid;
127
+ }
128
+ finally {
129
+ await unlink(filePath).catch(() => undefined);
130
+ }
131
+ };
132
+ const removeCoverPhoto = async (id) => {
133
+ return await query({
134
+ tag: 'iq',
135
+ attrs: {
136
+ to: S_WHATSAPP_NET,
137
+ type: 'set',
138
+ xmlns: 'w:biz'
139
+ },
140
+ content: [
141
+ {
142
+ tag: 'business_profile',
143
+ attrs: {
144
+ v: '3',
145
+ mutation_type: 'delta'
146
+ },
147
+ content: [
148
+ {
149
+ tag: 'cover_photo',
150
+ attrs: { op: 'delete', id }
151
+ }
152
+ ]
153
+ }
154
+ ]
155
+ });
156
+ };
157
+ const getCatalog = async ({ jid, limit, cursor }) => {
158
+ jid = jid || authState.creds.me?.id;
159
+ jid = jidNormalizedUser(jid);
160
+ const queryParamNodes = [
161
+ {
162
+ tag: 'limit',
163
+ attrs: {},
164
+ content: Buffer.from((limit || 10).toString())
165
+ },
166
+ {
167
+ tag: 'width',
168
+ attrs: {},
169
+ content: Buffer.from('100')
170
+ },
171
+ {
172
+ tag: 'height',
173
+ attrs: {},
174
+ content: Buffer.from('100')
175
+ }
176
+ ];
177
+ if (cursor) {
178
+ queryParamNodes.push({
179
+ tag: 'after',
180
+ attrs: {},
181
+ content: cursor
182
+ });
183
+ }
184
+ const result = await query({
185
+ tag: 'iq',
186
+ attrs: {
187
+ to: S_WHATSAPP_NET,
188
+ type: 'get',
189
+ xmlns: 'w:biz:catalog'
190
+ },
191
+ content: [
192
+ {
193
+ tag: 'product_catalog',
194
+ attrs: {
195
+ jid,
196
+ allow_shop_source: 'true'
197
+ },
198
+ content: queryParamNodes
199
+ }
200
+ ]
201
+ });
202
+ return parseCatalogNode(result);
203
+ };
204
+ const getCollections = async (jid, limit = 51) => {
205
+ jid = jid || authState.creds.me?.id;
206
+ jid = jidNormalizedUser(jid);
207
+ const result = await query({
208
+ tag: 'iq',
209
+ attrs: {
210
+ to: S_WHATSAPP_NET,
211
+ type: 'get',
212
+ xmlns: 'w:biz:catalog',
213
+ smax_id: '35'
214
+ },
215
+ content: [
216
+ {
217
+ tag: 'collections',
218
+ attrs: {
219
+ biz_jid: jid
220
+ },
221
+ content: [
222
+ {
223
+ tag: 'collection_limit',
224
+ attrs: {},
225
+ content: Buffer.from(limit.toString())
226
+ },
227
+ {
228
+ tag: 'item_limit',
229
+ attrs: {},
230
+ content: Buffer.from(limit.toString())
231
+ },
232
+ {
233
+ tag: 'width',
234
+ attrs: {},
235
+ content: Buffer.from('100')
236
+ },
237
+ {
238
+ tag: 'height',
239
+ attrs: {},
240
+ content: Buffer.from('100')
241
+ }
242
+ ]
243
+ }
244
+ ]
245
+ });
246
+ return parseCollectionsNode(result);
247
+ };
248
+ const getOrderDetails = async (orderId, tokenBase64) => {
249
+ const result = await query({
250
+ tag: 'iq',
251
+ attrs: {
252
+ to: S_WHATSAPP_NET,
253
+ type: 'get',
254
+ xmlns: 'fb:thrift_iq',
255
+ smax_id: '5'
256
+ },
257
+ content: [
258
+ {
259
+ tag: 'order',
260
+ attrs: {
261
+ op: 'get',
262
+ id: orderId
263
+ },
264
+ content: [
265
+ {
266
+ tag: 'image_dimensions',
267
+ attrs: {},
268
+ content: [
269
+ {
270
+ tag: 'width',
271
+ attrs: {},
272
+ content: Buffer.from('100')
273
+ },
274
+ {
275
+ tag: 'height',
276
+ attrs: {},
277
+ content: Buffer.from('100')
278
+ }
279
+ ]
280
+ },
281
+ {
282
+ tag: 'token',
283
+ attrs: {},
284
+ content: Buffer.from(tokenBase64)
285
+ }
286
+ ]
287
+ }
288
+ ]
289
+ });
290
+ return parseOrderDetailsNode(result);
291
+ };
292
+ const productUpdate = async (productId, update) => {
293
+ update = await uploadingNecessaryImagesOfProduct(update, waUploadToServer);
294
+ const editNode = toProductNode(productId, update);
295
+ const result = await query({
296
+ tag: 'iq',
297
+ attrs: {
298
+ to: S_WHATSAPP_NET,
299
+ type: 'set',
300
+ xmlns: 'w:biz:catalog'
301
+ },
302
+ content: [
303
+ {
304
+ tag: 'product_catalog_edit',
305
+ attrs: { v: '1' },
306
+ content: [
307
+ editNode,
308
+ {
309
+ tag: 'width',
310
+ attrs: {},
311
+ content: '100'
312
+ },
313
+ {
314
+ tag: 'height',
315
+ attrs: {},
316
+ content: '100'
317
+ }
318
+ ]
319
+ }
320
+ ]
321
+ });
322
+ const productCatalogEditNode = getBinaryNodeChild(result, 'product_catalog_edit');
323
+ const productNode = getBinaryNodeChild(productCatalogEditNode, 'product');
324
+ return parseProductNode(productNode);
325
+ };
326
+ const productCreate = async (create) => {
327
+ // ensure isHidden is defined
328
+ create.isHidden = !!create.isHidden;
329
+ create = await uploadingNecessaryImagesOfProduct(create, waUploadToServer);
330
+ const createNode = toProductNode(undefined, create);
331
+ const result = await query({
332
+ tag: 'iq',
333
+ attrs: {
334
+ to: S_WHATSAPP_NET,
335
+ type: 'set',
336
+ xmlns: 'w:biz:catalog'
337
+ },
338
+ content: [
339
+ {
340
+ tag: 'product_catalog_add',
341
+ attrs: { v: '1' },
342
+ content: [
343
+ createNode,
344
+ {
345
+ tag: 'width',
346
+ attrs: {},
347
+ content: '100'
348
+ },
349
+ {
350
+ tag: 'height',
351
+ attrs: {},
352
+ content: '100'
353
+ }
354
+ ]
355
+ }
356
+ ]
357
+ });
358
+ const productCatalogAddNode = getBinaryNodeChild(result, 'product_catalog_add');
359
+ const productNode = getBinaryNodeChild(productCatalogAddNode, 'product');
360
+ return parseProductNode(productNode);
361
+ };
362
+ const productDelete = async (productIds) => {
363
+ const result = await query({
364
+ tag: 'iq',
365
+ attrs: {
366
+ to: S_WHATSAPP_NET,
367
+ type: 'set',
368
+ xmlns: 'w:biz:catalog'
369
+ },
370
+ content: [
371
+ {
372
+ tag: 'product_catalog_delete',
373
+ attrs: { v: '1' },
374
+ content: productIds.map(id => ({
375
+ tag: 'product',
376
+ attrs: {},
377
+ content: [
378
+ {
379
+ tag: 'id',
380
+ attrs: {},
381
+ content: Buffer.from(id)
382
+ }
383
+ ]
384
+ }))
385
+ }
386
+ ]
387
+ });
388
+ const productCatalogDelNode = getBinaryNodeChild(result, 'product_catalog_delete');
389
+ return {
390
+ deleted: +(productCatalogDelNode?.attrs.deleted_count || 0)
391
+ };
392
+ };
393
+ return {
394
+ ...sock,
395
+ logger: config.logger,
396
+ getOrderDetails,
397
+ getCatalog,
398
+ getCollections,
399
+ productCreate,
400
+ productDelete,
401
+ productUpdate,
402
+ updateBussinesProfile: updateBusinessProfile,
403
+ updateBusinessProfile,
404
+ updateCoverPhoto,
405
+ removeCoverPhoto
406
+ };
407
+ };