@baileys-md/baileys 11.0.3 → 11.1.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 (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  3. package/WAProto/index.js +4182 -13516
  4. package/WASignalGroup/GroupProtocol.js +1697 -0
  5. package/WASignalGroup/ciphertext_message.js +16 -0
  6. package/WASignalGroup/group_cipher.js +120 -0
  7. package/WASignalGroup/group_session_builder.js +46 -0
  8. package/WASignalGroup/index.js +5 -0
  9. package/WASignalGroup/keyhelper.js +21 -0
  10. package/WASignalGroup/protobufs.js +3 -0
  11. package/WASignalGroup/queue_job.js +69 -0
  12. package/WASignalGroup/sender_chain_key.js +50 -0
  13. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  14. package/WASignalGroup/sender_key_message.js +92 -0
  15. package/WASignalGroup/sender_key_name.js +70 -0
  16. package/WASignalGroup/sender_key_record.js +56 -0
  17. package/WASignalGroup/sender_key_state.js +129 -0
  18. package/{lib/Signal/Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -4
  19. package/lib/Defaults/baileys-version.json +3 -0
  20. package/lib/Defaults/index.js +71 -52
  21. package/lib/Defaults/{phonenumber-mcc.js → phonenumber-mcc.json} +1 -1
  22. package/lib/Signal/libsignal.js +61 -41
  23. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  24. package/lib/Socket/Client/index.js +19 -3
  25. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  26. package/lib/Socket/Client/web-socket-client.js +62 -0
  27. package/lib/Socket/business.js +42 -37
  28. package/lib/Socket/chats.js +187 -194
  29. package/lib/Socket/groups.js +90 -87
  30. package/lib/Socket/index.js +8 -7
  31. package/lib/Socket/messages-recv.js +335 -360
  32. package/lib/Socket/messages-send.js +279 -156
  33. package/lib/Socket/newsletter.js +213 -144
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +161 -128
  36. package/lib/Socket/usync.js +26 -19
  37. package/lib/Store/index.js +8 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/{Utils → Store}/make-in-memory-store.js +27 -19
  40. package/lib/Store/make-mongo-store.js +567 -0
  41. package/lib/{Utils → Store}/make-ordered-dictionary.js +5 -2
  42. package/lib/{Utils → Store}/object-repository.js +4 -1
  43. package/lib/Types/Auth.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +4 -8
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +5 -3
  50. package/lib/Types/LabelAssociation.js +5 -3
  51. package/lib/Types/Message.js +7 -7
  52. package/lib/Types/Newsletter.js +17 -30
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +2 -3
  56. package/lib/Types/State.js +2 -2
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +31 -15
  59. package/lib/Utils/auth-utils.js +47 -31
  60. package/lib/Utils/baileys-event-stream.js +22 -15
  61. package/lib/Utils/business.js +69 -66
  62. package/lib/Utils/chat-utils.js +195 -200
  63. package/lib/Utils/crypto.js +85 -70
  64. package/lib/Utils/decode-wa-message.js +51 -46
  65. package/lib/Utils/event-buffer.js +46 -36
  66. package/lib/Utils/generics.js +188 -116
  67. package/lib/Utils/history.js +46 -37
  68. package/lib/Utils/index.js +33 -19
  69. package/lib/Utils/link-preview.js +55 -14
  70. package/lib/Utils/logger.js +7 -3
  71. package/lib/Utils/lt-hash.js +26 -23
  72. package/lib/Utils/make-mutex.js +10 -7
  73. package/lib/Utils/messages-media.js +368 -239
  74. package/lib/Utils/messages.js +510 -278
  75. package/lib/Utils/noise-handler.js +31 -22
  76. package/lib/Utils/process-message.js +148 -144
  77. package/lib/Utils/signal.js +64 -71
  78. package/lib/Utils/use-multi-file-auth-state.js +32 -14
  79. package/lib/Utils/validate-connection.js +115 -72
  80. package/lib/WABinary/constants.js +20 -1281
  81. package/lib/WABinary/decode.js +52 -15
  82. package/lib/WABinary/encode.js +48 -14
  83. package/lib/WABinary/generic-utils.js +39 -31
  84. package/lib/WABinary/index.js +21 -6
  85. package/lib/WABinary/jid-utils.js +40 -23
  86. package/lib/WABinary/types.js +2 -2
  87. package/lib/WAM/BinaryInfo.js +5 -2
  88. package/lib/WAM/constants.js +2366 -2257
  89. package/lib/WAM/encode.js +21 -17
  90. package/lib/WAM/index.js +19 -4
  91. package/lib/WAUSync/Protocols/USyncContactProtocol.js +11 -8
  92. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  93. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  94. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  95. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  96. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +6 -3
  97. package/lib/WAUSync/Protocols/index.js +20 -5
  98. package/lib/WAUSync/USyncQuery.js +32 -34
  99. package/lib/WAUSync/USyncUser.js +5 -2
  100. package/lib/WAUSync/index.js +19 -4
  101. package/lib/index.js +33 -11
  102. package/package.json +61 -21
  103. package/WAProto/GenerateStatics.sh +0 -3
  104. package/WAProto/WAProto.proto +0 -4633
  105. package/WAProto/fix-imports.js +0 -29
  106. package/lib/Defaults/baileys-version.js +0 -1
  107. package/lib/Signal/Group/ciphertext-message.js +0 -12
  108. package/lib/Signal/Group/group-session-builder.js +0 -30
  109. package/lib/Signal/Group/group_cipher.js +0 -94
  110. package/lib/Signal/Group/index.js +0 -12
  111. package/lib/Signal/Group/keyhelper.js +0 -19
  112. package/lib/Signal/Group/queue-job.js +0 -54
  113. package/lib/Signal/Group/sender-chain-key.js +0 -32
  114. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  115. package/lib/Signal/Group/sender-key-message.js +0 -67
  116. package/lib/Signal/Group/sender-key-name.js +0 -48
  117. package/lib/Signal/Group/sender-key-record.js +0 -50
  118. package/lib/Signal/Group/sender-key-state.js +0 -96
  119. package/lib/Socket/Client/types.js +0 -11
  120. package/lib/Socket/Client/websocket.js +0 -50
  121. package/lib/Socket/communities.js +0 -351
  122. package/lib/Socket/mex.js +0 -42
@@ -1,22 +1,25 @@
1
- import { Boom } from '@hapi/boom';
2
- import { proto } from '../../WAProto/index.js';
3
- import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults/index.js';
4
- import { decodeBinaryNode } from '../WABinary/index.js';
5
- import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto.js';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeNoiseHandler = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WAProto_1 = require("../../WAProto");
6
+ const Defaults_1 = require("../Defaults");
7
+ const WABinary_1 = require("../WABinary");
8
+ const crypto_1 = require("./crypto");
6
9
  const generateIV = (counter) => {
7
10
  const iv = new ArrayBuffer(12);
8
11
  new DataView(iv).setUint32(8, counter);
9
12
  return new Uint8Array(iv);
10
13
  };
11
- export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
14
+ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }) => {
12
15
  logger = logger.child({ class: 'ns' });
13
16
  const authenticate = (data) => {
14
17
  if (!isFinished) {
15
- hash = sha256(Buffer.concat([hash, data]));
18
+ hash = (0, crypto_1.sha256)(Buffer.concat([hash, data]));
16
19
  }
17
20
  };
18
21
  const encrypt = (plaintext) => {
19
- const result = aesEncryptGCM(plaintext, encKey, generateIV(writeCounter), hash);
22
+ const result = (0, crypto_1.aesEncryptGCM)(plaintext, encKey, generateIV(writeCounter), hash);
20
23
  writeCounter += 1;
21
24
  authenticate(result);
22
25
  return result;
@@ -25,7 +28,7 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
25
28
  // before the handshake is finished, we use the same counter
26
29
  // after handshake, the counters are different
27
30
  const iv = generateIV(isFinished ? readCounter : writeCounter);
28
- const result = aesDecryptGCM(ciphertext, decKey, iv, hash);
31
+ const result = (0, crypto_1.aesDecryptGCM)(ciphertext, decKey, iv, hash);
29
32
  if (isFinished) {
30
33
  readCounter += 1;
31
34
  }
@@ -36,7 +39,7 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
36
39
  return result;
37
40
  };
38
41
  const localHKDF = async (data) => {
39
- const key = await hkdf(Buffer.from(data), 64, { salt, info: '' });
42
+ const key = await (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
40
43
  return [key.slice(0, 32), key.slice(32)];
41
44
  };
42
45
  const mixIntoKey = async (data) => {
@@ -56,8 +59,8 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
56
59
  writeCounter = 0;
57
60
  isFinished = true;
58
61
  };
59
- const data = Buffer.from(NOISE_MODE);
60
- let hash = data.byteLength === 32 ? data : sha256(data);
62
+ const data = Buffer.from(Defaults_1.NOISE_MODE);
63
+ let hash = data.byteLength === 32 ? data : (0, crypto_1.sha256)(data);
61
64
  let salt = hash;
62
65
  let encKey = hash;
63
66
  let decKey = hash;
@@ -76,17 +79,22 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
76
79
  finishInit,
77
80
  processHandshake: async ({ serverHello }, noiseKey) => {
78
81
  authenticate(serverHello.ephemeral);
79
- await mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral));
82
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
80
83
  const decStaticContent = decrypt(serverHello.static);
81
- await mixIntoKey(Curve.sharedKey(privateKey, decStaticContent));
84
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
82
85
  const certDecoded = decrypt(serverHello.payload);
83
- const { intermediate: certIntermediate } = proto.CertChain.decode(certDecoded);
84
- const { issuerSerial } = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
85
- if (issuerSerial !== WA_CERT_DETAILS.SERIAL) {
86
- throw new Boom('certification match failed', { statusCode: 400 });
86
+ if (mobile) {
87
+ WAProto_1.proto.CertChain.NoiseCertificate.decode(certDecoded);
88
+ }
89
+ else {
90
+ const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
91
+ const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
92
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
93
+ throw new boom_1.Boom('certification match failed', { statusCode: 400 });
94
+ }
87
95
  }
88
96
  const keyEnc = encrypt(noiseKey.public);
89
- await mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
97
+ await mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
90
98
  return keyEnc;
91
99
  },
