naya-flore 4.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4450 -0
  5. package/WAProto/index.d.ts +48955 -0
  6. package/WAProto/index.js +151420 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/WASignalGroup/sender_message_key.js +39 -0
  22. package/lib/Defaults/baileys-version.json +3 -0
  23. package/lib/Defaults/index.d.ts +284 -0
  24. package/lib/Defaults/index.js +120 -0
  25. package/lib/Defaults/phonenumber-mcc.json +223 -0
  26. package/lib/Signal/libsignal.d.ts +3 -0
  27. package/lib/Signal/libsignal.js +161 -0
  28. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  29. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  30. package/lib/Socket/Client/index.d.ts +2 -0
  31. package/lib/Socket/Client/index.js +18 -0
  32. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  33. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  34. package/lib/Socket/Client/types.d.ts +17 -0
  35. package/lib/Socket/Client/types.js +13 -0
  36. package/lib/Socket/Client/websocket.d.ts +12 -0
  37. package/lib/Socket/Client/websocket.js +62 -0
  38. package/lib/Socket/business.d.ts +170 -0
  39. package/lib/Socket/business.js +260 -0
  40. package/lib/Socket/chats.d.ts +81 -0
  41. package/lib/Socket/chats.js +871 -0
  42. package/lib/Socket/groups.d.ts +115 -0
  43. package/lib/Socket/groups.js +304 -0
  44. package/lib/Socket/index.d.ts +172 -0
  45. package/lib/Socket/index.js +10 -0
  46. package/lib/Socket/messages-recv.d.ts +158 -0
  47. package/lib/Socket/messages-recv.js +966 -0
  48. package/lib/Socket/messages-send.d.ts +155 -0
  49. package/lib/Socket/messages-send.js +1021 -0
  50. package/lib/Socket/newsletter.d.ts +132 -0
  51. package/lib/Socket/newsletter.js +236 -0
  52. package/lib/Socket/registration.d.ts +264 -0
  53. package/lib/Socket/registration.js +166 -0
  54. package/lib/Socket/socket.d.ts +44 -0
  55. package/lib/Socket/socket.js +666 -0
  56. package/lib/Socket/usync.d.ts +37 -0
  57. package/lib/Socket/usync.js +70 -0
  58. package/lib/Store/index.d.ts +3 -0
  59. package/lib/Store/index.js +10 -0
  60. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  61. package/lib/Store/make-cache-manager-store.js +83 -0
  62. package/lib/Store/make-in-memory-store.d.ts +118 -0
  63. package/lib/Store/make-in-memory-store.js +431 -0
  64. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  65. package/lib/Store/make-ordered-dictionary.js +81 -0
  66. package/lib/Store/object-repository.d.ts +10 -0
  67. package/lib/Store/object-repository.js +27 -0
  68. package/lib/Types/Auth.d.ts +109 -0
  69. package/lib/Types/Auth.js +2 -0
  70. package/lib/Types/Call.d.ts +13 -0
  71. package/lib/Types/Call.js +2 -0
  72. package/lib/Types/Chat.d.ts +107 -0
  73. package/lib/Types/Chat.js +4 -0
  74. package/lib/Types/Contact.d.ts +19 -0
  75. package/lib/Types/Contact.js +2 -0
  76. package/lib/Types/Events.d.ts +172 -0
  77. package/lib/Types/Events.js +2 -0
  78. package/lib/Types/GroupMetadata.d.ts +56 -0
  79. package/lib/Types/GroupMetadata.js +2 -0
  80. package/lib/Types/Label.d.ts +46 -0
  81. package/lib/Types/Label.js +27 -0
  82. package/lib/Types/LabelAssociation.d.ts +29 -0
  83. package/lib/Types/LabelAssociation.js +9 -0
  84. package/lib/Types/Message.d.ts +433 -0
  85. package/lib/Types/Message.js +9 -0
  86. package/lib/Types/Newsletter.d.ts +92 -0
  87. package/lib/Types/Newsletter.js +32 -0
  88. package/lib/Types/Product.d.ts +78 -0
  89. package/lib/Types/Product.js +2 -0
  90. package/lib/Types/Signal.d.ts +57 -0
  91. package/lib/Types/Signal.js +2 -0
  92. package/lib/Types/Socket.d.ts +114 -0
  93. package/lib/Types/Socket.js +2 -0
  94. package/lib/Types/State.d.ts +27 -0
  95. package/lib/Types/State.js +2 -0
  96. package/lib/Types/USync.d.ts +25 -0
  97. package/lib/Types/USync.js +2 -0
  98. package/lib/Types/index.d.ts +66 -0
  99. package/lib/Types/index.js +42 -0
  100. package/lib/Utils/auth-utils.d.ts +18 -0
  101. package/lib/Utils/auth-utils.js +206 -0
  102. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  103. package/lib/Utils/baileys-event-stream.js +63 -0
  104. package/lib/Utils/business.d.ts +22 -0
  105. package/lib/Utils/business.js +234 -0
  106. package/lib/Utils/chat-utils.d.ts +70 -0
  107. package/lib/Utils/chat-utils.js +745 -0
  108. package/lib/Utils/crypto.d.ts +40 -0
  109. package/lib/Utils/crypto.js +163 -0
  110. package/lib/Utils/decode-wa-message.d.ts +36 -0
  111. package/lib/Utils/decode-wa-message.js +226 -0
  112. package/lib/Utils/event-buffer.d.ts +35 -0
  113. package/lib/Utils/event-buffer.js +514 -0
  114. package/lib/Utils/generics.d.ts +88 -0
  115. package/lib/Utils/generics.js +401 -0
  116. package/lib/Utils/history.d.ts +19 -0
  117. package/lib/Utils/history.js +94 -0
  118. package/lib/Utils/index.d.ts +17 -0
  119. package/lib/Utils/index.js +33 -0
  120. package/lib/Utils/link-preview.d.ts +21 -0
  121. package/lib/Utils/link-preview.js +93 -0
  122. package/lib/Utils/logger.d.ts +2 -0
  123. package/lib/Utils/logger.js +7 -0
  124. package/lib/Utils/lt-hash.d.ts +12 -0
  125. package/lib/Utils/lt-hash.js +51 -0
  126. package/lib/Utils/make-mutex.d.ts +7 -0
  127. package/lib/Utils/make-mutex.js +43 -0
  128. package/lib/Utils/messages-media.d.ts +113 -0
  129. package/lib/Utils/messages-media.js +722 -0
  130. package/lib/Utils/messages.d.ts +77 -0
  131. package/lib/Utils/messages.js +1217 -0
  132. package/lib/Utils/noise-handler.d.ts +20 -0
  133. package/lib/Utils/noise-handler.js +155 -0
  134. package/lib/Utils/process-message.d.ts +41 -0
  135. package/lib/Utils/process-message.js +321 -0
  136. package/lib/Utils/signal.d.ts +33 -0
  137. package/lib/Utils/signal.js +143 -0
  138. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  139. package/lib/Utils/use-multi-file-auth-state.js +88 -0
  140. package/lib/Utils/validate-connection.d.ts +11 -0
  141. package/lib/Utils/validate-connection.js +205 -0
  142. package/lib/WABinary/constants.d.ts +27 -0
  143. package/lib/WABinary/constants.js +40 -0
  144. package/lib/WABinary/decode.d.ts +6 -0
  145. package/lib/WABinary/decode.js +262 -0
  146. package/lib/WABinary/encode.d.ts +2 -0
  147. package/lib/WABinary/encode.js +244 -0
  148. package/lib/WABinary/generic-utils.d.ts +14 -0
  149. package/lib/WABinary/generic-utils.js +110 -0
  150. package/lib/WABinary/index.d.ts +5 -0
  151. package/lib/WABinary/index.js +21 -0
  152. package/lib/WABinary/jid-utils.d.ts +31 -0
  153. package/lib/WABinary/jid-utils.js +62 -0
  154. package/lib/WABinary/types.d.ts +18 -0
  155. package/lib/WABinary/types.js +2 -0
  156. package/lib/WAM/BinaryInfo.d.ts +8 -0
  157. package/lib/WAM/BinaryInfo.js +13 -0
  158. package/lib/WAM/constants.d.ts +38 -0
  159. package/lib/WAM/constants.js +15350 -0
  160. package/lib/WAM/encode.d.ts +2 -0
  161. package/lib/WAM/encode.js +155 -0
  162. package/lib/WAM/index.d.ts +3 -0
  163. package/lib/WAM/index.js +19 -0
  164. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  167. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  168. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  170. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  172. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  173. package/lib/WAUSync/Protocols/index.js +20 -0
  174. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  175. package/lib/WAUSync/USyncQuery.js +79 -0
  176. package/lib/WAUSync/USyncUser.d.ts +10 -0
  177. package/lib/WAUSync/USyncUser.js +22 -0
  178. package/lib/WAUSync/index.d.ts +3 -0
  179. package/lib/WAUSync/index.js +19 -0
  180. package/lib/index.d.ts +12 -0
  181. package/lib/index.js +31 -0
  182. package/package.json +116 -0
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,114 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import type { Agent } from 'https';
3
+ import type { Logger } from 'pino';
4
+ import type { URL } from 'url';
5
+ import { proto } from '../../WAProto';
6
+ import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth';
7
+ import { GroupMetadata } from './GroupMetadata';
8
+ import { MediaConnInfo } from './Message';
9
+ import { SignalRepository } from './Signal';
10
+ export type WAVersion = [number, number, number];
11
+ export type WABrowserDescription = [string, string, string];
12
+ export type CacheStore = {
13
+ /** get a cached key and change the stats */
14
+ get<T>(key: string): T | undefined;
15
+ /** set a key in the cache */
16
+ set<T>(key: string, value: T): void;
17
+ /** delete a key from the cache */
18
+ del(key: string): void;
19
+ /** flush all data */
20
+ flushAll(): void;
21
+ };
22
+ export type SocketConfig = {
23
+ /** the WS url to connect to WA */
24
+ waWebSocketUrl: string | URL;
25
+ /** Fails the connection if the socket times out in this interval */
26
+ connectTimeoutMs: number;
27
+ /** Default timeout for queries, undefined for no timeout */
28
+ defaultQueryTimeoutMs: number | undefined;
29
+ /** ping-pong interval for WS connection */
30
+ keepAliveIntervalMs: number;
31
+ /** should baileys use the mobile api instead of the multi device api */
32
+ mobile?: boolean;
33
+ /** proxy agent */
34
+ agent?: Agent;
35
+ /** pino logger */
36
+ logger: Logger;
37
+ /** version to connect with */
38
+ version: WAVersion;
39
+ /** override browser config */
40
+ browser: WABrowserDescription;
41
+ /** agent used for fetch requests -- uploading/downloading media */
42
+ fetchAgent?: Agent;
43
+ /** should events be emitted for actions done by this socket connection */
44
+ emitOwnEvents: boolean;
45
+ /** custom upload hosts to upload media to */
46
+ customUploadHosts: MediaConnInfo['hosts'];
47
+ /** time to wait between sending new retry requests */
48
+ retryRequestDelayMs: number;
49
+ /** max retry count */
50
+ maxMsgRetryCount: number;
51
+ /** time to wait for the generation of the next QR in ms */
52
+ qrTimeout?: number;
53
+ /** provide an auth state object to maintain the auth state */
54
+ auth: AuthenticationState;
55
+ /** manage history processing with this control; by default will sync up everything */
56
+ shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean;
57
+ /** transaction capability options for SignalKeyStore */
58
+ transactionOpts: TransactionCapabilityOptions;
59
+ /** marks the client as online whenever the socket successfully connects */
60
+ markOnlineOnConnect: boolean;
61
+ /** alphanumeric country code (USA -> US) for the number used */
62
+ countryCode: string;
63
+ /** provide a cache to store media, so does not have to be re-uploaded */
64
+ mediaCache?: CacheStore;
65
+ /**
66
+ * map to store the retry counts for failed messages;
67
+ * used to determine whether to retry a message or not */
68
+ msgRetryCounterCache?: CacheStore;
69
+ /** provide a cache to store a user's device list */
70
+ userDevicesCache?: CacheStore;
71
+ /** cache to store call offers */
72
+ callOfferCache?: CacheStore;
73
+ /** cache to track placeholder resends */
74
+ placeholderResendCache?: CacheStore;
75
+ /** width for link preview images */
76
+ linkPreviewImageThumbnailWidth: number;
77
+ /** Should Baileys ask the phone for full history, will be received async */
78
+ syncFullHistory: boolean;
79
+ /** Should baileys fire init queries automatically, default true */
80
+ fireInitQueries: boolean;
81
+ /**
82
+ * generate a high quality link preview,
83
+ * entails uploading the jpegThumbnail to WA
84
+ * */
85
+ generateHighQualityLinkPreview: boolean;
86
+ /**
87
+ * Returns if a jid should be ignored,
88
+ * no event for that jid will be triggered.
89
+ * Messages from that jid will also not be decrypted
90
+ * */
91
+ shouldIgnoreJid: (jid: string) => boolean | undefined;
92
+ /**
93
+ * Optionally patch the message before sending out
94
+ * */
95
+ patchMessageBeforeSending: (msg: proto.IMessage, recipientJids: string[]) => Promise<proto.IMessage> | proto.IMessage;
96
+ /** verify app state MACs */
97
+ appStateMacVerification: {
98
+ patch: boolean;
99
+ snapshot: boolean;
100
+ };
101
+ /** options for axios */
102
+ options: AxiosRequestConfig<{}>;
103
+ /**
104
+ * fetch a message from your store
105
+ * implement this so that messages failed to send
106
+ * (solves the "this message can take a while" issue) can be retried
107
+ * */
108
+ getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>;
109
+ /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
110
+ cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
111
+ makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
112
+ /** Socket passthrough */
113
+ socket?: any;
114
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,27 @@
1
+ import { Contact } from './Contact';
2
+ export type WAConnectionState = 'open' | 'connecting' | 'close';
3
+ export type ConnectionState = {
4
+ /** connection is now open, connecting or closed */
5
+ connection: WAConnectionState;
6
+ /** the error that caused the connection to close */
7
+ lastDisconnect?: {
8
+ error: Error | undefined;
9
+ date: Date;
10
+ };
11
+ /** is this a new login */
12
+ isNewLogin?: boolean;
13
+ /** the current QR code */
14
+ qr?: string;
15
+ /** has the device received all pending notifications while it was offline */
16
+ receivedPendingNotifications?: boolean;
17
+ /** legacy connection options */
18
+ legacy?: {
19
+ phoneConnected: boolean;
20
+ user?: Contact;
21
+ };
22
+ /**
23
+ * if the client is shown as an active, online client.
24
+ * If this is false, the primary phone and other devices will receive notifs
25
+ * */
26
+ isOnline?: boolean;
27
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,25 @@
1
+ import { BinaryNode } from '../WABinary';
2
+ import { USyncUser } from '../WAUSync';
3
+ /**
4
+ * Defines the interface for a USyncQuery protocol
5
+ */
6
+ export interface USyncQueryProtocol {
7
+ /**
8
+ * The name of the protocol
9
+ */
10
+ name: string;
11
+ /**
12
+ * Defines what goes inside the query part of a USyncQuery
13
+ */
14
+ getQueryElement: () => BinaryNode;
15
+ /**
16
+ * Defines what goes inside the user part of a USyncQuery
17
+ */
18
+ getUserElement: (user: USyncUser) => BinaryNode | null;
19
+ /**
20
+ * Parse the result of the query
21
+ * @param data Data from the result
22
+ * @returns Whatever the protocol is supposed to return
23
+ */
24
+ parser: (data: BinaryNode) => unknown;
25
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,66 @@
1
+ export * from './Auth';
2
+ export * from './GroupMetadata';
3
+ export * from './Chat';
4
+ export * from './Contact';
5
+ export * from './State';
6
+ export * from './Message';
7
+ export * from './Newsletter';
8
+ export * from './Socket';
9
+ export * from './Events';
10
+ export * from './Product';
11
+ export * from './Call';
12
+ export * from './Signal';
13
+ import { AuthenticationState } from './Auth';
14
+ import { SocketConfig } from './Socket';
15
+ export type UserFacingSocketConfig = Partial<SocketConfig> & {
16
+ auth: AuthenticationState;
17
+ };
18
+ export type BrowsersMap = {
19
+ ubuntu(browser: string): [string, string, string];
20
+ macOS(browser: string): [string, string, string];
21
+ baileys(browser: string): [string, string, string];
22
+ windows(browser: string): [string, string, string];
23
+ iOS(browser: string): [string, string, string];
24
+ linux(browser: string): [string, string, string];
25
+ appropriate(browser: string): [string, string, string];
26
+ };
27
+ export declare enum DisconnectReason {
28
+ connectionClosed = 428,
29
+ connectionLost = 408,
30
+ connectionReplaced = 440,
31
+ timedOut = 408,
32
+ loggedOut = 401,
33
+ badSession = 500,
34
+ restartRequired = 515,
35
+ multideviceMismatch = 411,
36
+ forbidden = 403,
37
+ unavailableService = 503
38
+ }
39
+ export type WAInitResponse = {
40
+ ref: string;
41
+ ttl: number;
42
+ status: 200;
43
+ };
44
+ export type WABusinessHoursConfig = {
45
+ day_of_week: string;
46
+ mode: string;
47
+ open_time?: number;
48
+ close_time?: number;
49
+ };
50
+ export type WABusinessProfile = {
51
+ description: string;
52
+ email: string | undefined;
53
+ business_hours: {
54
+ timezone?: string;
55
+ config?: WABusinessHoursConfig[];
56
+ business_config?: WABusinessHoursConfig[];
57
+ };
58
+ website: string[];
59
+ category?: string;
60
+ wid?: string;
61
+ address?: string;
62
+ };
63
+ export type CurveKeyPair = {
64
+ private: Uint8Array;
65
+ public: Uint8Array;
66
+ };
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.DisconnectReason = void 0;
18
+ __exportStar(require("./Auth"), exports);
19
+ __exportStar(require("./GroupMetadata"), exports);
20
+ __exportStar(require("./Chat"), exports);
21
+ __exportStar(require("./Contact"), exports);
22
+ __exportStar(require("./State"), exports);
23
+ __exportStar(require("./Message"), exports);
24
+ __exportStar(require("./Newsletter"), exports);
25
+ __exportStar(require("./Socket"), exports);
26
+ __exportStar(require("./Events"), exports);
27
+ __exportStar(require("./Product"), exports);
28
+ __exportStar(require("./Call"), exports);
29
+ __exportStar(require("./Signal"), exports);
30
+ var DisconnectReason;
31
+ (function (DisconnectReason) {
32
+ DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
33
+ DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
34
+ DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
35
+ DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
36
+ DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
37
+ DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
38
+ DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
39
+ DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
40
+ DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
41
+ DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
42
+ })(DisconnectReason || (exports.DisconnectReason = DisconnectReason = {}));
@@ -0,0 +1,18 @@
1
+ import type { Logger } from 'pino';
2
+ import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
3
+ /**
4
+ * Adds caching capability to a SignalKeyStore
5
+ * @param store the store to add caching to
6
+ * @param logger to log trace events
7
+ * @param _cache cache store to use
8
+ */
9
+ export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: Logger, _cache?: CacheStore): SignalKeyStore;
10
+ /**
11
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
12
+ * this allows batch read & write operations & improves the performance of the lib
13
+ * @param state the key store to apply this capability to
14
+ * @param logger logger to log events
15
+ * @returns SignalKeyStore with transaction capability
16
+ */
17
+ export declare const addTransactionCapability: (state: SignalKeyStore, logger: Logger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
+ export declare const initAuthCreds: () => AuthenticationCreds;
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.initAuthCreds = exports.addTransactionCapability = void 0;
7
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
8
+ const crypto_1 = require("crypto");
9
+ const node_cache_1 = __importDefault(require("node-cache"));
10
+ const uuid_1 = require("uuid");
11
+ const Defaults_1 = require("../Defaults");
12
+ const crypto_2 = require("./crypto");
13
+ const generics_1 = require("./generics");
14
+ /**
15
+ * Adds caching capability to a SignalKeyStore
16
+ * @param store the store to add caching to
17
+ * @param logger to log trace events
18
+ * @param _cache cache store to use
19
+ */
20
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
21
+ const cache = _cache || new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
23
+ useClones: false,
24
+ deleteOnExpire: true,
25
+ });
26
+ function getUniqueId(type, id) {
27
+ return `${type}.${id}`;
28
+ }
29
+ return {
30
+ async get(type, ids) {
31
+ const data = {};
32
+ const idsToFetch = [];
33
+ for (const id of ids) {
34
+ const item = cache.get(getUniqueId(type, id));
35
+ if (typeof item !== 'undefined') {
36
+ data[id] = item;
37
+ }
38
+ else {
39
+ idsToFetch.push(id);
40
+ }
41
+ }
42
+ if (idsToFetch.length) {
43
+ logger.trace({ items: idsToFetch.length }, 'loading from store');
44
+ const fetched = await store.get(type, idsToFetch);
45
+ for (const id of idsToFetch) {
46
+ const item = fetched[id];
47
+ if (item) {
48
+ data[id] = item;
49
+ cache.set(getUniqueId(type, id), item);
50
+ }
51
+ }
52
+ }
53
+ return data;
54
+ },
55
+ async set(data) {
56
+ let keys = 0;
57
+ for (const type in data) {
58
+ for (const id in data[type]) {
59
+ cache.set(getUniqueId(type, id), data[type][id]);
60
+ keys += 1;
61
+ }
62
+ }
63
+ logger.trace({ keys }, 'updated cache');
64
+ await store.set(data);
65
+ },
66
+ async clear() {
67
+ var _a;
68
+ cache.flushAll();
69
+ await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
70
+ }
71
+ };
72
+ }
73
+ /**
74
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
75
+ * this allows batch read & write operations & improves the performance of the lib
76
+ * @param state the key store to apply this capability to
77
+ * @param logger logger to log events
78
+ * @returns SignalKeyStore with transaction capability
79
+ */
80
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
81
+ // number of queries made to the DB during the transaction
82
+ // only there for logging purposes
83
+ let dbQueriesInTransaction = 0;
84
+ let transactionCache = {};
85
+ let mutations = {};
86
+ let transactionsInProgress = 0;
87
+ return {
88
+ get: async (type, ids) => {
89
+ if (isInTransaction()) {
90
+ const dict = transactionCache[type];
91
+ const idsRequiringFetch = dict
92
+ ? ids.filter(item => typeof dict[item] === 'undefined')
93
+ : ids;
94
+ // only fetch if there are any items to fetch
95
+ if (idsRequiringFetch.length) {
96
+ dbQueriesInTransaction += 1;
97
+ const result = await state.get(type, idsRequiringFetch);
98
+ transactionCache[type] || (transactionCache[type] = {});
99
+ Object.assign(transactionCache[type], result);
100
+ }
101
+ return ids.reduce((dict, id) => {
102
+ var _a;
103
+ const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
104
+ if (value) {
105
+ dict[id] = value;
106
+ }
107
+ return dict;
108
+ }, {});
109
+ }
110
+ else {
111
+ return state.get(type, ids);
112
+ }
113
+ },
114
+ set: data => {
115
+ if (isInTransaction()) {
116
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
117
+ for (const key in data) {
118
+ transactionCache[key] = transactionCache[key] || {};
119
+ Object.assign(transactionCache[key], data[key]);
120
+ mutations[key] = mutations[key] || {};
121
+ Object.assign(mutations[key], data[key]);
122
+ }
123
+ }
124
+ else {
125
+ return state.set(data);
126
+ }
127
+ },
128
+ isInTransaction,
129
+ async transaction(work) {
130
+ let result;
131
+ transactionsInProgress += 1;
132
+ if (transactionsInProgress === 1) {
133
+ logger.trace('entering transaction');
134
+ }
135
+ try {
136
+ result = await work();
137
+ // commit if this is the outermost transaction
138
+ if (transactionsInProgress === 1) {
139
+ if (Object.keys(mutations).length) {
140
+ logger.trace('committing transaction');
141
+ // retry mechanism to ensure we've some recovery
142
+ // in case a transaction fails in the first attempt
143
+ let tries = maxCommitRetries;
144
+ while (tries) {
145
+ tries -= 1;
146
+ try {
147
+ await state.set(mutations);
148
+ logger.trace({ dbQueriesInTransaction }, 'committed transaction');
149
+ break;
150
+ }
151
+ catch (error) {
152
+ logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
153
+ await (0, generics_1.delay)(delayBetweenTriesMs);
154
+ }
155
+ }
156
+ }
157
+ else {
158
+ logger.trace('no mutations in transaction');
159
+ }
160
+ }
161
+ }
162
+ finally {
163
+ transactionsInProgress -= 1;
164
+ if (transactionsInProgress === 0) {
165
+ transactionCache = {};
166
+ mutations = {};
167
+ dbQueriesInTransaction = 0;
168
+ }
169
+ }
170
+ return result;
171
+ }
172
+ };
173
+ function isInTransaction() {
174
+ return transactionsInProgress > 0;
175
+ }
176
+ };
177
+ exports.addTransactionCapability = addTransactionCapability;
178
+ const initAuthCreds = () => {
179
+ const identityKey = crypto_2.Curve.generateKeyPair();
180
+ return {
181
+ noiseKey: crypto_2.Curve.generateKeyPair(),
182
+ pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
183
+ signedIdentityKey: identityKey,
184
+ signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
185
+ registrationId: (0, generics_1.generateRegistrationId)(),
186
+ advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
187
+ processedHistoryMessages: [],
188
+ nextPreKeyId: 1,
189
+ firstUnuploadedPreKeyId: 1,
190
+ accountSyncCounter: 0,
191
+ accountSettings: {
192
+ unarchiveChats: false
193
+ },
194
+ // mobile creds
195
+ deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
+ phoneId: (0, uuid_1.v4)(),
197
+ identityId: (0, crypto_1.randomBytes)(20),
198
+ registered: false,
199
+ backupToken: (0, crypto_1.randomBytes)(20),
200
+ registration: {},
201
+ pairingCode: undefined,
202
+ lastPropHash: undefined,
203
+ routingInfo: undefined,
204
+ };
205
+ };
206
+ exports.initAuthCreds = initAuthCreds;
@@ -0,0 +1,16 @@
1
+ import type { BaileysEventEmitter } from '../Types';
2
+ /**
3
+ * Captures events from a baileys event emitter & stores them in a file
4
+ * @param ev The event emitter to read events from
5
+ * @param filename File to save to
6
+ */
7
+ export declare const captureEventStream: (ev: BaileysEventEmitter, filename: string) => void;
8
+ /**
9
+ * Read event file and emit events from there
10
+ * @param filename filename containing event data
11
+ * @param delayIntervalMs delay between each event emit
12
+ */
13
+ export declare const readAndEmitEventStream: (filename: string, delayIntervalMs?: number) => {
14
+ ev: BaileysEventEmitter;
15
+ task: Promise<void>;
16
+ };
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readAndEmitEventStream = exports.captureEventStream = void 0;
7
+ const events_1 = __importDefault(require("events"));
8
+ const fs_1 = require("fs");
9
+ const promises_1 = require("fs/promises");
10
+ const readline_1 = require("readline");
11
+ const generics_1 = require("./generics");
12
+ const make_mutex_1 = require("./make-mutex");
13
+ /**
14
+ * Captures events from a baileys event emitter & stores them in a file
15
+ * @param ev The event emitter to read events from
16
+ * @param filename File to save to
17
+ */
18
+ const captureEventStream = (ev, filename) => {
19
+ const oldEmit = ev.emit;
20
+ // write mutex so data is appended in order
21
+ const writeMutex = (0, make_mutex_1.makeMutex)();
22
+ // monkey patch eventemitter to capture all events
23
+ ev.emit = function (...args) {
24
+ const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
25
+ const result = oldEmit.apply(ev, args);
26
+ writeMutex.mutex(async () => {
27
+ await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
28
+ });
29
+ return result;
30
+ };
31
+ };
32
+ exports.captureEventStream = captureEventStream;
33
+ /**
34
+ * Read event file and emit events from there
35
+ * @param filename filename containing event data
36
+ * @param delayIntervalMs delay between each event emit
37
+ */
38
+ const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
39
+ const ev = new events_1.default();
40
+ const fireEvents = async () => {
41
+ // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
42
+ const fileStream = (0, fs_1.createReadStream)(filename);
43
+ const rl = (0, readline_1.createInterface)({
44
+ input: fileStream,
45
+ crlfDelay: Infinity
46
+ });
47
+ // Note: we use the crlfDelay option to recognize all instances of CR LF
48
+ // ('\r\n') in input.txt as a single line break.
49
+ for await (const line of rl) {
50
+ if (line) {
51
+ const { event, data } = JSON.parse(line);
52
+ ev.emit(event, data);
53
+ delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
54
+ }
55
+ }
56
+ fileStream.close();
57
+ };
58
+ return {
59
+ ev,
60
+ task: fireEvents()
61
+ };
62
+ };
63
+ exports.readAndEmitEventStream = readAndEmitEventStream;
@@ -0,0 +1,22 @@
1
+ import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
+ import { BinaryNode } from '../WABinary';
3
+ export declare const parseCatalogNode: (node: BinaryNode) => {
4
+ products: Product[];
5
+ nextPageCursor: any;
6
+ };
7
+ export declare const parseCollectionsNode: (node: BinaryNode) => {
8
+ collections: CatalogCollection[];
9
+ };
10
+ export declare const parseOrderDetailsNode: (node: BinaryNode) => OrderDetails;
11
+ export declare const toProductNode: (productId: string | undefined, product: ProductCreate | ProductUpdate) => BinaryNode;
12
+ export declare const parseProductNode: (productNode: BinaryNode) => Product;
13
+ /**
14
+ * Uploads images not already uploaded to WA's servers
15
+ */
16
+ export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs?: number): Promise<T>;
17
+ /**
18
+ * Uploads images not already uploaded to WA's servers
19
+ */
20
+ export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
21
+ url: string;
22
+ }[]>;