@vanzxy/baileys 2.0.0

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 (281) hide show
  1. package/NOTICE.md +111 -0
  2. package/README.md +830 -0
  3. package/WAProto/index.d.ts +9 -0
  4. package/WAProto/index.js +142036 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.d.ts +152 -0
  7. package/lib/Defaults/index.js +179 -0
  8. package/lib/Framework/Bot.js +209 -0
  9. package/lib/Framework/Context.js +90 -0
  10. package/lib/Framework/MediaManager.js +152 -0
  11. package/lib/Framework/SessionManager.js +34 -0
  12. package/lib/Framework/StatsManager.js +120 -0
  13. package/lib/Framework/Store/SQLiteStore.js +74 -0
  14. package/lib/Framework/index.js +11 -0
  15. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  16. package/lib/Signal/Group/ciphertext-message.js +12 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  20. package/lib/Signal/Group/group_cipher.js +82 -0
  21. package/lib/Signal/Group/index.d.ts +11 -0
  22. package/lib/Signal/Group/index.js +12 -0
  23. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  24. package/lib/Signal/Group/keyhelper.js +18 -0
  25. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  26. package/lib/Signal/Group/sender-chain-key.js +26 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  29. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  30. package/lib/Signal/Group/sender-key-message.js +66 -0
  31. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  32. package/lib/Signal/Group/sender-key-name.js +48 -0
  33. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  34. package/lib/Signal/Group/sender-key-record.js +41 -0
  35. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  36. package/lib/Signal/Group/sender-key-state.js +84 -0
  37. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  38. package/lib/Signal/Group/sender-message-key.js +26 -0
  39. package/lib/Signal/libsignal.d.ts +54 -0
  40. package/lib/Signal/libsignal.js +431 -0
  41. package/lib/Signal/lid-mapping.d.ts +20 -0
  42. package/lib/Signal/lid-mapping.js +277 -0
  43. package/lib/Socket/Client/index.d.ts +2 -0
  44. package/lib/Socket/Client/index.js +3 -0
  45. package/lib/Socket/Client/types.d.ts +5 -0
  46. package/lib/Socket/Client/types.js +11 -0
  47. package/lib/Socket/Client/websocket.d.ts +12 -0
  48. package/lib/Socket/Client/websocket.js +54 -0
  49. package/lib/Socket/business.d.ts +395 -0
  50. package/lib/Socket/business.js +380 -0
  51. package/lib/Socket/chats.d.ts +136 -0
  52. package/lib/Socket/chats.js +1328 -0
  53. package/lib/Socket/communities.d.ts +561 -0
  54. package/lib/Socket/communities.js +434 -0
  55. package/lib/Socket/dugong.d.ts +117 -0
  56. package/lib/Socket/dugong.js +799 -0
  57. package/lib/Socket/groups.d.ts +285 -0
  58. package/lib/Socket/groups.js +355 -0
  59. package/lib/Socket/index.d.ts +531 -0
  60. package/lib/Socket/index.js +34 -0
  61. package/lib/Socket/messages-recv.d.ts +333 -0
  62. package/lib/Socket/messages-recv.js +1782 -0
  63. package/lib/Socket/messages-send.d.ts +329 -0
  64. package/lib/Socket/messages-send.js +1383 -0
  65. package/lib/Socket/mex.d.ts +1 -0
  66. package/lib/Socket/mex.js +42 -0
  67. package/lib/Socket/newsletter.d.ts +281 -0
  68. package/lib/Socket/newsletter.js +321 -0
  69. package/lib/Socket/socket.d.ts +60 -0
  70. package/lib/Socket/socket.js +1001 -0
  71. package/lib/Socket/username.js +153 -0
  72. package/lib/Store/index.d.ts +3 -0
  73. package/lib/Store/index.js +4 -0
  74. package/lib/Store/make-in-memory-store.d.ts +62 -0
  75. package/lib/Store/make-in-memory-store.js +429 -0
  76. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  77. package/lib/Store/make-ordered-dictionary.js +79 -0
  78. package/lib/Store/object-repository.d.ts +10 -0
  79. package/lib/Store/object-repository.js +24 -0
  80. package/lib/Types/Auth.d.ts +117 -0
  81. package/lib/Types/Auth.js +2 -0
  82. package/lib/Types/Bussines.d.ts +25 -0
  83. package/lib/Types/Bussines.js +2 -0
  84. package/lib/Types/Call.d.ts +15 -0
  85. package/lib/Types/Call.js +2 -0
  86. package/lib/Types/Chat.d.ts +124 -0
  87. package/lib/Types/Chat.js +8 -0
  88. package/lib/Types/Contact.d.ts +26 -0
  89. package/lib/Types/Contact.js +2 -0
  90. package/lib/Types/Events.d.ts +256 -0
  91. package/lib/Types/Events.js +2 -0
  92. package/lib/Types/GroupMetadata.d.ts +71 -0
  93. package/lib/Types/GroupMetadata.js +2 -0
  94. package/lib/Types/Label.d.ts +2 -0
  95. package/lib/Types/Label.js +25 -0
  96. package/lib/Types/LabelAssociation.d.ts +2 -0
  97. package/lib/Types/LabelAssociation.js +7 -0
  98. package/lib/Types/Message.d.ts +11 -0
  99. package/lib/Types/Message.js +18 -0
  100. package/lib/Types/Mex.d.ts +2 -0
  101. package/lib/Types/Mex.js +39 -0
  102. package/lib/Types/Product.d.ts +79 -0
  103. package/lib/Types/Product.js +2 -0
  104. package/lib/Types/RichType.d.ts +2 -0
  105. package/lib/Types/RichType.js +23 -0
  106. package/lib/Types/Signal.d.ts +87 -0
  107. package/lib/Types/Signal.js +2 -0
  108. package/lib/Types/Socket.d.ts +136 -0
  109. package/lib/Types/Socket.js +2 -0
  110. package/lib/Types/State.d.ts +5 -0
  111. package/lib/Types/State.js +56 -0
  112. package/lib/Types/USync.d.ts +26 -0
  113. package/lib/Types/USync.js +2 -0
  114. package/lib/Types/index.d.ts +66 -0
  115. package/lib/Types/index.js +26 -0
  116. package/lib/Utils/A2UI.js +277 -0
  117. package/lib/Utils/MessageBuilder.js +4405 -0
  118. package/lib/Utils/MessageBuilder_d.ts +411 -0
  119. package/lib/Utils/PersistentStore.js +592 -0
  120. package/lib/Utils/PersistentStore_d.ts +60 -0
  121. package/lib/Utils/anti-delete.d.ts +74 -0
  122. package/lib/Utils/anti-delete.js +222 -0
  123. package/lib/Utils/auth-utils.d.ts +57 -0
  124. package/lib/Utils/auth-utils.js +307 -0
  125. package/lib/Utils/auto-reply.d.ts +47 -0
  126. package/lib/Utils/auto-reply.js +158 -0
  127. package/lib/Utils/baileys-event-stream.d.ts +8 -0
  128. package/lib/Utils/baileys-event-stream.js +62 -0
  129. package/lib/Utils/browser-utils.d.ts +8 -0
  130. package/lib/Utils/browser-utils.js +28 -0
  131. package/lib/Utils/business.d.ts +49 -0
  132. package/lib/Utils/business.js +240 -0
  133. package/lib/Utils/button-helper-utils.js +314 -0
  134. package/lib/Utils/button-sender.js +824 -0
  135. package/lib/Utils/chat-control.d.ts +159 -0
  136. package/lib/Utils/chat-control.js +232 -0
  137. package/lib/Utils/chat-history-helpers.d.ts +21 -0
  138. package/lib/Utils/chat-history-helpers.js +71 -0
  139. package/lib/Utils/chat-utils.d.ts +407 -0
  140. package/lib/Utils/chat-utils.js +886 -0
  141. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  142. package/lib/Utils/companion-reg-client-utils.js +40 -0
  143. package/lib/Utils/crypto.d.ts +41 -0
  144. package/lib/Utils/crypto.js +148 -0
  145. package/lib/Utils/decode-wa-message.d.ts +83 -0
  146. package/lib/Utils/decode-wa-message.js +317 -0
  147. package/lib/Utils/event-buffer.d.ts +12 -0
  148. package/lib/Utils/event-buffer.js +636 -0
  149. package/lib/Utils/generics.d.ts +69 -0
  150. package/lib/Utils/generics.js +439 -0
  151. package/lib/Utils/history.d.ts +90 -0
  152. package/lib/Utils/history.js +147 -0
  153. package/lib/Utils/identity-change-handler.d.ts +13 -0
  154. package/lib/Utils/identity-change-handler.js +50 -0
  155. package/lib/Utils/index.d.ts +39 -0
  156. package/lib/Utils/index.js +46 -0
  157. package/lib/Utils/link-preview.d.ts +12 -0
  158. package/lib/Utils/link-preview.js +85 -0
  159. package/lib/Utils/logger.d.ts +2 -0
  160. package/lib/Utils/logger.js +3 -0
  161. package/lib/Utils/lt-hash.d.ts +12 -0
  162. package/lib/Utils/lt-hash.js +27 -0
  163. package/lib/Utils/make-mutex.d.ts +6 -0
  164. package/lib/Utils/make-mutex.js +33 -0
  165. package/lib/Utils/media-messages.d.ts +18 -0
  166. package/lib/Utils/media-messages.js +71 -0
  167. package/lib/Utils/media-set.d.ts +13 -0
  168. package/lib/Utils/media-set.js +172 -0
  169. package/lib/Utils/message-kind.js +139 -0
  170. package/lib/Utils/message-retry-manager.d.ts +79 -0
  171. package/lib/Utils/message-retry-manager.js +265 -0
  172. package/lib/Utils/message-search.d.ts +44 -0
  173. package/lib/Utils/message-search.js +189 -0
  174. package/lib/Utils/messages-media.d.ts +135 -0
  175. package/lib/Utils/messages-media.js +869 -0
  176. package/lib/Utils/messages.d.ts +44 -0
  177. package/lib/Utils/messages.js +2155 -0
  178. package/lib/Utils/noise-handler.d.ts +20 -0
  179. package/lib/Utils/noise-handler.js +201 -0
  180. package/lib/Utils/offline-node-processor.d.ts +9 -0
  181. package/lib/Utils/offline-node-processor.js +40 -0
  182. package/lib/Utils/past-participants.d.ts +14 -0
  183. package/lib/Utils/past-participants.js +40 -0
  184. package/lib/Utils/pre-key-manager.d.ts +25 -0
  185. package/lib/Utils/pre-key-manager.js +106 -0
  186. package/lib/Utils/process-message.d.ts +82 -0
  187. package/lib/Utils/process-message.js +809 -0
  188. package/lib/Utils/reporting-utils.d.ts +12 -0
  189. package/lib/Utils/reporting-utils.js +258 -0
  190. package/lib/Utils/rich-message-utils.d.ts +48 -0
  191. package/lib/Utils/rich-message-utils.js +445 -0
  192. package/lib/Utils/scheduling.d.ts +42 -0
  193. package/lib/Utils/scheduling.js +140 -0
  194. package/lib/Utils/signal.d.ts +82 -0
  195. package/lib/Utils/signal.js +201 -0
  196. package/lib/Utils/stanza-ack.d.ts +16 -0
  197. package/lib/Utils/stanza-ack.js +38 -0
  198. package/lib/Utils/status.d.ts +50 -0
  199. package/lib/Utils/status.js +108 -0
  200. package/lib/Utils/stickerpack.d.ts +51 -0
  201. package/lib/Utils/stickerpack.js +275 -0
  202. package/lib/Utils/sync-action-utils.d.ts +2 -0
  203. package/lib/Utils/sync-action-utils.js +49 -0
  204. package/lib/Utils/tc-token-utils.d.ts +29 -0
  205. package/lib/Utils/tc-token-utils.js +163 -0
  206. package/lib/Utils/templates.d.ts +76 -0
  207. package/lib/Utils/templates.js +151 -0
  208. package/lib/Utils/use-cache-manager-auth-state.d.ts +13 -0
  209. package/lib/Utils/use-cache-manager-auth-state.js +82 -0
  210. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  211. package/lib/Utils/use-multi-file-auth-state.js +167 -0
  212. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  213. package/lib/Utils/use-single-file-auth-state.js +114 -0
  214. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  215. package/lib/Utils/use-sqlite-auth-state.js +170 -0
  216. package/lib/Utils/validate-connection.d.ts +42 -0
  217. package/lib/Utils/validate-connection.js +199 -0
  218. package/lib/Utils/vcard.d.ts +58 -0
  219. package/lib/Utils/vcard.js +105 -0
  220. package/lib/VoIP/audio-feeder.d.ts +15 -0
  221. package/lib/VoIP/audio-feeder.js +132 -0
  222. package/lib/VoIP/index.js +277 -0
  223. package/lib/VoIP/relay-transport.d.ts +43 -0
  224. package/lib/VoIP/relay-transport.js +559 -0
  225. package/lib/VoIP/signaling.js +624 -0
  226. package/lib/VoIP/types.d.ts +69 -0
  227. package/lib/VoIP/types.js +17 -0
  228. package/lib/VoIP/wasm-engine.d.ts +103 -0
  229. package/lib/VoIP/wasm-engine.js +1214 -0
  230. package/lib/VoIP/worker-bootstrap.js +1042 -0
  231. package/lib/WABinary/constants.d.ts +61 -0
  232. package/lib/WABinary/constants.js +1467 -0
  233. package/lib/WABinary/decode.d.ts +9 -0
  234. package/lib/WABinary/decode.js +262 -0
  235. package/lib/WABinary/encode.d.ts +2 -0
  236. package/lib/WABinary/encode.js +220 -0
  237. package/lib/WABinary/generic-utils.d.ts +74 -0
  238. package/lib/WABinary/generic-utils.js +277 -0
  239. package/lib/WABinary/index.d.ts +5 -0
  240. package/lib/WABinary/index.js +6 -0
  241. package/lib/WABinary/jid-utils.d.ts +28 -0
  242. package/lib/WABinary/jid-utils.js +96 -0
  243. package/lib/WABinary/types.d.ts +19 -0
  244. package/lib/WABinary/types.js +2 -0
  245. package/lib/WAM/BinaryInfo.d.ts +7 -0
  246. package/lib/WAM/BinaryInfo.js +10 -0
  247. package/lib/WAM/constants.d.ts +34926 -0
  248. package/lib/WAM/constants.js +22853 -0
  249. package/lib/WAM/encode.d.ts +1 -0
  250. package/lib/WAM/encode.js +150 -0
  251. package/lib/WAM/index.d.ts +3 -0
  252. package/lib/WAM/index.js +4 -0
  253. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  254. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  255. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  256. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +63 -0
  257. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  258. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  259. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  260. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  261. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  262. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  263. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  264. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  265. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  266. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  267. package/lib/WAUSync/Protocols/index.d.ts +7 -0
  268. package/lib/WAUSync/Protocols/index.js +8 -0
  269. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  270. package/lib/WAUSync/USyncQuery.js +122 -0
  271. package/lib/WAUSync/USyncUser.d.ts +16 -0
  272. package/lib/WAUSync/USyncUser.js +31 -0
  273. package/lib/WAUSync/index.d.ts +3 -0
  274. package/lib/WAUSync/index.js +4 -0
  275. package/lib/assets/wasm/loader.js +5 -0
  276. package/lib/assets/wasm/whatsapp.wasm +0 -0
  277. package/lib/assets/wasm/worker-modules.js +273 -0
  278. package/lib/index.d.ts +12 -0
  279. package/lib/index.js +20 -0
  280. package/package.json +175 -0
  281. package/postinstall-banner.js +56 -0