92
100
  encodeFrame: (data) => {
@@ -118,6 +126,7 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
118
126
  return frame;
119
127
  },
120
128
  decodeFrame: async (newData, onFrame) => {
129
+ var _a;
121
130
  // the binary protocol uses its own framing mechanism
122
131
  // on top of the WS frames
123
132
  // so we get this data and separate out the frames
@@ -134,13 +143,13 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
134
143
  inBytes = inBytes.slice(size + 3);
135
144
  if (isFinished) {
136
145
  const result = decrypt(frame);
137
- frame = await decodeBinaryNode(result);
146
+ frame = await (0, WABinary_1.decodeBinaryNode)(result);
138
147
  }
139
- logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
148
+ logger.trace({ msg: (_a = frame === null || frame === void 0 ? void 0 : frame.attrs) === null || _a === void 0 ? void 0 : _a.id }, 'recv frame');
140
149
  onFrame(frame);
141
150
  size = getBytesSize();
142
151
  }
143
152
  }
144
153
  };
145
154
  };
146
- //# sourceMappingURL=noise-handler.js.map
155
+ exports.makeNoiseHandler = makeNoiseHandler;
@@ -1,28 +1,34 @@
1
- import { proto } from '../../WAProto/index.js';
2
- import { WAMessageStubType } from '../Types/index.js';
3
- import { getContentType, normalizeMessageContent } from '../Utils/messages.js';
4
- import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
5
- import { aesDecryptGCM, hmacSign } from './crypto.js';
6
- import { toNumber } from './generics.js';
7
- import { downloadAndProcessHistorySyncNotification } from './history.js';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
+ exports.decryptPollVote = decryptPollVote;
5
+ const WAProto_1 = require("../../WAProto");
6
+ const Types_1 = require("../Types");
7
+ const messages_1 = require("../Utils/messages");
8
+ const WABinary_1 = require("../WABinary");
9
+ const crypto_1 = require("./crypto");
10
+ const generics_1 = require("./generics");
11
+ const history_1 = require("./history");
8
12
  const REAL_MSG_STUB_TYPES = new Set([
9
- WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
10
- WAMessageStubType.CALL_MISSED_GROUP_VOICE,
11
- WAMessageStubType.CALL_MISSED_VIDEO,
12
- WAMessageStubType.CALL_MISSED_VOICE
13
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
16
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE
17
+ ]);
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
13
20
  ]);
