@hiroosy/baileys-lite 0.3.3 → 0.3.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiroosy/baileys-lite",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "A Lightweight Baileys built with NodeJs 18+",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,5 +1,5 @@
1
1
  import { promisify } from 'node:util'
2
- import { inflate } from 'node:zlib'
2
+ import { inflate, inflateSync } from 'node:zlib'
3
3
  import { randomBytes } from 'node:crypto'
4
4
  import { Boom } from '../foundation/boom.js'
5
5
  import * as constants from './wa-binary-constants.js'
@@ -255,10 +255,12 @@ const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
255
255
  }
256
256
 
257
257
  const inflatePromise = promisify(inflate)
258
+ const SYNC_INFLATE_MAX_BYTES = 256 * 1024
258
259
 
259
260
  export const decompressingIfRequired = async buffer => {
260
261
  if (2 & buffer.readUInt8()) {
261
- buffer = await inflatePromise(buffer.slice(1))
262
+ const compressed = buffer.subarray(1)
263
+ buffer = compressed.length <= SYNC_INFLATE_MAX_BYTES ? inflateSync(compressed) : await inflatePromise(compressed)
262
264
  } else {
263
265
  buffer = buffer.slice(1)
264
266
  }
package/src/defaults.js CHANGED
@@ -69,7 +69,8 @@ export const DEFAULT_CONNECTION_CONFIG = {
69
69
  disableStickyRouting: false,
70
70
  auth: undefined,
71
71
  markOnlineOnConnect: true,
72
- syncFullHistory: true,
72
+ syncFullHistory: false,
73
+ memoryTrim: { enabled: true },
73
74
  patchMessageBeforeSending: msg => msg,
74
75
  shouldSyncHistoryMessage: ({ syncType }) => syncType !== proto.HistorySync.HistorySyncType.FULL,
75
76
  shouldIgnoreJid: () => false,
@@ -1,14 +1,78 @@
1
+ const SIZE_NODE_BUDGET = 4000
2
+
3
+ export const estimateSize = value => {
4
+ let total = 0
5
+ let nodes = 0
6
+ const stack = [value]
7
+ const seen = new Set()
8
+ while (stack.length && nodes < SIZE_NODE_BUDGET) {
9
+ const v = stack.pop()
10
+ nodes++
11
+ switch (typeof v) {
12
+ case 'string':
13
+ total += 16 + v.length
14
+ break
15
+ case 'number':
16
+ case 'boolean':
17
+ case 'bigint':
18
+ total += 8
19
+ break
20
+ case 'object': {
21
+ if (v === null) {
22
+ total += 8
23
+ break
24
+ }
25
+ if (ArrayBuffer.isView(v)) {
26
+ total += 32 + v.byteLength
27
+ break
28
+ }
29
+ if (v instanceof ArrayBuffer) {
30
+ total += 32 + v.byteLength
31
+ break
32
+ }
33
+ if (seen.has(v)) break
34
+ seen.add(v)
35
+ if (Array.isArray(v)) {
36
+ total += 16 + v.length * 8
37
+ for (let i = 0; i < v.length; i++) stack.push(v[i])
38
+ } else {
39
+ const keys = Object.keys(v)
40
+ total += 32 + keys.length * 16
41
+ for (let i = 0; i < keys.length; i++) {
42
+ total += keys[i].length
43
+ stack.push(v[keys[i]])
44
+ }
45
+ }
46
+ break
47
+ }
48
+ default:
49
+ break
50
+ }
51
+ }
52
+ if (stack.length) total += stack.length * 64
53
+ return total
54
+ }
55
+
1
56
  export class Cache {
2
57
  constructor(options = {}) {
3
58
  this.ttl = options.ttl ?? (options.stdTTL ? options.stdTTL * 1000 : 0)
4
59
  this.max = options.max || Infinity
60
+ this.maxBytes = options.maxBytes || 0
61
+ this.sizeOf = options.sizeOf || estimateSize
5
62
  this.updateAgeOnGet = !!options.updateAgeOnGet
6
63
  this.dispose = options.dispose || (() => {})
7
64
  this._store = new Map()
65
+ this._bytes = 0
8
66
 
9
67
  if (this.ttl > 0) {
10
- this._sweeper = setInterval(() => this._sweep(), Math.min(this.ttl, 60_000))
11
- this._sweeper.unref?.()
68
+ const ref = new WeakRef(this)
69
+ const timer = setInterval(() => {
70
+ const cache = ref.deref()
71
+ if (cache) cache._sweep()
72
+ else clearInterval(timer)
73
+ }, Math.min(this.ttl, 60_000))
74
+ timer.unref?.()
75
+ this._sweeper = timer
12
76
  }
13
77
  }
14
78
 
@@ -16,13 +80,23 @@ export class Cache {
16
80
  return this.ttl > 0 && entry.expiresAt !== 0 && entry.expiresAt <= Date.now()
17
81
  }
18
82
 
83
+ _remove(key, entry) {
84
+ this._store.delete(key)
85
+ this._bytes -= entry.size
86
+ this.dispose(entry.value, key)
87
+ }
88
+
19
89
  _sweep() {
20
90
  const now = Date.now()
21
91
  for (const [key, entry] of this._store) {
22
- if (entry.expiresAt !== 0 && entry.expiresAt <= now) {
23
- this._store.delete(key)
24
- this.dispose(entry.value, key)
25
- }
92
+ if (entry.expiresAt !== 0 && entry.expiresAt <= now) this._remove(key, entry)
93
+ }
94
+ }
95
+
96
+ _evict() {
97
+ while (this._store.size > this.max || (this.maxBytes > 0 && this._bytes > this.maxBytes && this._store.size > 1)) {
98
+ const oldestKey = this._store.keys().next().value
99
+ this._remove(oldestKey, this._store.get(oldestKey))
26
100
  }
27
101
  }
28
102
 
@@ -30,13 +104,11 @@ export class Cache {
30
104
  const entry = this._store.get(key)
31
105
  if (!entry) return undefined
32
106
  if (this._isExpired(entry)) {
33
- this._store.delete(key)
34
- this.dispose(entry.value, key)
107
+ this._remove(key, entry)
35
108
  return undefined
36
109
  }
37
110
  if (this.updateAgeOnGet && this.ttl > 0) {
38
111
  entry.expiresAt = Date.now() + this.ttl
39
-
40
112
  this._store.delete(key)
41
113
  this._store.set(key, entry)
42
114
  }
@@ -44,17 +116,15 @@ export class Cache {
44
116
  }
45
117
 
46
118
  set(key, value) {
47
- if (this._store.has(key)) this._store.delete(key)
48
- this._store.set(key, {
49
- value,
50
- expiresAt: this.ttl > 0 ? Date.now() + this.ttl : 0
51
- })
52
- while (this._store.size > this.max) {
53
- const oldestKey = this._store.keys().next().value
54
- const oldest = this._store.get(oldestKey)
55
- this._store.delete(oldestKey)
56
- this.dispose(oldest.value, oldestKey)
119
+ const previous = this._store.get(key)
120
+ if (previous) {
121
+ this._store.delete(key)
122
+ this._bytes -= previous.size
57
123
  }
124
+ const size = this.maxBytes > 0 ? this.sizeOf(value) : 0
125
+ this._store.set(key, { value, size, expiresAt: this.ttl > 0 ? Date.now() + this.ttl : 0 })
126
+ this._bytes += size
127
+ this._evict()
58
128
  return true
59
129
  }
60
130
 
@@ -62,8 +132,7 @@ export class Cache {
62
132
  const entry = this._store.get(key)
63
133
  if (!entry) return false
64
134
  if (this._isExpired(entry)) {
65
- this._store.delete(key)
66
- this.dispose(entry.value, key)
135
+ this._remove(key, entry)
67
136
  return false
68
137
  }
69
138
  return true
@@ -72,14 +141,15 @@ export class Cache {
72
141
  delete(key) {
73
142
  const entry = this._store.get(key)
74
143
  if (!entry) return false
75
- this._store.delete(key)
76
- this.dispose(entry.value, key)
144
+ this._remove(key, entry)
77
145
  return true
78
146
  }
79
147
 
80
148
  clear() {
81
- for (const [key, entry] of this._store) this.dispose(entry.value, key)
149
+ const entries = [...this._store]
82
150
  this._store.clear()
151
+ this._bytes = 0
152
+ for (const [key, entry] of entries) this.dispose(entry.value, key)
83
153
  }
84
154
 
85
155
  flushAll() {
@@ -95,6 +165,7 @@ export class Cache {
95
165
  clearInterval(this._sweeper)
96
166
  this._sweeper = undefined
97
167
  }
168
+ this.clear()
98
169
  }
99
170
 
100
171
  mget(keys) {
@@ -114,6 +185,10 @@ export class Cache {
114
185
  get size() {
115
186
  return this._store.size
116
187
  }
188
+
189
+ get bytes() {
190
+ return this._bytes
191
+ }
117
192
  }
118
193
 
119
194
  export const LRUCache = Cache
@@ -0,0 +1,103 @@
1
+ import v8 from 'node:v8'
2
+ import vm from 'node:vm'
3
+
4
+ const MB = 1024 * 1024
5
+
6
+ export const DEFAULT_MEMORY_TRIM = {
7
+ enabled: true,
8
+ checkIntervalMs: 15_000,
9
+ minIntervalMs: 30_000,
10
+ growthBytes: 16 * MB,
11
+ unusedHeapBytes: 16 * MB
12
+ }
13
+
14
+ let collector
15
+ let lastTrimAt = 0
16
+ let lastTrimRss = 0
17
+ let trimming = false
18
+ let guardTimer
19
+ let guardRefs = 0
20
+ let guardOptions = DEFAULT_MEMORY_TRIM
21
+ let pendingTrim
22
+
23
+ const resolveCollector = () => {
24
+ if (collector !== undefined) return collector
25
+ if (typeof globalThis.gc === 'function') {
26
+ collector = globalThis.gc
27
+ return collector
28
+ }
29
+ try {
30
+ v8.setFlagsFromString('--expose-gc')
31
+ collector = vm.runInNewContext('gc')
32
+ v8.setFlagsFromString('--no-expose-gc')
33
+ } catch {
34
+ collector = null
35
+ }
36
+ return collector
37
+ }
38
+
39
+ export const trimMemory = () => {
40
+ if (trimming) return false
41
+ const collect = resolveCollector()
42
+ if (!collect) return false
43
+ trimming = true
44
+ try {
45
+ try {
46
+ collect({ type: 'major', execution: 'sync', flavor: 'last-resort' })
47
+ } catch {
48
+ collect()
49
+ }
50
+ lastTrimAt = Date.now()
51
+ lastTrimRss = process.memoryUsage.rss()
52
+ return true
53
+ } finally {
54
+ trimming = false
55
+ }
56
+ }
57
+
58
+ export const requestTrim = (delayMs = 2000) => {
59
+ if (!guardOptions.enabled) return
60
+ if (pendingTrim) clearTimeout(pendingTrim)
61
+ pendingTrim = setTimeout(() => {
62
+ pendingTrim = undefined
63
+ if (Date.now() - lastTrimAt >= 5000) trimMemory()
64
+ }, delayMs)
65
+ pendingTrim.unref?.()
66
+ }
67
+
68
+ const guardTick = () => {
69
+ const now = Date.now()
70
+ if (now - lastTrimAt < guardOptions.minIntervalMs) return
71
+ const usage = process.memoryUsage()
72
+ const grew = usage.rss - lastTrimRss >= guardOptions.growthBytes
73
+ const unused = usage.heapTotal - usage.heapUsed >= guardOptions.unusedHeapBytes
74
+ if (grew || unused) trimMemory()
75
+ }
76
+
77
+ export const retainMemoryGuard = options => {
78
+ const resolved = { ...DEFAULT_MEMORY_TRIM, ...(options === false ? { enabled: false } : options || {}) }
79
+ guardOptions = resolved
80
+ if (!resolved.enabled) return () => {}
81
+ guardRefs++
82
+ if (!guardTimer) {
83
+ lastTrimRss = process.memoryUsage.rss()
84
+ guardTimer = setInterval(guardTick, resolved.checkIntervalMs)
85
+ guardTimer.unref?.()
86
+ }
87
+ let released = false
88
+ return () => {
89
+ if (released) return
90
+ released = true
91
+ guardRefs--
92
+ if (guardRefs <= 0) {
93
+ guardRefs = 0
94
+ clearInterval(guardTimer)
95
+ guardTimer = undefined
96
+ if (pendingTrim) {
97
+ clearTimeout(pendingTrim)
98
+ pendingTrim = undefined
99
+ }
100
+ requestTrim(1500)
101
+ }
102
+ }
103
+ }
@@ -580,16 +580,10 @@ export class SessionRecord {
580
580
  })
581
581
  }
582
582
  closeSession(session) {
583
- if (this.isClosed(session)) {
584
- console.warn('Session already closed', session)
585
- return
586
- }
587
- console.info('Closing session:', session)
583
+ if (this.isClosed(session)) return
588
584
  session.indexInfo.closed = Date.now()
589
585
  }
590
586
  openSession(session) {
591
- if (!this.isClosed(session)) console.warn('Session already open')
592
- console.info('Opening session:', session)
593
587
  session.indexInfo.closed = -1
594
588
  }
595
589
  isClosed(session) {
@@ -606,7 +600,6 @@ export class SessionRecord {
606
600
  }
607
601
  }
608
602
  if (oldestKey) {
609
- console.info('Removing old closed session:', oldestSession)
610
603
  delete this.sessions[oldestKey]
611
604
  } else {
612
605
  throw new Error('Corrupt sessions object')
@@ -7,7 +7,7 @@ import { SenderKeyName, SenderKeyRecord, GroupCipher, GroupSessionBuilder, Sende
7
7
 
8
8
  export class LIDMappingStore {
9
9
  constructor(keys, logger, pnToLIDFunc) {
10
- this.mappingCache = new Cache({ ttl: 3 * 24 * 60 * 60 * 1000, max: 10000, updateAgeOnGet: true })
10
+ this.mappingCache = new Cache({ ttl: 3 * 24 * 60 * 60 * 1000, max: 4000, updateAgeOnGet: true })
11
11
  this.inflightLIDLookups = new Map()
12
12
  this.inflightPNLookups = new Map()
13
13
  this.keys = keys
@@ -260,7 +260,9 @@ export class LIDMappingStore {
260
260
  }
261
261
 
262
262
  close() {
263
- this.mappingCache.clear()
263
+ this.mappingCache.close()
264
+ this.inflightLIDLookups.clear()
265
+ this.inflightPNLookups.clear()
264
266
  }
265
267
  }
266
268
 
@@ -281,7 +283,7 @@ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
281
283
  const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc)
282
284
  const storage = signalStorage(auth, lidMapping)
283
285
  const parsedKeys = auth.keys
284
- const migratedSessionCache = new Cache({ ttl: 3 * 24 * 60 * 60 * 1000, updateAgeOnGet: true })
286
+ const migratedSessionCache = new Cache({ ttl: 3 * 24 * 60 * 60 * 1000, max: 4000, updateAgeOnGet: true })
285
287
 
286
288
  const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
287
289
  const senderName = jidToSignalSenderKeyName(group, meId)
@@ -423,7 +425,7 @@ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
423
425
  },
424
426
 
425
427
  close() {
426
- migratedSessionCache.clear()
428
+ migratedSessionCache.close()
427
429
  lidMapping.close()
428
430
  },
429
431
 
@@ -1,6 +1,7 @@
1
1
  import { proto } from '../../WAProto/index.js'
2
2
  import { Boom } from '../foundation/boom.js'
3
3
  import { Cache } from '../foundation/cache.js'
4
+ import { requestTrim } from '../foundation/memory.js'
4
5
  import { makeMutex } from '../foundation/concurrency.js'
5
6
  import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../defaults.js'
6
7
  import { ALL_WA_PATCH_NAMES, SyncState } from '../constants.js'
@@ -501,6 +502,7 @@ export const makeChatsSocket = config => {
501
502
  syncState = SyncState.Online
502
503
  logger.info('App state sync complete, transitioning to Online state and flushing buffer')
503
504
  ev.flush()
505
+ requestTrim(5000)
504
506
  const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
505
507
  ev.emit('creds.update', { accountSyncCounter })
506
508
  }
@@ -79,13 +79,13 @@ export const makeMessagesRecvSocket = (config) => {
79
79
 
80
80
  const msgRetryCache = config.msgRetryCounterCache ||
81
81
  new Cache({
82
- max: 8192,
82
+ max: 2048,
83
83
  stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
84
84
  useClones: false
85
85
  });
86
86
  const callOfferCache = config.callOfferCache ||
87
87
  new Cache({
88
- max: 2048,
88
+ max: 256,
89
89
  stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
90
90
  useClones: false
91
91
  });
@@ -1336,7 +1336,7 @@ export const makeMessagesRecvSocket = (config) => {
1336
1336
  }
1337
1337
  await messageMutex.mutex(async () => {
1338
1338
  await decrypt();
1339
- if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1339
+ if (msg.key?.fromMe && msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1340
1340
  messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1341
1341
  }
1342
1342
 
@@ -1715,6 +1715,8 @@ export const makeMessagesRecvSocket = (config) => {
1715
1715
  callOfferCache.close();
1716
1716
  }
1717
1717
  identityAssertDebounce.close();
1718
+ inFlightPreKeyLow.clear();
1719
+ inFlight463Recoveries.clear();
1718
1720
  sendActiveReceipts = false;
1719
1721
  });
1720
1722
  async function pruneExpiredTcTokens() {
@@ -66,7 +66,7 @@ export const makeMessagesSocket = (config) => {
66
66
  const userDevicesCache = config.userDevicesCache ||
67
67
  new Cache({
68
68
  ttl: DEFAULT_CACHE_TTLS.USER_DEVICES * 1000,
69
- max: 1000
69
+ max: 500
70
70
  });
71
71
 
72
72
  const devicesMutex = makeMutex();
@@ -1105,7 +1105,7 @@ export const makeMessagesSocket = (config) => {
1105
1105
  }
1106
1106
  mediaConn = undefined;
1107
1107
  if (messageRetryManager) {
1108
- messageRetryManager.clear();
1108
+ messageRetryManager.close();
1109
1109
  }
1110
1110
  });
1111
1111
  const fullSock = {
@@ -33,6 +33,7 @@ import { USyncQuery, USyncUser } from './usync.js'
33
33
  import { normalizeUsername, isValidUsername, isValidUsernameKey } from '../utils/username.js'
34
34
  import { WebSocketClient } from '../socket-client/websocket-client.js'
35
35
  import { generateQR } from '../foundation/qrcode-terminal.js'
36
+ import { retainMemoryGuard } from '../foundation/memory.js'
36
37
 
37
38
  const wMexQuery = (variables, queryId, query, generateMessageTag) =>
38
39
  query({
@@ -93,6 +94,7 @@ export const makeSocket = config => {
93
94
  wsConfig = { ...config, options: { ...(config.options || {}), headers } }
94
95
  }
95
96
 
97
+ const releaseMemoryGuard = retainMemoryGuard(config.memoryTrim)
96
98
  const ephemeralKeyPair = Curve.generateKeyPair()
97
99
 
98
100
  const noise = makeNoiseHandler({ keyPair: ephemeralKeyPair, NOISE_HEADER: NOISE_WA_HEADER, logger, routingInfo: authState?.creds?.routingInfo })
@@ -481,6 +483,7 @@ export const makeSocket = config => {
481
483
 
482
484
  noise.destroy?.()
483
485
  signalRepository.close?.()
486
+ releaseMemoryGuard()
484
487
  if (!ws.isClosed && !ws.isClosing) {
485
488
  try {
486
489
 
@@ -100,10 +100,11 @@ export class PreKeyManager {
100
100
  }
101
101
 
102
102
  const txStorage = new AsyncLocalStorage()
103
+ const SIGNAL_CACHE_BYTES = 6 * 1024 * 1024
103
104
 
104
105
  export function makeCacheableSignalKeyStore(store, logger, _cache) {
105
106
 
106
- const cache = _cache || new Cache({ max: 8192, ttl: DEFAULT_CACHE_TTLS.SIGNAL_STORE * 1000 })
107
+ const cache = _cache || new Cache({ max: 2048, maxBytes: SIGNAL_CACHE_BYTES, ttl: DEFAULT_CACHE_TTLS.SIGNAL_STORE * 1000 })
107
108
  const cacheMutex = makeMutex()
108
109
 
109
110
  function getUniqueId(type, id) {
@@ -8,6 +8,7 @@ import { aesDecrypt, aesEncrypt, hmacSign, toNumber, trimUndefined, LT_HASH_ANTI
8
8
  import { downloadContentFromMessage } from './media.js'
9
9
  import { updateMessageWithReaction, updateMessageWithReceipt } from './message-compose.js'
10
10
  import { isRealMessage, shouldIncrementChatUnread } from './message-processing.js'
11
+ import { requestTrim } from '../foundation/memory.js'
11
12
 
12
13
  const mutationKeys = keydata => {
13
14
  const keys = expandAppStateKeys(keydata)
@@ -897,6 +898,7 @@ export const makeEventBuffer = logger => {
897
898
  let flushPendingTimeout = null
898
899
  let bufferCount = 0
899
900
  const MAX_HISTORY_CACHE_SIZE = 10000
901
+ const HEAVY_FLUSH_MESSAGES = 200
900
902
  const BUFFER_TIMEOUT_MS = 30000
901
903
 
902
904
  ev.on('event', map => {
@@ -947,7 +949,9 @@ export const makeEventBuffer = logger => {
947
949
  }
948
950
  }
949
951
  const consolidatedData = consolidateEvents(data)
952
+ const heavy = !!consolidatedData['messaging-history.set'] || (consolidatedData['messages.upsert']?.messages.length ?? 0) > HEAVY_FLUSH_MESSAGES
950
953
  if (Object.keys(consolidatedData).length) ev.emit('event', consolidatedData)
954
+ if (heavy) requestTrim(3000)
951
955
  data = newData
952
956
  logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events')
953
957
  return true
@@ -85,7 +85,13 @@ export const getImageProcessingLibrary = async () => {
85
85
  import('@napi-rs/image').catch(() => {}),
86
86
  import('jimp').catch(() => {})
87
87
  ])
88
- if (sharp) imageProcessingLibrary = { sharp }
88
+ if (sharp) {
89
+ try {
90
+ sharp.default.cache(false)
91
+ sharp.default.concurrency(1)
92
+ } catch {}
93
+ imageProcessingLibrary = { sharp }
94
+ }
89
95
  else if (image) imageProcessingLibrary = { image }
90
96
  else if (jimp) imageProcessingLibrary = { jimp }
91
97
  else {
@@ -167,15 +173,13 @@ export const extractVideoThumb = async (path, time, size) => {
167
173
  ],
168
174
  { stdio: ['ignore', 'pipe', 'pipe'] }
169
175
  )
170
- let buffer = Buffer.alloc(0)
176
+ const stdoutChunks = []
171
177
  const stderrChunks = []
172
- ffmpeg.stdout.on('data', chunk => {
173
- buffer = Buffer.concat([buffer, chunk])
174
- })
178
+ ffmpeg.stdout.on('data', chunk => stdoutChunks.push(chunk))
175
179
  ffmpeg.stderr.on('data', chunk => stderrChunks.push(chunk))
176
180
  const [code] = await once(ffmpeg, 'close')
177
181
  if (code !== 0) throw new Boom(`FFmpeg failed (code ${code}):\n` + Buffer.concat(stderrChunks).toString('utf8'))
178
- return buffer
182
+ return Buffer.concat(stdoutChunks)
179
183
  }
180
184
 
181
185
  const thumbWithLibrary = async (lib, bufferOrFilePath, width) => {
@@ -574,9 +578,10 @@ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, ag
574
578
  resolve(uploadWithNodeHttp({ url: newUrl, filePath, headers, timeoutMs, agent }, redirectCount + 1))
575
579
  return
576
580
  }
577
- let body = ''
578
- res.on('data', chunk => (body += chunk))
581
+ const bodyChunks = []
582
+ res.on('data', chunk => bodyChunks.push(chunk))
579
583
  res.on('end', () => {
584
+ const body = Buffer.concat(bodyChunks).toString('utf8')
580
585
  try {
581
586
  resolve(JSON.parse(body))
582
587
  } catch {
@@ -28,8 +28,10 @@ import { aesDecryptGCM, hmacSign, getKeyAuthor, toNumber, generateMessageIDV2 }
28
28
  import { getContentType, normalizeMessageContent } from './message-compose.js'
29
29
  import { downloadContentFromMessage, getStream, getUrlFromDirectPath } from './media.js'
30
30
  import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './auth-state-core.js'
31
+ import { requestTrim } from '../foundation/memory.js'
31
32
 
32
33
  const inflatePromise = promisify(inflate)
34
+ const MAX_PROCESSED_HISTORY_MESSAGES = 64
33
35
 
34
36
  const REAL_MSG_STUB_TYPES = new Set([
35
37
  WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
@@ -207,7 +209,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
207
209
  if (process) {
208
210
  if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
209
211
  ev.emit('creds.update', {
210
- processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }]
212
+ processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }].slice(-MAX_PROCESSED_HISTORY_MESSAGES)
211
213
  })
212
214
  }
213
215
  const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger)
@@ -222,6 +224,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
222
224
  chunkOrder: histNotification.chunkOrder,
223
225
  peerDataRequestSessionId: histNotification.peerDataRequestSessionId
224
226
  })
227
+ requestTrim(4000)
225
228
  }
226
229
  break
227
230
  }
@@ -480,7 +483,8 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
480
483
 
481
484
  export default processMessage
482
485
 
483
- const RECENT_MESSAGES_SIZE = 1024
486
+ const RECENT_MESSAGES_SIZE = 512
487
+ const RECENT_MESSAGES_BYTES = 4 * 1024 * 1024
484
488
  const MESSAGE_KEY_SEPARATOR = '\u0000'
485
489
  const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
486
490
  const PHONE_REQUEST_DELAY = 3000
@@ -511,6 +515,7 @@ export class MessageRetryManager {
511
515
  this.logger = logger
512
516
  this.recentMessagesMap = new Cache({
513
517
  max: RECENT_MESSAGES_SIZE,
518
+ maxBytes: RECENT_MESSAGES_BYTES,
514
519
  ttl: 5 * 60 * 1000,
515
520
  dispose: (_value, key) => {
516
521
  const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
@@ -519,9 +524,9 @@ export class MessageRetryManager {
519
524
  })
520
525
  this.messageKeyIndex = new Map()
521
526
 
522
- this.sessionRecreateHistory = new Cache({ max: 4096, ttl: RECREATE_SESSION_TIMEOUT * 2 })
523
- this.retryCounters = new Cache({ max: 4096, ttl: 15 * 60 * 1000, updateAgeOnGet: true })
524
- this.baseKeys = new Cache({ max: 1024, ttl: 15 * 60 * 1000 })
527
+ this.sessionRecreateHistory = new Cache({ max: 2048, ttl: RECREATE_SESSION_TIMEOUT * 2 })
528
+ this.retryCounters = new Cache({ max: 2048, ttl: 15 * 60 * 1000, updateAgeOnGet: true })
529
+ this.baseKeys = new Cache({ max: 512, ttl: 15 * 60 * 1000 })
525
530
  this.pendingPhoneRequests = {}
526
531
  this.maxMsgRetryCount = maxMsgRetryCount
527
532
  this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
@@ -646,6 +651,15 @@ export class MessageRetryManager {
646
651
  this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
647
652
  }
648
653
 
654
+ close() {
655
+ this.clear()
656
+ this.recentMessagesMap.close()
657
+ this.sessionRecreateHistory.close()
658
+ this.retryCounters.close()
659
+ this.baseKeys.close()
660
+ this.invalidatedMessages.close()
661
+ }
662
+
649
663
  saveBaseKey(addr, msgId, baseKey) {
650
664
  this.baseKeys.set(`${addr}:${msgId}`, baseKey)
651
665
  }
@@ -719,7 +733,9 @@ export const downloadHistory = async (msg, options) => {
719
733
  const chunks = []
720
734
  inflater.on('data', chunk => chunks.push(chunk))
721
735
  await pipeline(stream, inflater)
722
- return proto.HistorySync.decode(Buffer.concat(chunks))
736
+ const inflated = Buffer.concat(chunks)
737
+ chunks.length = 0
738
+ return proto.HistorySync.decode(inflated)
723
739
  }
724
740
 
725
741
  export const processHistoryMessage = (item, logger) => {