@@ -0,0 +1,153 @@
1
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
2
+ import { makeCommunitiesSocket } from './communities.js';
3
+ import { executeWMexQuery } from './mex.js';
4
+
5
+ // Vanz@Port (from @queenanya/baileys, originally @innovatorssoft/baileys) ---
6
+ // WhatsApp Username socket layer: check, set, pin, find, and recommend usernames.
7
+ // Query IDs below are captured from live WA Web sessions and may rotate with
8
+ // WA updates — re-capture via the proto-extract tool if a call starts failing
9
+ // with an "unexpected response structure" Boom.
10
+ export const USERNAME_QUERY_IDS = {
11
+ CHECK: '26124072630599520', // UsernameCheck
12
+ CHECK_MULTI: '27134626522840290', // UsernameCheckMulti
13
+ SET: '27108705368767936', // UsernameSet
14
+ GET: '32618050064506056', // UsernameGet
15
+ GET_RECOMMENDATIONS: '26077456248616956', // UsernameGetRecommendationsQuery
16
+ PIN_SET: '25529696019976770' // UsernamePinSet
17
+ };
18
+
19
+ export const USERNAME_CHECK_RESULT = {
20
+ SUCCESS: 'SUCCESS',
21
+ INVALID: 'INVALID'
22
+ };
23
+
24
+ export const USERNAME_SOURCE = {
25
+ FB: 'FB',
26
+ IG: 'IG',
27
+ USER_INPUT: 'USER_INPUT',
28
+ SUGGESTION: 'SUGGESTION'
29
+ };
30
+
31
+ export const makeUsernameSocket = (config) => {
32
+ const sock = makeCommunitiesSocket(config);
33
+ const { query, generateMessageTag, executeUSyncQuery } = sock;
34
+
35
+ /** Internal helper — wraps executeWMexQuery with this socket's query/tag */
36
+ const mexQuery = (variables, queryId, dataPath) => executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
37
+
38
+ // 1. Check username availability
39
+ const checkUsername = async (username, includeSuggestions = true) => {
40
+ if (!USERNAME_QUERY_IDS.CHECK) {
41
+ throw new Error('Username CHECK query_id not configured — capture a live WA session to obtain it');
42
+ }
43
+ const data = await mexQuery({ username, include_suggestions: includeSuggestions }, USERNAME_QUERY_IDS.CHECK, 'xwa2_username_check');
44
+ if (data?.result === USERNAME_CHECK_RESULT.SUCCESS) {
45
+ return { available: true, username };
46
+ }
47
+ return {
48
+ available: false,
49
+ username,
50
+ suggestions: data?.suggestions ?? [],
51
+ rejectionReasons: data?.rejection_reasons ?? [],
52
+ suggestionsEligible: data?.suggestions_eligible ?? true
53
+ };
54
+ };
55
+
56
+ // 2. Check multiple usernames at once
57
+ const checkUsernameMulti = async (usernames) => {
58
+ if (!USERNAME_QUERY_IDS.CHECK_MULTI) {
59
+ throw new Error('Username CHECK_MULTI query_id not configured');
60
+ }
61
+ return mexQuery({ usernames }, USERNAME_QUERY_IDS.CHECK_MULTI, 'xwa2_username_check_multi');
62
+ };
63
+
64
+ // 3. Set username
65
+ const setUsername = async (username, options = {}) => {
66
+ if (!USERNAME_QUERY_IDS.SET) {
67
+ throw new Error('Username SET query_id not configured — capture a live WA session to obtain it');
68
+ }
69
+ const { source = USERNAME_SOURCE.USER_INPUT, sessionId, pin } = options;
70
+ const variables = {
71
+ username,
72
+ reserved: false,
73
+ source,
74
+ ...(sessionId ? { session_id: sessionId } : {}),
75
+ ...(pin ? { pin } : {})
76
+ };
77
+ return mexQuery(variables, USERNAME_QUERY_IDS.SET, 'xwa2_username_set');
78
+ };
79
+
80
+ // 4. Delete / unset username
81
+ const deleteUsername = async () => {
82
+ if (!USERNAME_QUERY_IDS.SET) {
83
+ throw new Error('Username SET query_id not configured — capture a live WA session to obtain it');
84
+ }
85
+ return mexQuery({ username: null }, USERNAME_QUERY_IDS.SET, 'xwa2_username_delete');
86
+ };
87
+
88
+ // 5. Get own username
89
+ const getMyUsername = async () => {
90
+ if (!USERNAME_QUERY_IDS.GET) {
91
+ throw new Error('Username GET query_id not configured — capture a live WA session to obtain it');
92
+ }
93
+ const data = await mexQuery({}, USERNAME_QUERY_IDS.GET, 'xwa2_username_get');
94
+ return data?.username ?? null;
95
+ };
96
+
97
+ // 6. Pin/unpin username (requires PIN)
98
+ const setUsernamePin = async (pin) => {
99
+ if (!USERNAME_QUERY_IDS.PIN_SET) {
100
+ throw new Error('Username PIN_SET query_id not configured — capture a live WA session to obtain it');
101
+ }
102
+ return mexQuery({ pin }, USERNAME_QUERY_IDS.PIN_SET, 'xwa2_username_pin_set');
103
+ };
104
+
105
+ // 7. Find user by username (USync)
106
+ const findUserByUsername = async (username, pin) => {
107
+ const usyncQuery = new USyncQuery().withContactProtocol();
108
+ const user = new USyncUser().withUsername(username);
109
+ if (pin) user.withUsernameKey(pin);
110
+ usyncQuery.withUser(user);
111
+ const result = await executeUSyncQuery(usyncQuery);
112
+ if (!result?.list?.length) return null;
113
+ const entry = result.list[0];
114
+ if (!entry) return null;
115
+ return {
116
+ jid: entry.id,
117
+ contact: Boolean(entry.contact)
118
+ };
119
+ };
120
+
121
+ // 8. Fetch usernames of known contacts (USync)
122
+ const fetchContactUsernames = async (...jids) => {
123
+ const usyncQuery = new USyncQuery().withUsernameProtocol();
124
+ for (const jid of jids) {
125
+ usyncQuery.withUser(new USyncUser().withId(jid));
126
+ }
127
+ const result = await executeUSyncQuery(usyncQuery);
128
+ return result?.list ?? [];
129
+ };
130
+
131
+ // 9. Get username recommendations
132
+ const getUsernameRecommendations = async (source = null) => {
133
+ const variables = {};
134
+ if (source) variables.source = source;
135
+ return mexQuery(variables, USERNAME_QUERY_IDS.GET_RECOMMENDATIONS, 'xwa2_username_get_recommendations');
136
+ };
137
+
138
+ return {
139
+ ...sock,
140
+ checkUsername,
141
+ checkUsernameMulti,
142
+ setUsername,
143
+ deleteUsername,
144
+ getMyUsername,
145
+ setUsernamePin,
146
+ findUserByUsername,
147
+ fetchContactUsernames,
148
+ getUsernameRecommendations,
149
+ USERNAME_QUERY_IDS,
150
+ USERNAME_CHECK_RESULT,
151
+ USERNAME_SOURCE
152
+ };
153
+ };
@@ -0,0 +1,3 @@
1
+ export * from "./make-in-memory-store.js";
2
+ export * from "./make-ordered-dictionary.js";
3
+ export * from "./object-repository.js";
@@ -0,0 +1,4 @@
1
+ export * from './make-in-memory-store.js';
2
+ export * from './make-ordered-dictionary.js';
3
+ export * from './object-repository.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,62 @@
1
+ export function waChatKey(pin: any): {
2
+ key: (c: any) => string;
3
+ compare: (k1: any, k2: any) => any;
4
+ };
5
+ export function waMessageID(m: any): any;
6
+ export namespace waLabelAssociationKey {
7
+ function key(la: any): any;
8
+ function compare(k1: any, k2: any): any;
9
+ }
10
+ export function makeInMemoryStore(config?: {}): {
11
+ chats: any;
12
+ contacts: {};
13
+ messages: {};
14
+ groupMetadata: {};
15
+ state: {
16
+ connection: string;
17
+ };
18
+ presences: {};
19
+ labels: ObjectRepository;
20
+ labelAssociations: any;
21
+ bind: (ev: any) => void;
22
+ /** loads messages from the store, if not found -- uses the legacy connection */
23
+ loadMessages: (jid: any, count: any, cursor: any) => Promise<any>;
24
+ /**
25
+ * Get all available labels for profile
26
+ *
27
+ * Keep in mind that the list is formed from predefined tags and tags
28
+ * that were "caught" during their editing.
29
+ */
30
+ getLabels: () => ObjectRepository;
31
+ /**
32
+ * Get labels for chat
33
+ *
34
+ * @returns Label IDs
35
+ **/
36
+ getChatLabels: (chatId: any) => any;
37
+ /**
38
+ * Get labels for message
39
+ *
40
+ * @returns Label IDs
41
+ **/
42
+ getMessageLabels: (messageId: any) => any;
43
+ loadMessage: (jid: any, id: any) => Promise<any>;
44
+ mostRecentMessage: (jid: any) => Promise<any>;
45
+ fetchImageUrl: (jid: any, sock: any) => Promise<any>;
46
+ fetchGroupMetadata: (jid: any, sock: any) => Promise<any>;
47
+ fetchMessageReceipts: ({ remoteJid, id }: {
48
+ remoteJid: any;
49
+ id: any;
50
+ }) => Promise<any>;
51
+ toJSON: () => {
52
+ chats: any;
53
+ contacts: {};
54
+ messages: {};
55
+ labels: ObjectRepository;
56
+ labelAssociations: any;
57
+ };
58
+ fromJSON: (json: any) => void;
59
+ writeToFile: (path: any) => void;
60
+ readFromFile: (path: any) => void;
61
+ };
62
+ import { ObjectRepository } from './object-repository.js';
@@ -0,0 +1,429 @@
1
+ /**
2
+ * Lia@Note 03-02-26 [WIP]
3
+ * Manually converted to ESM and modified by me
4
+ * Originally based on @whiskeysockets/baileys v6.7.16
5
+ * Minor adjustments for compatibility with baileys v7 (⁠つ⁠≧⁠▽⁠≦⁠)⁠つ
6
+ */
7
+ import keyedDB from '@adiwajshing/keyed-db';
8
+ import { writeFileSync, readFileSync, existsSync } from 'fs';
9
+ import { WAProto } from '../Types/index.js';
10
+ import { LabelAssociationType } from '../Types/LabelAssociation.js';
11
+ import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
12
+ import { md5, toNumber, updateMessageWithReceipt, updateMessageWithReaction } from '../Utils/index.js';
13
+ import { jidDecode, jidNormalizedUser } from '../WABinary/index.js';
14
+ import { makeOrderedDictionary } from './make-ordered-dictionary.js';
15
+ import { ObjectRepository } from './object-repository.js';
16
+ export const waChatKey = (pin) => ({
17
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
18
+ compare: (k1, k2) => k2.localeCompare(k1)
19
+ });
20
+ export const waMessageID = (m) => m.key.id || '';
21
+ export const waLabelAssociationKey = {
22
+ key: (la) => (la.type === LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
23
+ compare: (k1, k2) => k2.localeCompare(k1)
24
+ };
25
+ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
26
+ export const makeInMemoryStore = (config = {}) => {
27
+ const socket = config.socket;
28
+ const chatKey = config.chatKey || waChatKey(true);
29
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
30
+ const logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
31
+ const KeyedDB = keyedDB?.default ?? keyedDB; // Lia@Note 03-02-26 --- Handle CJS ↔ ESM default export differences ⊂⁠(⁠・⁠ω⁠・⁠*⁠⊂⁠)
32
+ const chats = new KeyedDB(chatKey, c => c.id);
33
+ const messages = {};
34
+ const contacts = {};
35
+ const groupMetadata = {};
36
+ const presences = {};
37
+ const state = { connection: 'close' };
38
+ const labels = new ObjectRepository();
39
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
40
+ const assertMessageList = (jid) => {
41
+ if (!messages[jid]) {
42
+ messages[jid] = makeMessagesDictionary();
43
+ }
44
+ return messages[jid];
45
+ };
46
+ const contactsUpsert = (newContacts) => {
47
+ const oldContacts = new Set(Object.keys(contacts));
48
+ for (const contact of newContacts) {
49
+ oldContacts.delete(contact.id);
50
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
51
+ }
52
+ return oldContacts;
53
+ };
54
+ const labelsUpsert = (newLabels) => {
55
+ for (const label of newLabels) {
56
+ labels.upsertById(label.id, label);
57
+ }
58
+ };
59
+ /**
60
+ * binds to a BaileysEventEmitter.
61
+ * It listens to all events and constructs a state that you can query accurate data from.
62
+ * Eg. can use the store to fetch chats, contacts, messages etc.
63
+ * @param ev typically the event emitter from the socket connection
64
+ */
65
+ const bind = (ev) => {
66
+ ev.on('connection.update', update => {
67
+ Object.assign(state, update);
68
+ });
69
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
70
+ if (syncType === WAProto.HistorySync.HistorySyncType.ON_DEMAND) {
71
+ // Vanz@Fix (bug 38): was early-returning without saving anything.
72
+ // ON_DEMAND is used when loading older messages (e.g. scroll-up / .q search).
73
+ // We should at minimum merge the messages into the store.
74
+ for (const msg of newMessages) {
75
+ const jid = msg.key.remoteJidAlt || msg.key.remoteJid;
76
+ const list = assertMessageList(jid);
77
+ list.upsert(msg, 'prepend');
78
+ }
79
+ logger.debug({ messages: newMessages.length }, 'synced ON_DEMAND messages');
80
+ return;
81
+ }
82
+ if (isLatest) {
83
+ chats.clear();
84
+ for (const id in messages) {
85
+ delete messages[id];
86
+ }
87
+ }
88
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
89
+ logger.debug({ chatsAdded }, 'synced chats');
90
+ const oldContacts = contactsUpsert(newContacts);
91
+ if (isLatest) {
92
+ for (const jid of oldContacts) {
93
+ delete contacts[jid];
94
+ }
95
+ }
96
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
97
+ for (const msg of newMessages) {
98
+ const jid = msg.key.remoteJidAlt || msg.key.remoteJid;
99
+ const list = assertMessageList(jid);
100
+ list.upsert(msg, 'prepend');
101
+ }
102
+ logger.debug({ messages: newMessages.length }, 'synced messages');
103
+ });
104
+ ev.on('contacts.upsert', contacts => {
105
+ contactsUpsert(contacts);
106
+ });
107
+ ev.on('contacts.update', async (updates) => {
108
+ var _a;
109
+ for (const update of updates) {
110
+ let contact;
111
+ if (contacts[update.id]) {
112
+ contact = contacts[update.id];
113
+ }
114
+ else {
115
+ const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
116
+ const { user } = jidDecode(contactId);
117
+ return [contactId, (await md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
118
+ }));
119
+ contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
120
+ }
121
+ if (contact) {
122
+ if (update.imgUrl === 'changed') {
123
+ contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
124
+ }
125
+ else if (update.imgUrl === 'removed') {
126
+ delete contact.imgUrl;
127
+ }
128
+ }
129
+ else {
130
+ return logger.debug({ update }, 'got update for non-existant contact');
131
+ }
132
+ Object.assign(contacts[contact.id], contact);
133
+ }
134
+ });
135
+ ev.on('chats.upsert', newChats => {
136
+ chats.upsert(...newChats);
137
+ });
138
+ ev.on('chats.update', updates => {
139
+ for (let update of updates) {
140
+ const result = chats.update(update.id, chat => {
141
+ if (update.unreadCount > 0) {
142
+ update = { ...update };
143
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
144
+ }
145
+ Object.assign(chat, update);
146
+ });
147
+ if (!result) {
148
+ logger.debug({ update }, 'got update for non-existant chat');
149
+ }
150
+ }
151
+ });
152
+ ev.on('labels.edit', (label) => {
153
+ if (label.deleted) {
154
+ return labels.deleteById(label.id);
155
+ }
156
+ // WhatsApp can store only up to 20 labels
157
+ if (labels.count() < 20) {
158
+ return labels.upsertById(label.id, label);
159
+ }
160
+ logger.error('Labels count exceed');
161
+ });
162
+ ev.on('labels.association', ({ type, association }) => {
163
+ switch (type) {
164
+ case 'add':
165
+ labelAssociations.upsert(association);
166
+ break;
167
+ case 'remove':
168
+ labelAssociations.delete(association);
169
+ break;
170
+ default:
171
+ console.error(`unknown operation type [${type}]`);
172
+ }
173
+ });
174
+ ev.on('presence.update', ({ id, presences: update }) => {
175
+ presences[id] = presences[id] || {};
176
+ Object.assign(presences[id], update);
177
+ });
178
+ ev.on('chats.delete', deletions => {
179
+ for (const item of deletions) {
180
+ if (chats.get(item)) {
181
+ chats.deleteById(item);
182
+ }
183
+ }
184
+ });
185
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
186
+ switch (type) {
187
+ case 'append':
188
+ case 'notify':
189
+ for (const msg of newMessages) {
190
+ const jid = jidNormalizedUser(msg.key.remoteJidAlt || msg.key.remoteJid);
191
+ const list = assertMessageList(jid);
192
+ list.upsert(msg, 'append');
193
+ if (type === 'notify' && !chats.get(jid)) {
194
+ ev.emit('chats.upsert', [
195
+ {
196
+ id: jid,
197
+ conversationTimestamp: toNumber(msg.messageTimestamp),
198
+ unreadCount: 1
199
+ }
200
+ ]);
201
+ }
202
+ }
203
+ break;
204
+ }
205
+ });
206
+ ev.on('messages.update', updates => {
207
+ var _a;
208
+ for (const { update, key } of updates) {
209
+ const list = assertMessageList(jidNormalizedUser(key.remoteJid));
210
+ if (update === null || update === void 0 ? void 0 : update.status) {
211
+ const listStatus = (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status;
212
+ if (listStatus && (update === null || update === void 0 ? void 0 : update.status) <= listStatus) {
213
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
214
+ delete update.status;
215
+ logger.debug({ update }, 'new update object');
216
+ }
217
+ }
218
+ const result = list.updateAssign(key.id, update);
219
+ if (!result) {
220
+ logger.debug({ update }, 'got update for non-existent message');
221
+ }
222
+ }
223
+ });
224
+ ev.on('messages.delete', item => {
225
+ if ('all' in item) {
226
+ const list = messages[item.jid];
227
+ list === null || list === void 0 ? void 0 : list.clear();
228
+ }
229
+ else {
230
+ const jid = item.keys[0].remoteJidAlt || item.keys[0].remoteJid;
231
+ const list = messages[jid];
232
+ if (list) {
233
+ const idSet = new Set(item.keys.map(k => k.id));
234
+ list.filter(m => !idSet.has(m.key.id));
235
+ }
236
+ }
237
+ });
238
+ ev.on('groups.update', updates => {
239
+ for (const update of updates) {
240
+ const id = update.id;
241
+ if (groupMetadata[id]) {
242
+ Object.assign(groupMetadata[id], update);
243
+ }
244
+ else {
245
+ logger.debug({ update }, 'got update for non-existant group metadata');
246
+ }
247
+ }
248
+ });
249
+ ev.on('group-participants.update', ({ id, participants, action }) => {
250
+ const metadata = groupMetadata[id];
251
+ if (metadata) {
252
+ switch (action) {
253
+ case 'add':
254
+ metadata.participants.push(...participants.map(participant => ({ id: participant.id, phoneNumber: participant.phoneNumber, admin: participant.admin })));
255
+ break;
256
+ case 'demote':
257
+ case 'promote':
258
+ for (const participant of metadata.participants) {
259
+ for (const participantData of participants) {
260
+ if (participantData.id === participant.id || participantData.phoneNumber === participant.phoneNumber) {
261
+ participant.admin = action === 'promote' && 'admin';
262
+ }
263
+ }
264
+ }
265
+ break;
266
+ case 'remove':
267
+ const removeSet = new Set();
268
+ for (const p of participants) {
269
+ if (p.id)
270
+ removeSet.add(p.id);
271
+ if (p.phoneNumber)
272
+ removeSet.add(p.phoneNumber);
273
+ }
274
+ metadata.participants = metadata.participants.reduce((acc, p) => {
275
+ if (!removeSet.has(p.id) && !removeSet.has(p.phoneNumber))
276
+ acc.push(p);
277
+ return acc;
278
+ }, []);
279
+ break;
280
+ }
281
+ }
282
+ });
283
+ ev.on('message-receipt.update', updates => {
284
+ for (const { key, receipt } of updates) {
285
+ const obj = messages[key.remoteJidAlt || key.remoteJid];
286
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
287
+ if (msg) {
288
+ updateMessageWithReceipt(msg, receipt);
289
+ }
290
+ }
291
+ });
292
+ ev.on('messages.reaction', (reactions) => {
293
+ for (const { key, reaction } of reactions) {
294
+ const obj = messages[key.remoteJidAlt || key.remoteJid];
295
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
296
+ if (msg) {
297
+ updateMessageWithReaction(msg, reaction);
298
+ }
299
+ }
300
+ });
301
+ };
302
+ const toJSON = () => ({
303
+ chats,
304
+ contacts,
305
+ messages,
306
+ labels,
307
+ labelAssociations
308
+ });
309
+ const fromJSON = (json) => {
310
+ chats.upsert(...json.chats);
311
+ labelAssociations.upsert(...json.labelAssociations || []);
312
+ contactsUpsert(Object.values(json.contacts));
313
+ labelsUpsert(Object.values(json.labels || {}));
314
+ for (const jid in json.messages) {
315
+ const list = assertMessageList(jid);
316
+ for (const msg of json.messages[jid]) {
317
+ list.upsert(WAProto.WebMessageInfo.fromObject(msg), 'append');
318
+ }
319
+ }
320
+ };
321
+ return {
322
+ chats,
323
+ contacts,
324
+ messages,
325
+ groupMetadata,
326
+ state,
327
+ presences,
328
+ labels,
329
+ labelAssociations,
330
+ bind,
331
+ /** loads messages from the store, if not found -- uses the legacy connection */
332
+ loadMessages: async (jid, count, cursor) => {
333
+ const list = assertMessageList(jid);
334
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after';
335
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
336
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
337
+ let messages;
338
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
339
+ if (cursorValue) {
340
+ const msgIdx = list.array.findIndex(m => m.key.id === (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id));
341
+ messages = list.array.slice(0, msgIdx);
342
+ }
343
+ else {
344
+ messages = list.array;
345
+ }
346
+ const diff = count - messages.length;
347
+ if (diff < 0) {
348
+ messages = messages.slice(-count); // get the last X messages
349
+ }
350
+ }
351
+ else {
352
+ messages = [];
353
+ }
354
+ return messages;
355
+ },
356
+ /**
357
+ * Get all available labels for profile
358
+ *
359
+ * Keep in mind that the list is formed from predefined tags and tags
360
+ * that were "caught" during their editing.
361
+ */
362
+ getLabels: () => {
363
+ return labels;
364
+ },
365
+ /**
366
+ * Get labels for chat
367
+ *
368
+ * @returns Label IDs
369
+ **/
370
+ getChatLabels: (chatId) => {
371
+ return labelAssociations.filter((la) => la.chatId === chatId).all();
372
+ },
373
+ /**
374
+ * Get labels for message
375
+ *
376
+ * @returns Label IDs
377
+ **/
378
+ getMessageLabels: (messageId) => {
379
+ const associations = labelAssociations
380
+ .filter((la) => la.messageId === messageId)
381
+ .all();
382
+ return associations.map(({ labelId }) => labelId);
383
+ },
384
+ loadMessage: async (jid, id) => { var _a; return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id); },
385
+ mostRecentMessage: async (jid) => {
386
+ var _a;
387
+ const message = (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0];
388
+ return message;
389
+ },
390
+ fetchImageUrl: async (jid, sock) => {
391
+ const contact = contacts[jid];
392
+ if (!contact) {
393
+ return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid);
394
+ }
395
+ if (typeof contact.imgUrl === 'undefined') {
396
+ contact.imgUrl = await (sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid));
397
+ }
398
+ return contact.imgUrl;
399
+ },
400
+ fetchGroupMetadata: async (jid, sock) => {
401
+ if (!groupMetadata[jid]) {
402
+ const metadata = await (sock === null || sock === void 0 ? void 0 : sock.groupMetadata(jid));
403
+ if (metadata) {
404
+ groupMetadata[jid] = metadata;
405
+ }
406
+ }
407
+ return groupMetadata[jid];
408
+ },
409
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
410
+ const list = messages[remoteJid];
411
+ const msg = list === null || list === void 0 ? void 0 : list.get(id);
412
+ return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
413
+ },
414
+ toJSON,
415
+ fromJSON,
416
+ writeToFile: (path) => {
417
+ writeFileSync(path, JSON.stringify(toJSON()));
418
+ },
419
+ readFromFile: (path) => {
420
+ if (existsSync(path)) {
421
+ logger.debug({ path }, 'reading from file');
422
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' });
423
+ const json = JSON.parse(jsonStr);
424
+ fromJSON(json);
425
+ }
426
+ }
427
+ };
428
+ };
429
+ //# sourceMappingURL=make-in-memory-store.js.map
@@ -0,0 +1,12 @@
1
+ export function makeOrderedDictionary(idGetter: any): {
2
+ array: any[];
3
+ get: (id: any) => any;
4
+ upsert: (item: any, mode: any) => void;
5
+ update: (item: any) => boolean;
6
+ remove: (item: any) => boolean;
7
+ updateAssign: (id: any, update: any) => boolean;
8
+ clear: () => void;
9
+ filter: (contain: any) => void;
10
+ toJSON: () => any[];
11
+ fromJSON: (newItems: any) => void;
12
+ };