14
- const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
15
21
  /** Cleans a received message to further processing */
16
- export const cleanMessage = (message, meId) => {
22
+ const cleanMessage = (message, meId) => {
17
23
  // ensure remoteJid and participant doesn't have device or agent in it
18
- message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
19
- message.key.participant = message.key.participant ? jidNormalizedUser(message.key.participant) : undefined;
20
- const content = normalizeMessageContent(message.message);
24
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
25
+ message.key.participant = message.key.participant ? (0, WABinary_1.jidNormalizedUser)(message.key.participant) : undefined;
26
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
21
27
  // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
22
- if (content?.reactionMessage) {
28
+ if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
23
29
  normaliseKey(content.reactionMessage.key);
24
30
  }
25
- if (content?.pollUpdateMessage) {
31
+ if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
26
32
  normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
27
33
  }
28
34
  function normaliseKey(msgKey) {
@@ -32,10 +38,10 @@ export const cleanMessage = (message, meId) => {
32
38
  // if the sender believed the message being reacted to is not from them
33
39
  // we've to correct the key to be from them, or some other participant
34
40
  msgKey.fromMe = !msgKey.fromMe
35
- ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId)
36
- : // if the message being reacted to, was from them
37
- // fromMe automatically becomes false
38
- false;
41
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
42
+ // if the message being reacted to, was from them
43
+ // fromMe automatically becomes false
44
+ : false;
39
45
  // set the remoteJid to being the same as the chat the message came from
40
46
  msgKey.remoteJid = message.key.remoteJid;
41
47
  // set participant of the message
@@ -43,36 +49,43 @@ export const cleanMessage = (message, meId) => {
43
49
  }
44
50
  }
45
51
  };
46
- export const isRealMessage = (message, meId) => {
47
- const normalizedContent = normalizeMessageContent(message.message);
48
- const hasSomeContent = !!getContentType(normalizedContent);
49
- return ((!!normalizedContent ||
50
- REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
51
- (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType) &&
52
- message.messageStubParameters?.some(p => areJidsSameUser(meId, p)))) &&
53
- hasSomeContent &&
54
- !normalizedContent?.protocolMessage &&
55
- !normalizedContent?.reactionMessage &&
56
- !normalizedContent?.pollUpdateMessage);
52
+ exports.cleanMessage = cleanMessage;
53
+ const isRealMessage = (message, meId) => {
54
+ var _a;
55
+ const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
56
+ const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
57
+ return (!!normalizedContent
58
+ || REAL_MSG_STUB_TYPES.has(message.messageStubType)
59
+ || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
60
+ && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
61
+ && hasSomeContent
62
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
63
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
64
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
57
65
  };
58
- export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
66
+ exports.isRealMessage = isRealMessage;
67
+ const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
68
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
59
69
  /**
60
70
  * Get the ID of the chat from the given key.
61
71
  * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
62
72
  */
63
- export const getChatId = ({ remoteJid, participant, fromMe }) => {
64
- if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
73
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
74
+ if ((0, WABinary_1.isJidBroadcast)(remoteJid)
75
+ && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
76
+ && !fromMe) {
65
77
  return participant;
66
78
  }
67
79
  return remoteJid;
68
80
  };
81
+ exports.getChatId = getChatId;
69
82
  /**
70
83
  * Decrypt a poll vote
71
84
  * @param vote encrypted vote
72
85
  * @param ctx additional info about the poll required for decryption
73
86
  * @returns list of SHA256 options
74
87
  */
75
- export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
88
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
76
89
  const sign = Buffer.concat([
77
90
  toBinary(pollMsgId),
78
91
  toBinary(pollCreatorJid),
@@ -80,50 +93,52 @@ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsg
80
93
  toBinary('Poll Vote'),
81
94
  new Uint8Array([1])
82
95
  ]);
83
- const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
84
- const decKey = hmacSign(sign, key0, 'sha256');
96
+ const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
97
+ const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
85
98
  const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
86
- const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
87
- return proto.Message.PollVoteMessage.decode(decrypted);
99
+ const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
100
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
88
101
  function toBinary(txt) {
89
102
  return Buffer.from(txt);
90
103
  }
91
104
  }
92
- const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options }) => {
105
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
106
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
93
107
  const meId = creds.me.id;
94
108
  const { accountSettings } = creds;
95
- const chat = { id: jidNormalizedUser(getChatId(message.key)) };
96
- const isRealMsg = isRealMessage(message, meId);
109
+ const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
110
+ const isRealMsg = (0, exports.isRealMessage)(message, meId);
97
111
  if (isRealMsg) {
98
112
  chat.messages = [{ message }];
99
- chat.conversationTimestamp = toNumber(message.messageTimestamp);
113
+ chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
100
114
  // only increment unread count if not CIPHERTEXT and from another person
101
- if (shouldIncrementChatUnread(message)) {
115
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
102
116
  chat.unreadCount = (chat.unreadCount || 0) + 1;
103
117
  }
104
118
  }
105
- const content = normalizeMessageContent(message.message);
119
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
106
120
  // unarchive chat if it's a real message, or someone reacted to our message
107
121
  // and we've the unarchive chats setting on
108
- if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
122
+ if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
123
+ && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
109
124
  chat.archived = false;
110
125
  chat.readOnly = false;
111
126
  }
