@d0v3riz/baileys 6.7.12 → 6.7.17

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 (161) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +35 -1267
  3. package/WAProto/index.d.ts +16106 -2739
  4. package/WAProto/index.js +128593 -73944
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/baileys-version.json +3 -3
  7. package/lib/Defaults/index.d.ts +51 -53
  8. package/lib/Defaults/index.js +105 -106
  9. package/lib/Signal/libsignal.d.ts +3 -3
  10. package/lib/Signal/libsignal.js +161 -152
  11. package/lib/Socket/Client/index.d.ts +2 -2
  12. package/lib/Socket/Client/index.js +18 -18
  13. package/lib/Socket/Client/types.d.ts +15 -17
  14. package/lib/Socket/Client/types.js +13 -13
  15. package/lib/Socket/Client/websocket.d.ts +12 -12
  16. package/lib/Socket/Client/websocket.js +62 -62
  17. package/lib/Socket/business.d.ts +146 -148
  18. package/lib/Socket/business.js +260 -260
  19. package/lib/Socket/chats.d.ts +85 -84
  20. package/lib/Socket/chats.js +880 -846
  21. package/lib/Socket/groups.d.ts +124 -123
  22. package/lib/Socket/groups.js +314 -314
  23. package/lib/Socket/index.d.ts +146 -148
  24. package/lib/Socket/index.js +10 -10
  25. package/lib/Socket/messages-recv.d.ts +135 -135
  26. package/lib/Socket/messages-recv.js +920 -913
  27. package/lib/Socket/messages-send.d.ts +130 -129
  28. package/lib/Socket/messages-send.js +683 -673
  29. package/lib/Socket/socket.d.ts +42 -45
  30. package/lib/Socket/socket.js +622 -622
  31. package/lib/Socket/usync.d.ts +36 -38
  32. package/lib/Socket/usync.js +70 -70
  33. package/lib/Types/Auth.d.ts +103 -105
  34. package/lib/Types/Auth.js +2 -2
  35. package/lib/Types/Call.d.ts +13 -13
  36. package/lib/Types/Call.js +2 -2
  37. package/lib/Types/Chat.d.ts +112 -107
  38. package/lib/Types/Chat.js +4 -4
  39. package/lib/Types/Contact.d.ts +19 -19
  40. package/lib/Types/Contact.js +2 -2
  41. package/lib/Types/Events.d.ts +172 -172
  42. package/lib/Types/Events.js +2 -2
  43. package/lib/Types/GroupMetadata.d.ts +56 -56
  44. package/lib/Types/GroupMetadata.js +2 -2
  45. package/lib/Types/Label.d.ts +46 -46
  46. package/lib/Types/Label.js +27 -27
  47. package/lib/Types/LabelAssociation.d.ts +29 -29
  48. package/lib/Types/LabelAssociation.js +9 -9
  49. package/lib/Types/Message.d.ts +269 -273
  50. package/lib/Types/Message.js +7 -9
  51. package/lib/Types/Product.d.ts +78 -78
  52. package/lib/Types/Product.js +2 -2
  53. package/lib/Types/Signal.d.ts +57 -57
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.d.ts +121 -118
  56. package/lib/Types/Socket.js +2 -2
  57. package/lib/Types/State.d.ts +27 -27
  58. package/lib/Types/State.js +2 -2
  59. package/lib/Types/USync.d.ts +25 -25
  60. package/lib/Types/USync.js +2 -2
  61. package/lib/Types/index.d.ts +63 -63
  62. package/lib/Types/index.js +41 -41
  63. package/lib/Utils/auth-utils.d.ts +18 -18
  64. package/lib/Utils/auth-utils.js +200 -200
  65. package/lib/Utils/baileys-event-stream.d.ts +16 -16
  66. package/lib/Utils/baileys-event-stream.js +63 -63
  67. package/lib/Utils/business.d.ts +22 -22
  68. package/lib/Utils/business.js +234 -234
  69. package/lib/Utils/chat-utils.d.ts +70 -72
  70. package/lib/Utils/chat-utils.js +745 -745
  71. package/lib/Utils/crypto.d.ts +40 -42
  72. package/lib/Utils/crypto.js +193 -153
  73. package/lib/Utils/decode-wa-message.d.ts +36 -36
  74. package/lib/Utils/decode-wa-message.js +205 -205
  75. package/lib/Utils/event-buffer.d.ts +35 -35
  76. package/lib/Utils/event-buffer.js +520 -520
  77. package/lib/Utils/generics.d.ts +90 -94
  78. package/lib/Utils/generics.js +398 -421
  79. package/lib/Utils/history.d.ts +19 -19
  80. package/lib/Utils/history.js +94 -94
  81. package/lib/Utils/index.d.ts +17 -17
  82. package/lib/Utils/index.js +33 -33
  83. package/lib/Utils/link-preview.d.ts +21 -21
  84. package/lib/Utils/link-preview.js +126 -116
  85. package/lib/Utils/logger.d.ts +11 -4
  86. package/lib/Utils/logger.js +7 -7
  87. package/lib/Utils/lt-hash.d.ts +12 -12
  88. package/lib/Utils/lt-hash.js +51 -51
  89. package/lib/Utils/make-mutex.d.ts +7 -7
  90. package/lib/Utils/make-mutex.js +44 -44
  91. package/lib/Utils/messages-media.d.ts +104 -108
  92. package/lib/Utils/messages-media.js +677 -667
  93. package/lib/Utils/messages.d.ts +75 -78
  94. package/lib/Utils/messages.js +765 -762
  95. package/lib/Utils/noise-handler.d.ts +19 -21
  96. package/lib/Utils/noise-handler.js +150 -150
  97. package/lib/Utils/process-message.d.ts +41 -42
  98. package/lib/Utils/process-message.js +382 -371
  99. package/lib/Utils/signal.d.ts +33 -33
  100. package/lib/Utils/signal.js +153 -153
  101. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -12
  102. package/lib/Utils/use-multi-file-auth-state.js +125 -94
  103. package/lib/Utils/validate-connection.d.ts +10 -10
  104. package/lib/Utils/validate-connection.js +175 -175
  105. package/lib/WABinary/constants.d.ts +27 -27
  106. package/lib/WABinary/constants.js +40 -40
  107. package/lib/WABinary/decode.d.ts +6 -8
  108. package/lib/WABinary/decode.js +264 -254
  109. package/lib/WABinary/encode.d.ts +2 -4
  110. package/lib/WABinary/encode.js +252 -234
  111. package/lib/WABinary/generic-utils.d.ts +14 -16
  112. package/lib/WABinary/generic-utils.js +110 -110
  113. package/lib/WABinary/index.d.ts +5 -5
  114. package/lib/WABinary/index.js +21 -21
  115. package/lib/WABinary/jid-utils.d.ts +33 -31
  116. package/lib/WABinary/jid-utils.js +66 -62
  117. package/lib/WABinary/types.d.ts +18 -18
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.d.ts +8 -18
  120. package/lib/WAM/BinaryInfo.js +13 -13
  121. package/lib/WAM/constants.d.ts +39 -39
  122. package/lib/WAM/constants.js +15350 -15350
  123. package/lib/WAM/encode.d.ts +2 -4
  124. package/lib/WAM/encode.js +155 -155
  125. package/lib/WAM/index.d.ts +3 -3
  126. package/lib/WAM/index.js +19 -19
  127. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  128. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -32
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -22
  130. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -57
  131. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -12
  132. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -30
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -12
  134. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -42
  135. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  136. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  137. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  138. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  139. package/lib/WAUSync/Protocols/index.d.ts +4 -4
  140. package/lib/WAUSync/Protocols/index.js +20 -20
  141. package/lib/WAUSync/USyncQuery.d.ts +28 -26
  142. package/lib/WAUSync/USyncQuery.js +89 -79
  143. package/lib/WAUSync/USyncUser.d.ts +12 -10
  144. package/lib/WAUSync/USyncUser.js +26 -22
  145. package/lib/WAUSync/index.d.ts +3 -3
  146. package/lib/WAUSync/index.js +19 -19
  147. package/lib/index.d.ts +11 -12
  148. package/lib/index.js +30 -31
  149. package/package.json +27 -35
  150. package/WAProto/GenerateStatics.sh +0 -4
  151. package/WAProto/WAProto.proto +0 -3344
  152. package/lib/Store/index.d.ts +0 -3
  153. package/lib/Store/index.js +0 -10
  154. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  155. package/lib/Store/make-cache-manager-store.js +0 -83
  156. package/lib/Store/make-in-memory-store.d.ts +0 -118
  157. package/lib/Store/make-in-memory-store.js +0 -420
  158. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  159. package/lib/Store/make-ordered-dictionary.js +0 -81
  160. package/lib/Store/object-repository.d.ts +0 -10
  161. package/lib/Store/object-repository.js +0 -27
