@x4r1s3/baileys 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1245 -2
- package/SECURITY.md +47 -0
- package/WAProto/V +1 -0
- package/WAProto/WAProto.proto +8892 -0
- package/WAProto/index.d.ts +104128 -0
- package/WAProto/index.js +334920 -0
- package/assets/rolling-circle.svg +133 -0
- package/assets/x4r1s3-banner.svg +32 -0
- package/engine-requirements.js +27 -0
- package/lib/Builders/A2UI.js +245 -0
- package/lib/Builders/AIRich.js +179 -0
- package/lib/Builders/Button.js +108 -0
- package/lib/Builders/CFC.js +284 -0
- package/lib/Builders/Carousel.js +81 -0
- package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
- package/lib/Call/astralena-v3.mjs +96 -0
- package/lib/Call/audio-feeder.mjs +201 -0
- package/lib/Call/audio-recorder.mjs +250 -0
- package/lib/Call/fetch-wasm-resources.mjs +104 -0
- package/lib/Call/index.mjs +707 -0
- package/lib/Call/relay-transport.mjs +563 -0
- package/lib/Call/signaling.mjs +660 -0
- package/lib/Call/types.mjs +17 -0
- package/lib/Call/video-feeder.mjs +94 -0
- package/lib/Call/voip-resources.mjs +259 -0
- package/lib/Call/wasm-engine.mjs +1372 -0
- package/lib/Call/worker-bootstrap.mjs +1042 -0
- package/lib/Defaults/ban-checker.js +56 -0
- package/lib/Defaults/index.js +170 -0
- package/lib/Signal/Group/ciphertext-message.js +23 -0
- package/lib/Signal/Group/group-session-builder.js +41 -0
- package/lib/Signal/Group/group_cipher.js +93 -0
- package/lib/Signal/Group/index.js +23 -0
- package/lib/Signal/Group/keyhelper.js +29 -0
- package/lib/Signal/Group/sender-chain-key.js +37 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
- package/lib/Signal/Group/sender-key-message.js +77 -0
- package/lib/Signal/Group/sender-key-name.js +59 -0
- package/lib/Signal/Group/sender-key-record.js +52 -0
- package/lib/Signal/Group/sender-key-state.js +95 -0
- package/lib/Signal/Group/sender-message-key.js +37 -0
- package/lib/Signal/libsignal.js +440 -0
- package/lib/Signal/lid-mapping.js +292 -0
- package/lib/Socket/Client/index.js +14 -0
- package/lib/Socket/Client/types.js +22 -0
- package/lib/Socket/Client/websocket.js +65 -0
- package/lib/Socket/aigroups.js +327 -0
- package/lib/Socket/ban-checker.js +165 -0
- package/lib/Socket/business.js +419 -0
- package/lib/Socket/chats.js +1921 -0
- package/lib/Socket/communities.js +443 -0
- package/lib/Socket/graphql.js +911 -0
- package/lib/Socket/groups.js +561 -0
- package/lib/Socket/index.js +49 -0
- package/lib/Socket/interactive-handler.js +612 -0
- package/lib/Socket/interop.js +575 -0
- package/lib/Socket/managed-account.js +220 -0
- package/lib/Socket/messages-recv.js +2193 -0
- package/lib/Socket/messages-send.js +4141 -0
- package/lib/Socket/mex.js +53 -0
- package/lib/Socket/newsletter.js +291 -0
- package/lib/Socket/privacy.js +458 -0
- package/lib/Socket/registration.js +440 -0
- package/lib/Socket/socket.js +1042 -0
- package/lib/Socket/status-actions.js +287 -0
- package/lib/Socket/username.js +241 -0
- package/lib/Store/index.js +16 -0
- package/lib/Store/make-cache-manager-store.js +101 -0
- package/lib/Store/make-in-memory-store.js +432 -0
- package/lib/Store/make-ordered-dictionary.js +90 -0
- package/lib/Store/object-repository.js +35 -0
- package/lib/Types/Auth.js +13 -0
- package/lib/Types/Bussines.js +13 -0
- package/lib/Types/Call.js +13 -0
- package/lib/Types/Chat.js +19 -0
- package/lib/Types/Contact.js +13 -0
- package/lib/Types/Events.js +13 -0
- package/lib/Types/GroupMetadata.js +13 -0
- package/lib/Types/Label.js +36 -0
- package/lib/Types/LabelAssociation.js +18 -0
- package/lib/Types/Message.js +30 -0
- package/lib/Types/Mex.js +53 -0
- package/lib/Types/Product.js +13 -0
- package/lib/Types/RichType.js +34 -0
- package/lib/Types/Signal.js +13 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +60 -0
- package/lib/Types/USync.js +13 -0
- package/lib/Types/index.js +37 -0
- package/lib/Utils/auth-utils.js +313 -0
- package/lib/Utils/ban-checker.js +48 -0
- package/lib/Utils/bot-capabilities.js +96 -0
- package/lib/Utils/bot-planning-replay.js +177 -0
- package/lib/Utils/browser-utils.js +40 -0
- package/lib/Utils/business.js +242 -0
- package/lib/Utils/c2582.js +147 -0
- package/lib/Utils/chat-utils.js +905 -0
- package/lib/Utils/companion-reg-client-utils.js +104 -0
- package/lib/Utils/consumer-application.js +114 -0
- package/lib/Utils/crypto.js +129 -0
- package/lib/Utils/decode-wa-message.js +496 -0
- package/lib/Utils/direct-chat-theme.js +164 -0
- package/lib/Utils/event-buffer.js +601 -0
- package/lib/Utils/experimental-proto.js +206 -0
- package/lib/Utils/games/miniapp.js +17 -0
- package/lib/Utils/games/slot-machine.js +270 -0
- package/lib/Utils/games/website-preview.js +306 -0
- package/lib/Utils/generics.js +402 -0
- package/lib/Utils/group-history.js +68 -0
- package/lib/Utils/group-wallpaper.js +168 -0
- package/lib/Utils/history.js +162 -0
- package/lib/Utils/identity-change-handler.js +60 -0
- package/lib/Utils/index.js +61 -0
- package/lib/Utils/jid-display-normalization.js +221 -0
- package/lib/Utils/link-preview.js +96 -0
- package/lib/Utils/logger.js +14 -0
- package/lib/Utils/lt-hash.js +19 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/message-composer.js +709 -0
- package/lib/Utils/message-inspect.js +79 -0
- package/lib/Utils/message-retry-manager.js +253 -0
- package/lib/Utils/message-security.js +167 -0
- package/lib/Utils/messages-media.js +1027 -0
- package/lib/Utils/messages.js +2467 -0
- package/lib/Utils/meta-ai-msmsg.js +215 -0
- package/lib/Utils/meta-compositing.js +239 -0
- package/lib/Utils/native-flow.js +158 -0
- package/lib/Utils/newsletter-live-update-utils.js +74 -0
- package/lib/Utils/newsletter-status-utils.js +152 -0
- package/lib/Utils/noise-handler.js +212 -0
- package/lib/Utils/offline-node-processor.js +51 -0
- package/lib/Utils/poll-manager.js +206 -0
- package/lib/Utils/portable-compat.js +12 -0
- package/lib/Utils/pre-key-manager.js +117 -0
- package/lib/Utils/process-message.js +610 -0
- package/lib/Utils/reporting-utils.js +269 -0
- package/lib/Utils/rich-message-utils.js +2841 -0
- package/lib/Utils/scheduled-message.js +107 -0
- package/lib/Utils/signal.js +212 -0
- package/lib/Utils/source-grep.js +57 -0
- package/lib/Utils/stanza-ack.js +49 -0
- package/lib/Utils/sticker-annotation.js +87 -0
- package/lib/Utils/sync-action-utils.js +59 -0
- package/lib/Utils/tc-token-utils.js +174 -0
- package/lib/Utils/use-multi-file-auth-state.js +132 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +120 -0
- package/lib/Utils/validate-connection.js +221 -0
- package/lib/Utils/view-once-utils.js +218 -0
- package/lib/Utils/voip-rekey.js +32 -0
- package/lib/Utils/website-preview.js +27 -0
- package/lib/Utils/welcome-flow.js +228 -0
- package/lib/Utils/x4r1s3.js +144 -0
- package/lib/WABinary/constants.js +1475 -0
- package/lib/WABinary/decode.js +273 -0
- package/lib/WABinary/encode.js +231 -0
- package/lib/WABinary/generic-utils.js +242 -0
- package/lib/WABinary/index.js +17 -0
- package/lib/WABinary/jid-utils.js +107 -0
- package/lib/WABinary/types.js +13 -0
- package/lib/WAM/BinaryInfo.js +21 -0
- package/lib/WAM/constants.js +22864 -0
- package/lib/WAM/encode.js +161 -0
- package/lib/WAM/index.js +15 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
- package/lib/WAUSync/Protocols/index.js +24 -0
- package/lib/WAUSync/USyncQuery.js +213 -0
- package/lib/WAUSync/USyncUser.js +66 -0
- package/lib/WAUSync/index.js +15 -0
- package/lib/antiban.cjs +4726 -0
- package/lib/index.d.ts +1895 -0
- package/lib/index.js +41 -0
- package/package.json +125 -4
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/history.js
|
|
5
|
+
* About: History module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: downloadHistory, processHistoryMessage, downloadAndProcessHistorySyncNotification, getHistoryMsg
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { promisify } from 'util';
|
|
14
|
+
import { inflate } from 'zlib';
|
|
15
|
+
import { proto } from '../../WAProto/index.js';
|
|
16
|
+
import { WAMessageStubType } from '../Types/index.js';
|
|
17
|
+
import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
|
|
18
|
+
import { toNumber } from './generics.js';
|
|
19
|
+
import { normalizeMessageContent } from './messages.js';
|
|
20
|
+
import { downloadContentFromMessage } from './messages-media.js';
|
|
21
|
+
const inflatePromise = promisify(inflate);
|
|
22
|
+
const extractPnFromMessages = (messages) => {
|
|
23
|
+
for (const msgItem of messages) {
|
|
24
|
+
const message = msgItem.message;
|
|
25
|
+
// Only extract from outgoing messages (fromMe: true) in 1:1 chats
|
|
26
|
+
// because userReceipt.userJid is the recipient's JID
|
|
27
|
+
if (!message?.key?.fromMe || !message.userReceipt?.length) {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const userJid = message.userReceipt[0]?.userJid;
|
|
31
|
+
if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
|
|
32
|
+
return userJid;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
};
|
|
37
|
+
export const downloadHistory = async (msg, options) => {
|
|
38
|
+
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
|
|
39
|
+
const bufferArray = [];
|
|
40
|
+
for await (const chunk of stream) {
|
|
41
|
+
bufferArray.push(chunk);
|
|
42
|
+
}
|
|
43
|
+
let buffer = Buffer.concat(bufferArray);
|
|
44
|
+
// decompress buffer
|
|
45
|
+
buffer = await inflatePromise(buffer);
|
|
46
|
+
const syncData = proto.HistorySync.decode(buffer);
|
|
47
|
+
return syncData;
|
|
48
|
+
};
|
|
49
|
+
export const processHistoryMessage = (item, logger) => {
|
|
50
|
+
const messages = [];
|
|
51
|
+
const contacts = [];
|
|
52
|
+
const chats = [];
|
|
53
|
+
const lidPnMappings = [];
|
|
54
|
+
const favoriteStickers = [];
|
|
55
|
+
const omittedConversations = [];
|
|
56
|
+
logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
|
|
57
|
+
// Extract LID-PN mappings for all sync types
|
|
58
|
+
for (const m of item.phoneNumberToLidMappings || []) {
|
|
59
|
+
if (m.lidJid && m.pnJid) {
|
|
60
|
+
lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const favoriteStickerKeys = new Set();
|
|
64
|
+
for (const sticker of item.favoriteStickers || []) {
|
|
65
|
+
const key = sticker.fileSha256 ? Buffer.from(sticker.fileSha256).toString('base64') : undefined;
|
|
66
|
+
if (!key || !favoriteStickerKeys.has(key)) {
|
|
67
|
+
if (key)
|
|
68
|
+
favoriteStickerKeys.add(key);
|
|
69
|
+
favoriteStickers.push(sticker);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const omitted of item.omittedConversations || []) {
|
|
73
|
+
omittedConversations.push({
|
|
74
|
+
id: omitted.historyChatId,
|
|
75
|
+
accountLid: omitted.accountLid || undefined
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
switch (item.syncType) {
|
|
79
|
+
case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
|
|
80
|
+
case proto.HistorySync.HistorySyncType.RECENT:
|
|
81
|
+
case proto.HistorySync.HistorySyncType.FULL:
|
|
82
|
+
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
|
83
|
+
for (const chat of item.conversations) {
|
|
84
|
+
contacts.push({
|
|
85
|
+
id: chat.id,
|
|
86
|
+
name: chat.displayName || chat.name || chat.username || undefined,
|
|
87
|
+
lid: chat.lidJid || chat.accountLid || undefined,
|
|
88
|
+
phoneNumber: chat.pnJid || undefined
|
|
89
|
+
});
|
|
90
|
+
const chatId = chat.id;
|
|
91
|
+
const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
|
|
92
|
+
const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
|
|
93
|
+
if (isLid && chat.pnJid) {
|
|
94
|
+
lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
|
|
95
|
+
}
|
|
96
|
+
else if (isPn && chat.lidJid) {
|
|
97
|
+
lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
|
|
98
|
+
}
|
|
99
|
+
else if (isLid && !chat.pnJid) {
|
|
100
|
+
// Fallback: extract PN from userReceipt in messages when pnJid is missing
|
|
101
|
+
const pnFromReceipt = extractPnFromMessages(chat.messages || []);
|
|
102
|
+
if (pnFromReceipt) {
|
|
103
|
+
lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const msgs = chat.messages || [];
|
|
107
|
+
delete chat.messages;
|
|
108
|
+
for (const item of msgs) {
|
|
109
|
+
const message = item.message;
|
|
110
|
+
messages.push(message);
|
|
111
|
+
if (!chat.messages?.length) {
|
|
112
|
+
// keep only the most recent message in the chat array
|
|
113
|
+
chat.messages = [{ message }];
|
|
114
|
+
}
|
|
115
|
+
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
|
116
|
+
chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
|
|
117
|
+
}
|
|
118
|
+
if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
|
|
119
|
+
message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
|
|
120
|
+
message.messageStubParameters?.[0]) {
|
|
121
|
+
contacts.push({
|
|
122
|
+
id: message.key.participant || message.key.remoteJid,
|
|
123
|
+
verifiedName: message.messageStubParameters?.[0]
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
chats.push({ ...chat });
|
|
128
|
+
}
|
|
129
|
+
break;
|
|
130
|
+
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
131
|
+
for (const c of item.pushnames) {
|
|
132
|
+
contacts.push({ id: c.id, notify: c.pushname });
|
|
133
|
+
}
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
chats,
|
|
138
|
+
contacts,
|
|
139
|
+
messages,
|
|
140
|
+
lidPnMappings,
|
|
141
|
+
favoriteStickers,
|
|
142
|
+
omittedConversations,
|
|
143
|
+
omittedConversationsProvided: item.omittedConversationsProvided ?? false,
|
|
144
|
+
syncType: item.syncType,
|
|
145
|
+
progress: item.progress
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
|
|
149
|
+
let historyMsg;
|
|
150
|
+
if (msg.initialHistBootstrapInlinePayload) {
|
|
151
|
+
historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
historyMsg = await downloadHistory(msg, options);
|
|
155
|
+
}
|
|
156
|
+
return processHistoryMessage(historyMsg, logger);
|
|
157
|
+
};
|
|
158
|
+
export const getHistoryMsg = (message) => {
|
|
159
|
+
const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
|
|
160
|
+
const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
|
|
161
|
+
return anyHistoryMsg;
|
|
162
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/identity-change-handler.js
|
|
5
|
+
* About: Identity change handler module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: handleIdentityChange
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import NodeCache from '@cacheable/node-cache';
|
|
14
|
+
import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js';
|
|
15
|
+
import { isStringNullOrEmpty } from './generics.js';
|
|
16
|
+
export async function handleIdentityChange(node, ctx) {
|
|
17
|
+
const from = node.attrs.from;
|
|
18
|
+
if (!from) {
|
|
19
|
+
return { action: 'invalid_notification' };
|
|
20
|
+
}
|
|
21
|
+
const identityNode = getBinaryNodeChild(node, 'identity');
|
|
22
|
+
if (!identityNode) {
|
|
23
|
+
return { action: 'no_identity_node' };
|
|
24
|
+
}
|
|
25
|
+
ctx.logger.info({ jid: from }, 'identity changed');
|
|
26
|
+
const decoded = jidDecode(from);
|
|
27
|
+
if (decoded?.device && decoded.device !== 0) {
|
|
28
|
+
ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
|
|
29
|
+
return { action: 'skipped_companion_device', device: decoded.device };
|
|
30
|
+
}
|
|
31
|
+
const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
|
|
32
|
+
if (isSelfPrimary) {
|
|
33
|
+
ctx.logger.info({ jid: from }, 'self primary identity changed');
|
|
34
|
+
return { action: 'skipped_self_primary' };
|
|
35
|
+
}
|
|
36
|
+
if (ctx.debounceCache.get(from)) {
|
|
37
|
+
ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
|
|
38
|
+
return { action: 'debounced' };
|
|
39
|
+
}
|
|
40
|
+
ctx.debounceCache.set(from, true);
|
|
41
|
+
const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
|
|
42
|
+
const hasExistingSession = await ctx.validateSession(from);
|
|
43
|
+
if (!hasExistingSession.exists) {
|
|
44
|
+
ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
|
|
45
|
+
return { action: 'skipped_no_session' };
|
|
46
|
+
}
|
|
47
|
+
ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
|
|
48
|
+
if (isOfflineNotification) {
|
|
49
|
+
ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
|
|
50
|
+
return { action: 'skipped_offline' };
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
await ctx.assertSessions([from], true);
|
|
54
|
+
return { action: 'session_refreshed' };
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
|
|
58
|
+
return { action: 'session_refresh_failed', error };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/index.js
|
|
5
|
+
* About: Utils module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: No public exports detected; module side effects or declarations are local.
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
export * from './generics.js';
|
|
14
|
+
export * from './decode-wa-message.js';
|
|
15
|
+
export * from './message-inspect.js';
|
|
16
|
+
export * from './scheduled-message.js';
|
|
17
|
+
export * from './messages.js';
|
|
18
|
+
export * from './poll-manager.js';
|
|
19
|
+
export * from './messages-media.js';
|
|
20
|
+
export * from './group-wallpaper.js';
|
|
21
|
+
export * from './direct-chat-theme.js';
|
|
22
|
+
export * from './experimental-proto.js';
|
|
23
|
+
export * from './rich-message-utils.js';
|
|
24
|
+
export * from './c2582.js';
|
|
25
|
+
export * from './meta-compositing.js';
|
|
26
|
+
export * from './bot-planning-replay.js';
|
|
27
|
+
export * from './bot-capabilities.js';
|
|
28
|
+
export * from './welcome-flow.js';
|
|
29
|
+
export * from './message-composer.js';
|
|
30
|
+
export * from './consumer-application.js';
|
|
31
|
+
export * from './group-history.js';
|
|
32
|
+
export * from './jid-display-normalization.js';
|
|
33
|
+
export * from './voip-rekey.js';
|
|
34
|
+
export * from './meta-ai-msmsg.js';
|
|
35
|
+
export * from './native-flow.js';
|
|
36
|
+
export * from './validate-connection.js';
|
|
37
|
+
export * from './crypto.js';
|
|
38
|
+
export * from './signal.js';
|
|
39
|
+
export * from './noise-handler.js';
|
|
40
|
+
export * from './history.js';
|
|
41
|
+
export * from './chat-utils.js';
|
|
42
|
+
export * from './lt-hash.js';
|
|
43
|
+
export * from './auth-utils.js';
|
|
44
|
+
export * from './use-multi-file-auth-state.js';
|
|
45
|
+
export * from './use-single-file-auth-state.js';
|
|
46
|
+
export * from './use-sqlite-auth-state.js';
|
|
47
|
+
export * from './link-preview.js';
|
|
48
|
+
export * from './event-buffer.js';
|
|
49
|
+
export * from './process-message.js';
|
|
50
|
+
export * from './message-retry-manager.js';
|
|
51
|
+
export * from './browser-utils.js';
|
|
52
|
+
export * from './companion-reg-client-utils.js';
|
|
53
|
+
export * from './identity-change-handler.js';
|
|
54
|
+
export * from './stanza-ack.js';
|
|
55
|
+
export * from './source-grep.js';
|
|
56
|
+
export * from './games/miniapp.js';
|
|
57
|
+
|
|
58
|
+
export * from './x4r1s3.js';
|
|
59
|
+
|
|
60
|
+
export * from './message-security.js';
|
|
61
|
+
export * from './newsletter-live-update-utils.js';
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/jid-display-normalization.js
|
|
5
|
+
* About: Jid display normalization module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: normalizeMentionedJidsForSend, normalizeMessageForDisplayJids
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode } from '../WABinary/index.js';
|
|
14
|
+
|
|
15
|
+
const createLidPnDebug = (logger) => {
|
|
16
|
+
const enabled = process.env.LID_PN_DEBUG === '1' || process.env.LID_PN_DEBUG === 'true';
|
|
17
|
+
return (phase, payload) => {
|
|
18
|
+
if (!enabled) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
logger?.debug({ ...payload, phase }, 'lid->pn normalization trace');
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const fallbackPnFromLidJid = (jid) => {
|
|
26
|
+
const decoded = jidDecode(jid);
|
|
27
|
+
const rawUser = decoded?.user || (typeof jid === 'string' ? jid.split('@')[0] : '');
|
|
28
|
+
const user = rawUser.split(':')[0];
|
|
29
|
+
if (!user) {
|
|
30
|
+
return jid;
|
|
31
|
+
}
|
|
32
|
+
return `${user}@s.whatsapp.net`;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const toDisplayPnJid = (jid) => {
|
|
36
|
+
if (!jid || typeof jid !== 'string') {
|
|
37
|
+
return jid;
|
|
38
|
+
}
|
|
39
|
+
const decoded = jidDecode(jid);
|
|
40
|
+
if (!decoded?.user) {
|
|
41
|
+
return jid;
|
|
42
|
+
}
|
|
43
|
+
if (!isPnUser(jid) && !isHostedPnUser(jid)) {
|
|
44
|
+
return jid;
|
|
45
|
+
}
|
|
46
|
+
const user = decoded.user.split(':')[0];
|
|
47
|
+
if (!user) {
|
|
48
|
+
return jid;
|
|
49
|
+
}
|
|
50
|
+
const server = decoded.server === 'hosted' ? 'hosted' : 's.whatsapp.net';
|
|
51
|
+
return `${user}@${server}`;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const buildLidPnHints = (key) => {
|
|
55
|
+
const hints = new Map();
|
|
56
|
+
if (!key) {
|
|
57
|
+
return hints;
|
|
58
|
+
}
|
|
59
|
+
const addHint = (lid, pn) => {
|
|
60
|
+
if (!isLidUser(lid) && !isHostedLidUser(lid)) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (!isPnUser(pn) && !isHostedPnUser(pn)) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
hints.set(lid, pn);
|
|
67
|
+
const lidDecoded = jidDecode(lid);
|
|
68
|
+
const pnDecoded = jidDecode(pn);
|
|
69
|
+
if (lidDecoded?.user && pnDecoded?.user) {
|
|
70
|
+
hints.set(`${lidDecoded.user}@lid`, `${pnDecoded.user}@s.whatsapp.net`);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
addHint(key.participant, key.participantAlt);
|
|
74
|
+
addHint(key.remoteJid, key.remoteJidAlt);
|
|
75
|
+
addHint(key.participantAlt, key.participant);
|
|
76
|
+
addHint(key.remoteJidAlt, key.remoteJid);
|
|
77
|
+
return hints;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const mergeGroupDataHints = (hints, groupData, debug) => {
|
|
81
|
+
if (!groupData?.participants?.length) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
debug?.('groupData-size', { participants: groupData.participants.length });
|
|
85
|
+
for (const participant of groupData.participants) {
|
|
86
|
+
const lidCandidate = participant?.lid;
|
|
87
|
+
const idCandidate = participant?.id;
|
|
88
|
+
const pnCandidate = participant?.phoneNumber;
|
|
89
|
+
const lid =
|
|
90
|
+
((isLidUser(lidCandidate) || isHostedLidUser(lidCandidate)
|
|
91
|
+
? lidCandidate
|
|
92
|
+
: undefined)) ||
|
|
93
|
+
((isLidUser(idCandidate) || isHostedLidUser(idCandidate) ? idCandidate : undefined));
|
|
94
|
+
const pn =
|
|
95
|
+
((isPnUser(pnCandidate) || isHostedPnUser(pnCandidate)
|
|
96
|
+
? pnCandidate
|
|
97
|
+
: undefined)) ||
|
|
98
|
+
((isPnUser(idCandidate) || isHostedPnUser(idCandidate) ? idCandidate : undefined));
|
|
99
|
+
if (!lid || !pn) {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (
|
|
103
|
+
(isLidUser(lid) || isHostedLidUser(lid)) &&
|
|
104
|
+
(isPnUser(pn) || isHostedPnUser(pn))
|
|
105
|
+
) {
|
|
106
|
+
const displayPn = toDisplayPnJid(pn);
|
|
107
|
+
hints.set(lid, displayPn);
|
|
108
|
+
const lidDecoded = jidDecode(lid);
|
|
109
|
+
if (lidDecoded?.user) {
|
|
110
|
+
hints.set(`${lidDecoded.user}@lid`, displayPn);
|
|
111
|
+
}
|
|
112
|
+
debug?.('group-hint', { lid, pn: displayPn });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const normalizeToPnJid = async (jid, hints, signalRepository, debug) => {
|
|
118
|
+
if (!jid || typeof jid !== 'string') {
|
|
119
|
+
return jid;
|
|
120
|
+
}
|
|
121
|
+
if (!isLidUser(jid) && !isHostedLidUser(jid)) {
|
|
122
|
+
return jid;
|
|
123
|
+
}
|
|
124
|
+
debug?.('input', { lid: jid });
|
|
125
|
+
const hinted = hints.get(jid);
|
|
126
|
+
if (hinted) {
|
|
127
|
+
const normalized = toDisplayPnJid(hinted);
|
|
128
|
+
debug?.('hint-exact', { lid: jid, hinted, normalized });
|
|
129
|
+
return normalized;
|
|
130
|
+
}
|
|
131
|
+
const decoded = jidDecode(jid);
|
|
132
|
+
if (decoded?.user) {
|
|
133
|
+
const userHint = hints.get(`${decoded.user}@lid`);
|
|
134
|
+
if (userHint) {
|
|
135
|
+
const normalized = toDisplayPnJid(userHint);
|
|
136
|
+
debug?.('hint-user', { lid: jid, userHint, normalized });
|
|
137
|
+
return normalized;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const mapped = await signalRepository?.lidMapping?.getPNForLID?.(jid);
|
|
141
|
+
if (mapped) {
|
|
142
|
+
const normalized = toDisplayPnJid(mapped);
|
|
143
|
+
debug?.('mapping', { lid: jid, mapped, normalized });
|
|
144
|
+
return normalized;
|
|
145
|
+
}
|
|
146
|
+
const fallback = fallbackPnFromLidJid(jid);
|
|
147
|
+
debug?.('fallback', { lid: jid, fallback });
|
|
148
|
+
return fallback;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const normalizeMentionedJidsToPn = async (node, hints, signalRepository, debug) => {
|
|
152
|
+
if (!node || typeof node !== 'object') {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (Array.isArray(node)) {
|
|
156
|
+
for (const item of node) {
|
|
157
|
+
await normalizeMentionedJidsToPn(item, hints, signalRepository, debug);
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (Array.isArray(node.mentionedJid)) {
|
|
162
|
+
const before = [...node.mentionedJid];
|
|
163
|
+
node.mentionedJid = await Promise.all(
|
|
164
|
+
node.mentionedJid.map(jid => normalizeToPnJid(jid, hints, signalRepository, debug))
|
|
165
|
+
);
|
|
166
|
+
debug?.('mentions', { before, after: node.mentionedJid });
|
|
167
|
+
}
|
|
168
|
+
if (typeof node.participant === 'string') {
|
|
169
|
+
const before = node.participant;
|
|
170
|
+
node.participant = await normalizeToPnJid(node.participant, hints, signalRepository, debug);
|
|
171
|
+
if (before !== node.participant) {
|
|
172
|
+
debug?.('participant-field', { before, after: node.participant });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (typeof node.remoteJid === 'string') {
|
|
176
|
+
const before = node.remoteJid;
|
|
177
|
+
node.remoteJid = await normalizeToPnJid(node.remoteJid, hints, signalRepository, debug);
|
|
178
|
+
if (before !== node.remoteJid) {
|
|
179
|
+
debug?.('remoteJid-field', { before, after: node.remoteJid });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const value of Object.values(node)) {
|
|
183
|
+
if (value && typeof value === 'object') {
|
|
184
|
+
await normalizeMentionedJidsToPn(value, hints, signalRepository, debug);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export const normalizeMentionedJidsForSend = async (mentions, groupData, signalRepository, logger) => {
|
|
190
|
+
if (!Array.isArray(mentions)) {
|
|
191
|
+
return mentions;
|
|
192
|
+
}
|
|
193
|
+
const debug = createLidPnDebug(logger);
|
|
194
|
+
const hints = new Map();
|
|
195
|
+
mergeGroupDataHints(hints, groupData, debug);
|
|
196
|
+
const normalized = await Promise.all(mentions.map(jid => normalizeToPnJid(jid, hints, signalRepository, debug)));
|
|
197
|
+
debug('send-mentions-result', { before: mentions, after: normalized });
|
|
198
|
+
return normalized;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export const normalizeMessageForDisplayJids = async (messageInfo, signalRepository, logger, groupData) => {
|
|
202
|
+
if (!messageInfo?.key) {
|
|
203
|
+
return messageInfo;
|
|
204
|
+
}
|
|
205
|
+
const debug = createLidPnDebug(logger);
|
|
206
|
+
const hints = buildLidPnHints(messageInfo.key);
|
|
207
|
+
mergeGroupDataHints(hints, groupData, debug);
|
|
208
|
+
const beforeKey = { ...messageInfo.key };
|
|
209
|
+
messageInfo.key.participant = await normalizeToPnJid(messageInfo.key.participant, hints, signalRepository, debug);
|
|
210
|
+
messageInfo.key.participantAlt = await normalizeToPnJid(
|
|
211
|
+
messageInfo.key.participantAlt,
|
|
212
|
+
hints,
|
|
213
|
+
signalRepository,
|
|
214
|
+
debug
|
|
215
|
+
);
|
|
216
|
+
messageInfo.key.remoteJid = await normalizeToPnJid(messageInfo.key.remoteJid, hints, signalRepository, debug);
|
|
217
|
+
messageInfo.key.remoteJidAlt = await normalizeToPnJid(messageInfo.key.remoteJidAlt, hints, signalRepository, debug);
|
|
218
|
+
await normalizeMentionedJidsToPn(messageInfo.message, hints, signalRepository, debug);
|
|
219
|
+
debug('display-key-result', { before: beforeKey, after: messageInfo.key });
|
|
220
|
+
return messageInfo;
|
|
221
|
+
};
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/link-preview.js
|
|
5
|
+
* About: Link preview module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: getUrlInfo
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { prepareWAMessageMedia } from './messages.js';
|
|
14
|
+
import { extractImageThumb, getHttpStream } from './messages-media.js';
|
|
15
|
+
const THUMBNAIL_WIDTH_PX = 192;
|
|
16
|
+
/** Fetches an image and generates a thumbnail for it */
|
|
17
|
+
const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
|
|
18
|
+
const stream = await getHttpStream(url, fetchOpts);
|
|
19
|
+
const result = await extractImageThumb(stream, thumbnailWidth);
|
|
20
|
+
return result;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Given a piece of text, checks for any URL present, generates link preview for the same and returns it
|
|
24
|
+
* Return undefined if the fetch failed or no URL was found
|
|
25
|
+
* @param text first matched URL in text
|
|
26
|
+
* @returns the URL info required to generate link preview
|
|
27
|
+
*/
|
|
28
|
+
export const getUrlInfo = async (text, opts = {
|
|
29
|
+
thumbnailWidth: THUMBNAIL_WIDTH_PX,
|
|
30
|
+
fetchOpts: { timeout: 3000 }
|
|
31
|
+
}) => {
|
|
32
|
+
try {
|
|
33
|
+
// retries
|
|
34
|
+
const retries = 0;
|
|
35
|
+
const maxRetry = 5;
|
|
36
|
+
const { getLinkPreview } = await import('link-preview-js');
|
|
37
|
+
let previewLink = text;
|
|
38
|
+
if (!text.startsWith('https://') && !text.startsWith('http://')) {
|
|
39
|
+
previewLink = 'https://' + previewLink;
|
|
40
|
+
}
|
|
41
|
+
const info = await getLinkPreview(previewLink, {
|
|
42
|
+
...opts.fetchOpts,
|
|
43
|
+
followRedirects: 'follow',
|
|
44
|
+
handleRedirects: (baseURL, forwardedURL) => {
|
|
45
|
+
const urlObj = new URL(baseURL);
|
|
46
|
+
const forwardedURLObj = new URL(forwardedURL);
|
|
47
|
+
if (retries >= maxRetry) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
if (forwardedURLObj.hostname === urlObj.hostname ||
|
|
51
|
+
forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
|
|
52
|
+
'www.' + forwardedURLObj.hostname === urlObj.hostname) {
|
|
53
|
+
retries + 1;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
headers: opts.fetchOpts?.headers
|
|
61
|
+
});
|
|
62
|
+
if (info && 'title' in info && info.title) {
|
|
63
|
+
const [image] = info.images;
|
|
64
|
+
const urlInfo = {
|
|
65
|
+
'canonical-url': info.url,
|
|
66
|
+
'matched-text': text,
|
|
67
|
+
title: info.title,
|
|
68
|
+
description: info.description,
|
|
69
|
+
originalThumbnailUrl: image
|
|
70
|
+
};
|
|
71
|
+
if (opts.uploadImage) {
|
|
72
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
|
|
73
|
+
upload: opts.uploadImage,
|
|
74
|
+
mediaTypeOverride: 'thumbnail-link',
|
|
75
|
+
options: opts.fetchOpts
|
|
76
|
+
});
|
|
77
|
+
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
|
|
78
|
+
urlInfo.highQualityThumbnail = imageMessage || undefined;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
try {
|
|
82
|
+
urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return urlInfo;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (!error.message.includes('receive a valid')) {
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/logger.js
|
|
5
|
+
* About: Logger module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: No public exports detected; module side effects or declarations are local.
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import P from 'pino';
|
|
14
|
+
export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/lt-hash.js
|
|
5
|
+
* About: Lt hash module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: LT_HASH_ANTI_TAMPERING
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
|
|
14
|
+
/**
|
|
15
|
+
* LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
|
|
16
|
+
* over a series of mutations. You can add/remove mutations and it'll return a hash equal to
|
|
17
|
+
* if the same series of mutations was made sequentially.
|
|
18
|
+
*/
|
|
19
|
+
export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/make-mutex.js
|
|
5
|
+
* About: Make mutex module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: makeMutex, makeKeyedMutex
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { Mutex as AsyncMutex } from 'async-mutex';
|
|
14
|
+
export const makeMutex = () => {
|
|
15
|
+
const mutex = new AsyncMutex();
|
|
16
|
+
return {
|
|
17
|
+
mutex(code) {
|
|
18
|
+
return mutex.runExclusive(code);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
export const makeKeyedMutex = () => {
|
|
23
|
+
const map = new Map();
|
|
24
|
+
return {
|
|
25
|
+
async mutex(key, task) {
|
|
26
|
+
let entry = map.get(key);
|
|
27
|
+
if (!entry) {
|
|
28
|
+
entry = { mutex: new AsyncMutex(), refCount: 0 };
|
|
29
|
+
map.set(key, entry);
|
|
30
|
+
}
|
|
31
|
+
entry.refCount++;
|
|
32
|
+
try {
|
|
33
|
+
return await entry.mutex.runExclusive(task);
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
entry.refCount--;
|
|
37
|
+
// only delete it if this is still the current entry
|
|
38
|
+
if (entry.refCount === 0 && map.get(key) === entry) {
|
|
39
|
+
map.delete(key);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
};
|