112
- const protocolMsg = content?.protocolMessage;
127
+ const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
113
128
  if (protocolMsg) {
114
129
  switch (protocolMsg.type) {
115
- case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
130
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
116
131
  const histNotification = protocolMsg.historySyncNotification;
117
132
  const process = shouldProcessHistoryMsg;
118
- const isLatest = !creds.processedHistoryMessages?.length;
119
- logger?.info({
133
+ const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
134
+ logger === null || logger === void 0 ? void 0 : logger.info({
120
135
  histNotification,
121
136
  process,
122
137
  id: message.key.id,
123
- isLatest
138
+ isLatest,
124
139
  }, 'got history notification');
125
140
  if (process) {
126
- if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
141
+ if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
127
142
  ev.emit('creds.update', {
128
143
  processedHistoryMessages: [
129
144
  ...(creds.processedHistoryMessages || []),
@@ -131,17 +146,19 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
131
146
  ]
132
147
  });
133
148
  }
134
- const data = await downloadAndProcessHistorySyncNotification(histNotification, options);
149
+ const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
135
150
  ev.emit('messaging-history.set', {
136
151
  ...data,
137
- isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
152
+ isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
153
+ ? isLatest
154
+ : undefined,
138
155
  peerDataRequestSessionId: histNotification.peerDataRequestSessionId
139
156
  });
140
157
  }
141
158
  break;
142
- case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
159
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
143
160
  const keys = protocolMsg.appStateSyncKeyShare.keys;
144
- if (keys?.length) {
161
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
145
162
  let newAppStateSyncKeyId = '';
146
163
  await keyStore.transaction(async () => {
147
164
  const newKeys = [];
@@ -151,42 +168,41 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
151
168
  await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
152
169
  newAppStateSyncKeyId = strKeyId;
153
170
  }
154
- logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
171
+ logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
155
172
  });
156
173
  ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
157
174
  }
158
175
  else {
159
- logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
176
+ logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
160
177
  }
161
178
  break;
162
- case proto.Message.ProtocolMessage.Type.REVOKE:
179
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
163
180
  ev.emit('messages.update', [
164
181
  {
165
182
  key: {
166
183
  ...message.key,
167
184
  id: protocolMsg.key.id
168
185
  },
169
- update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
186
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
170
187
  }
171
188
  ]);
172
189
  break;
173
- case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
190
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
174
191
  Object.assign(chat, {
175
- ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
192
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
176
193
  ephemeralExpiration: protocolMsg.ephemeralExpiration || null
177
194
  });
178
195
  break;
179
- case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
196
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
180
197
  const response = protocolMsg.peerDataOperationRequestResponseMessage;
181
198
  if (response) {
182
- placeholderResendCache?.del(response.stanzaId);
199
+ placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
183
200
  // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
184
201
  const { peerDataOperationResult } = response;
185
202
  for (const result of peerDataOperationResult) {
186
203
  const { placeholderMessageResendResponse: retryResponse } = result;
187
- //eslint-disable-next-line max-depth
188
204
  if (retryResponse) {
189
- const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
205
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
190
206
  // wait till another upsert event is available, don't want it to be part of the PDO response message
191
207
  setTimeout(() => {
192
208
  ev.emit('messages.upsert', {
@@ -198,12 +214,11 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
198
214
  }
199
215
  }
200
216
  }
201
- break;
202
- case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
217
+ case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
203
218
  ev.emit('messages.update', [
204
219
  {
205
220
  // flip the sender / fromMe properties because they're in the perspective of the sender
206
- key: { ...message.key, id: protocolMsg.key?.id },
221
+ key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
207
222
  update: {
208
223
  message: {
209
224
  editedMessage: {
@@ -211,7 +226,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
211
226
  }
212
227
  },
213
228
  messageTimestamp: protocolMsg.timestampMs
214
- ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
229
+ ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
215
230
  : message.messageTimestamp
216
231
  }
217
232
  }
@@ -219,37 +234,36 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
219
234
  break;
220
235
  }
221
236
  }
222
- else if (content?.reactionMessage) {
237
+ else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
223
238
  const reaction = {
224
239
  ...content.reactionMessage,
225
- key: message.key
240
+ key: message.key,
226
241
  };
227
- ev.emit('messages.reaction', [
228
- {
242
+ ev.emit('messages.reaction', [{
229
243
  reaction,
230
- key: content.reactionMessage?.key
231
- }
232
- ]);
244
+ key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
245
+ }]);
233
246
  }
234
247
  else if (message.messageStubType) {
235
- const jid = message.key?.remoteJid;
248
+ const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
236
249
  //let actor = whatsappID (message.participant)
237
250
  let participants;
238
- const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action });
251
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
239
252
  const emitGroupUpdate = (update) => {
240
- ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }]);
253
+ var _a;
254
+ ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
241
255
  };
242
256
  const emitGroupRequestJoin = (participant, action, method) => {
243
257
  ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
244
258
  };
245
- const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid));
259
+ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
246
260
  switch (message.messageStubType) {
247
- case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
261
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
248
262
  participants = message.messageStubParameters || [];
249
263
  emitParticipantsUpdate('modify');
250
264
  break;
251
- case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
252
- case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
265
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
266
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
253
267
  participants = message.messageStubParameters || [];
254
268
  emitParticipantsUpdate('remove');
255
269
  // mark the chat read only if you left the group
@@ -257,82 +271,77 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
257
271
  chat.readOnly = true;
258
272
  }