@@ -1,63 +1,63 @@
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 './Socket';
8
- export * from './Events';
9
- export * from './Product';
10
- export * from './Call';
11
- export * from './Signal';
12
- import { AuthenticationState } from './Auth';
13
- import { SocketConfig } from './Socket';
14
- export type UserFacingSocketConfig = Partial<SocketConfig> & {
15
- auth: AuthenticationState;
16
- };
17
- export type BrowsersMap = {
18
- ubuntu(browser: string): [string, string, string];
19
- macOS(browser: string): [string, string, string];
20
- baileys(browser: string): [string, string, string];
21
- windows(browser: string): [string, string, string];
22
- appropriate(browser: string): [string, string, string];
23
- };
24
- export declare enum DisconnectReason {
25
- connectionClosed = 428,
26
- connectionLost = 408,
27
- connectionReplaced = 440,
28
- timedOut = 408,
29
- loggedOut = 401,
30
- badSession = 500,
31
- restartRequired = 515,
32
- multideviceMismatch = 411,
33
- forbidden = 403,
34
- unavailableService = 503
35
- }
36
- export type WAInitResponse = {
37
- ref: string;
38
- ttl: number;
39
- status: 200;
40
- };
41
- export type WABusinessHoursConfig = {
42
- day_of_week: string;
43
- mode: string;
44
- open_time?: number;
45
- close_time?: number;
46
- };
47
- export type WABusinessProfile = {
48
- description: string;
49
- email: string | undefined;
50
- business_hours: {
51
- timezone?: string;
52
- config?: WABusinessHoursConfig[];
53
- business_config?: WABusinessHoursConfig[];
54
- };
55
- website: string[];
56
- category?: string;
57
- wid?: string;
58
- address?: string;
59
- };
60
- export type CurveKeyPair = {
61
- private: Uint8Array;
62
- public: Uint8Array;
63
- };
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 './Socket';
8
+ export * from './Events';
9
+ export * from './Product';
10
+ export * from './Call';
11
+ export * from './Signal';
12
+ import { AuthenticationState } from './Auth';
13
+ import { SocketConfig } from './Socket';
14
+ export type UserFacingSocketConfig = Partial<SocketConfig> & {
15
+ auth: AuthenticationState;
16
+ };
17
+ export type BrowsersMap = {
18
+ ubuntu(browser: string): [string, string, string];
19
+ macOS(browser: string): [string, string, string];
20
+ baileys(browser: string): [string, string, string];
21
+ windows(browser: string): [string, string, string];
22
+ appropriate(browser: string): [string, string, string];
23
+ };
24
+ export declare enum DisconnectReason {
25
+ connectionClosed = 428,
26
+ connectionLost = 408,
27
+ connectionReplaced = 440,
28
+ timedOut = 408,
29
+ loggedOut = 401,
30
+ badSession = 500,
31
+ restartRequired = 515,
32
+ multideviceMismatch = 411,
33
+ forbidden = 403,
34
+ unavailableService = 503
35
+ }
36
+ export type WAInitResponse = {
37
+ ref: string;
38
+ ttl: number;
39
+ status: 200;
40
+ };
41
+ export type WABusinessHoursConfig = {
42
+ day_of_week: string;
43
+ mode: string;
44
+ open_time?: number;
45
+ close_time?: number;
46
+ };
47
+ export type WABusinessProfile = {
48
+ description: string;
49
+ email: string | undefined;
50
+ business_hours: {
51
+ timezone?: string;
52
+ config?: WABusinessHoursConfig[];
53
+ business_config?: WABusinessHoursConfig[];
54
+ };
55
+ website: string[];
56
+ category?: string;
57
+ wid?: string;
58
+ address?: string;
59
+ };
60
+ export type CurveKeyPair = {
61
+ private: Uint8Array;
62
+ public: Uint8Array;
63
+ };
@@ -1,41 +1,41 @@
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("./Socket"), exports);
25
- __exportStar(require("./Events"), exports);
26
- __exportStar(require("./Product"), exports);
27
- __exportStar(require("./Call"), exports);
28
- __exportStar(require("./Signal"), exports);
29
- var DisconnectReason;
30
- (function (DisconnectReason) {
31
- DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
32
- DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
33
- DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
34
- DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
35
- DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
36
- DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
37
- DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
38
- DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
39
- DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
40
- DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
41
- })(DisconnectReason = exports.DisconnectReason || (exports.DisconnectReason = {}));
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("./Socket"), exports);
25
+ __exportStar(require("./Events"), exports);
26
+ __exportStar(require("./Product"), exports);
27
+ __exportStar(require("./Call"), exports);
28
+ __exportStar(require("./Signal"), exports);
29
+ var DisconnectReason;
30
+ (function (DisconnectReason) {
31
+ DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
32
+ DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
33
+ DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
34
+ DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
35
+ DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
36
+ DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
37
+ DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
38
+ DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
39
+ DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
40
+ DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
41
+ })(DisconnectReason || (exports.DisconnectReason = DisconnectReason = {}));
@@ -1,18 +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;
1
+ import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
2
+ import { ILogger } from './logger';
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?: ILogger, _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: ILogger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
+ export declare const initAuthCreds: () => AuthenticationCreds;
@@ -1,200 +1,200 @@
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 = exports.makeCacheableSignalKeyStore = void 0;
7
- const crypto_1 = require("crypto");
8
- const node_cache_1 = __importDefault(require("node-cache"));
9
- const Defaults_1 = require("../Defaults");
10
- const crypto_2 = require("./crypto");
11
- const generics_1 = require("./generics");
12
- /**
13
- * Adds caching capability to a SignalKeyStore
14
- * @param store the store to add caching to
15
- * @param logger to log trace events
16
- * @param _cache cache store to use
17
- */
18
- function makeCacheableSignalKeyStore(store, logger, _cache) {
19
- const cache = _cache || new node_cache_1.default({
20
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
21
- useClones: false,
22
- deleteOnExpire: true,
23
- });
24
- function getUniqueId(type, id) {
25
- return `${type}.${id}`;
26
- }
27
- return {
28
- async get(type, ids) {
29
- const data = {};
30
- const idsToFetch = [];
31
- for (const id of ids) {
32
- const item = cache.get(getUniqueId(type, id));
33
- if (typeof item !== 'undefined') {
34
- data[id] = item;
35
- }
36
- else {
37
- idsToFetch.push(id);
38
- }
39
- }
40
- if (idsToFetch.length) {
41
- logger.trace({ items: idsToFetch.length }, 'loading from store');
42
- const fetched = await store.get(type, idsToFetch);
43
- for (const id of idsToFetch) {
44
- const item = fetched[id];
45
- if (item) {
46
- data[id] = item;
47
- cache.set(getUniqueId(type, id), item);
48
- }
49
- }
50
- }
51
- return data;
52
- },
53
- async set(data) {
54
- let keys = 0;
55
- for (const type in data) {
56
- for (const id in data[type]) {
57
- cache.set(getUniqueId(type, id), data[type][id]);
58
- keys += 1;
59
- }
60
- }
61
- logger.trace({ keys }, 'updated cache');
62
- await store.set(data);
63
- },
64
- async clear() {
65
- var _a;
66
- cache.flushAll();
67
- await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
68
- }
69
- };
70
- }
71
- exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
72
- /**
73
- * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
74
- * this allows batch read & write operations & improves the performance of the lib
75
- * @param state the key store to apply this capability to
76
- * @param logger logger to log events
77
- * @returns SignalKeyStore with transaction capability
78
- */
79
- const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
80
- // number of queries made to the DB during the transaction
81
- // only there for logging purposes
82
- let dbQueriesInTransaction = 0;
83
- let transactionCache = {};
84
- let mutations = {};
85
- let transactionsInProgress = 0;
86
- return {
87
- get: async (type, ids) => {
88
- if (isInTransaction()) {
89
- const dict = transactionCache[type];
90
- const idsRequiringFetch = dict
91
- ? ids.filter(item => typeof dict[item] === 'undefined')
92
- : ids;
93
- // only fetch if there are any items to fetch
94
- if (idsRequiringFetch.length) {
95
- dbQueriesInTransaction += 1;
96
- const result = await state.get(type, idsRequiringFetch);
97
- transactionCache[type] || (transactionCache[type] = {});
98
- Object.assign(transactionCache[type], result);
99
- }
100
- return ids.reduce((dict, id) => {
101
- var _a;
102
- const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
103
- if (value) {
104
- dict[id] = value;
105
- }
106
- return dict;
107
- }, {});
108
- }
109
- else {
110
- return state.get(type, ids);
111
- }
112
- },
113
- set: data => {
114
- if (isInTransaction()) {
115
- logger.trace({ types: Object.keys(data) }, 'caching in transaction');
116
- for (const key in data) {
117
- transactionCache[key] = transactionCache[key] || {};
118
- Object.assign(transactionCache[key], data[key]);
119
- mutations[key] = mutations[key] || {};
120
- Object.assign(mutations[key], data[key]);
121
- }
122
- }
123
- else {
124
- return state.set(data);
125
- }
126
- },
127
- isInTransaction,
128
- async transaction(work) {
129
- let result;
130
- transactionsInProgress += 1;
131
- if (transactionsInProgress === 1) {
132
- logger.trace('entering transaction');
133
- }
134
- try {
135
- result = await work();
136
- // commit if this is the outermost transaction
137
- if (transactionsInProgress === 1) {
138
- if (Object.keys(mutations).length) {
139
- logger.trace('committing transaction');
140
- // retry mechanism to ensure we've some recovery
141
- // in case a transaction fails in the first attempt
142
- let tries = maxCommitRetries;
143
- while (tries) {
144
- tries -= 1;
145
- //eslint-disable-next-line max-depth
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
- registered: false,
195
- pairingCode: undefined,
196
- lastPropHash: undefined,
197
- routingInfo: undefined,
198
- };
199
- };
200
- exports.initAuthCreds = initAuthCreds;
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 node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const crypto_2 = require("./crypto");
12
+ const generics_1 = require("./generics");
13
+ /**
14
+ * Adds caching capability to a SignalKeyStore
15
+ * @param store the store to add caching to
16
+ * @param logger to log trace events
17
+ * @param _cache cache store to use
18
+ */
19
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
20
+ const cache = _cache || new node_cache_1.default({
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
22
+ useClones: false,
23
+ deleteOnExpire: true,
24
+ });
25
+ function getUniqueId(type, id) {
26
+ return `${type}.${id}`;
27
+ }
28
+ return {
29
+ async get(type, ids) {
30
+ const data = {};
31
+ const idsToFetch = [];
32
+ for (const id of ids) {
33
+ const item = cache.get(getUniqueId(type, id));
34
+ if (typeof item !== 'undefined') {
35
+ data[id] = item;
36
+ }
37
+ else {
38
+ idsToFetch.push(id);
39
+ }
40
+ }
41
+ if (idsToFetch.length) {
42
+ logger === null || logger === void 0 ? void 0 : logger.trace({ items: idsToFetch.length }, 'loading from store');
43
+ const fetched = await store.get(type, idsToFetch);
44
+ for (const id of idsToFetch) {
45
+ const item = fetched[id];
46
+ if (item) {
47
+ data[id] = item;
48
+ cache.set(getUniqueId(type, id), item);
49
+ }
50
+ }
51
+ }
52
+ return data;
53
+ },
54
+ async set(data) {
55
+ let keys = 0;
56
+ for (const type in data) {
57
+ for (const id in data[type]) {
58
+ cache.set(getUniqueId(type, id), data[type][id]);
59
+ keys += 1;
60
+ }
61
+ }
62
+ logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
63
+ await store.set(data);
64
+ },
65
+ async clear() {
66
+ var _a;
67
+ cache.flushAll();
68
+ await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
69
+ }
70
+ };
71
+ }
72
+ /**
73
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
74
+ * this allows batch read & write operations & improves the performance of the lib
75
+ * @param state the key store to apply this capability to
76
+ * @param logger logger to log events
77
+ * @returns SignalKeyStore with transaction capability
78
+ */
79
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
80
+ // number of queries made to the DB during the transaction
81
+ // only there for logging purposes
82
+ let dbQueriesInTransaction = 0;
83
+ let transactionCache = {};
84
+ let mutations = {};
85
+ let transactionsInProgress = 0;
86
+ return {
87
+ get: async (type, ids) => {
88
+ if (isInTransaction()) {
89
+ const dict = transactionCache[type];
90
+ const idsRequiringFetch = dict
91
+ ? ids.filter(item => typeof dict[item] === 'undefined')
92
+ : ids;
93
+ // only fetch if there are any items to fetch
94
+ if (idsRequiringFetch.length) {
95
+ dbQueriesInTransaction += 1;
96
+ const result = await state.get(type, idsRequiringFetch);
97
+ transactionCache[type] || (transactionCache[type] = {});
98
+ Object.assign(transactionCache[type], result);
99
+ }
100
+ return ids.reduce((dict, id) => {
101
+ var _a;
102
+ const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
103
+ if (value) {
104
+ dict[id] = value;
105
+ }
106
+ return dict;
107
+ }, {});
108
+ }
109
+ else {
110
+ return state.get(type, ids);
111
+ }
112
+ },
113
+ set: data => {
114
+ if (isInTransaction()) {
115
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
116
+ for (const key in data) {
117
+ transactionCache[key] = transactionCache[key] || {};
118
+ Object.assign(transactionCache[key], data[key]);
119
+ mutations[key] = mutations[key] || {};
120
+ Object.assign(mutations[key], data[key]);
121
+ }
122
+ }
123
+ else {
124
+ return state.set(data);
125
+ }
126
+ },
127
+ isInTransaction,
128
+ async transaction(work) {
129
+ let result;
130
+ transactionsInProgress += 1;
131
+ if (transactionsInProgress === 1) {
132
+ logger.trace('entering transaction');
133
+ }
134
+ try {
135
+ result = await work();
136
+ // commit if this is the outermost transaction
137
+ if (transactionsInProgress === 1) {
138
+ if (Object.keys(mutations).length) {
139
+ logger.trace('committing transaction');
140
+ // retry mechanism to ensure we've some recovery
141
+ // in case a transaction fails in the first attempt
142
+ let tries = maxCommitRetries;
143
+ while (tries) {
144
+ tries -= 1;
145
+ //eslint-disable-next-line max-depth
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
+ registered: false,
195
+ pairingCode: undefined,
196
+ lastPropHash: undefined,
197
+ routingInfo: undefined,
198
+ };
199
+ };
200
+ exports.initAuthCreds = initAuthCreds;