259
273
  break;
260
- case WAMessageStubType.GROUP_PARTICIPANT_ADD:
261
- case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
262
- case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
274
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
275
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
276
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
263
277
  participants = message.messageStubParameters || [];
264
278
  if (participantsIncludesMe()) {
265
279
  chat.readOnly = false;
266
280
  }
267
281
  emitParticipantsUpdate('add');
268
282
  break;
269
- case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
283
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
270
284
  participants = message.messageStubParameters || [];
271
285
  emitParticipantsUpdate('demote');
272
286
  break;
273
- case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
287
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
274
288
  participants = message.messageStubParameters || [];
275
289
  emitParticipantsUpdate('promote');
276
290
  break;
277
- case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
278
- const announceValue = message.messageStubParameters?.[0];
291
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
292
+ const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
279
293
  emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
280
294
  break;
281
- case WAMessageStubType.GROUP_CHANGE_RESTRICT:
282
- const restrictValue = message.messageStubParameters?.[0];
295
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
296
+ const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
283
297
  emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
284
298
  break;
285
- case WAMessageStubType.GROUP_CHANGE_SUBJECT:
286
- const name = message.messageStubParameters?.[0];
299
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
300
+ const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
287
301
  chat.name = name;
288
302
  emitGroupUpdate({ subject: name });
289
303
  break;
290
- case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
291
- const description = message.messageStubParameters?.[0];
304
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
305
+ const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
292
306
  chat.description = description;
293
307
  emitGroupUpdate({ desc: description });
294
308
  break;
295
- case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
296
- const code = message.messageStubParameters?.[0];
309
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
310
+ const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
297
311
  emitGroupUpdate({ inviteCode: code });
298
312
  break;
299
- case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
300
- const memberAddValue = message.messageStubParameters?.[0];
313
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
314
+ const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
301
315
  emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
302
316
  break;
303
- case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
304
- const approvalMode = message.messageStubParameters?.[0];
317
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
318
+ const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
305
319
  emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
306
320
  break;
307
- case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
308
- const participant = message.messageStubParameters?.[0];
309
- const action = message.messageStubParameters?.[1];
310
- const method = message.messageStubParameters?.[2];
321
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
322
+ const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
323
+ const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
324
+ const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
311
325
  emitGroupRequestJoin(participant, action, method);
312
326
  break;
313
327
  }
314
- } /* else if(content?.pollUpdateMessage) {
315
- const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
328
+ }
329
+ else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
330
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
316
331
  // we need to fetch the poll creation message to get the poll enc key
317
- // TODO: make standalone, remove getMessage reference
318
- // TODO: Remove entirely
319
- const pollMsg = await getMessage(creationMsgKey)
320
- if(pollMsg) {
321
- const meIdNormalised = jidNormalizedUser(meId)
322
- const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
323
- const voterJid = getKeyAuthor(message.key, meIdNormalised)
324
- const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
325
-
332
+ const pollMsg = await getMessage(creationMsgKey);
333
+ if (pollMsg) {
334
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
335
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
336
+ const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
337
+ const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
326
338
  try {
327
- const voteMsg = decryptPollVote(
328
- content.pollUpdateMessage.vote!,
329
- {
330
- pollEncKey,
331
- pollCreatorJid,
332
- pollMsgId: creationMsgKey.id!,
333
- voterJid,
334
- }
335
- )
339
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
340
+ pollEncKey,
341
+ pollCreatorJid,
342
+ pollMsgId: creationMsgKey.id,
343
+ voterJid,
344
+ });
336
345
  ev.emit('messages.update', [
337
346
  {
338
347
  key: creationMsgKey,
@@ -341,28 +350,23 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
341
350
  {
342
351
  pollUpdateMessageKey: message.key,
343
352
  vote: voteMsg,
344
- senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
353
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
345
354
  }
346
355
  ]
347
356
  }
348
357
  }
349
- ])
350
- } catch(err) {
351
- logger?.warn(
352
- { err, creationMsgKey },
353
- 'failed to decrypt poll vote'
354
- )
358
+ ]);
359
+ }
360
+ catch (err) {
361
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
355
362
  }
356
- } else {
357
- logger?.warn(
358
- { creationMsgKey },
359
- 'poll creation message not found, cannot decrypt update'
360
- )
361
363
  }
362
- } */
364
+ else {
365
+ logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
366
+ }
367
+ }
363
368
  if (Object.keys(chat).length > 1) {
364
369
  ev.emit('chats.update', [chat]);
365
370
  }
366
371
  };
367
- export default processMessage;
368
- //# sourceMappingURL=process-message.js.map
372
+ exports.default = processMessage;