@hiroosy/baileys-lite 0.3.2 → 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/README.md +1 -1
- package/WAProto/index.js +1530 -1514
- package/package.json +1 -1
- package/src/binary/wa-binary.js +4 -2
- package/src/defaults.js +2 -1
- package/src/foundation/ai-rich.js +1 -19
- package/src/foundation/cache.js +99 -24
- package/src/foundation/image-thumb.js +5 -106
- package/src/foundation/memory.js +103 -0
- package/src/signal/libsignal.js +1 -8
- package/src/signal/signal-repository.js +6 -4
- package/src/socket/chats.js +2 -0
- package/src/socket/messages-recv.js +5 -3
- package/src/socket/messages-send.js +19 -2
- package/src/socket/socket-core.js +3 -0
- package/src/utils/auth-state-core.js +2 -1
- package/src/utils/chat-sync.js +4 -0
- package/src/utils/media.js +16 -11
- package/src/utils/message-processing.js +22 -6
- package/src/utils/wa-protocol-core.js +6 -5
- package/src/wam/wam-constants.js +22 -22851
- package/src/wam/wam-data.json +1 -0
- package/src/vendor/jpeg-js/decoder.js +0 -1091
- package/src/vendor/jpeg-js/encoder.js +0 -739
- package/src/vendor/pngjs/LICENSE +0 -20
- package/src/vendor/pngjs/bitmapper.js +0 -251
- package/src/vendor/pngjs/bitpacker.js +0 -159
- package/src/vendor/pngjs/constants.js +0 -30
- package/src/vendor/pngjs/crc.js +0 -41
- package/src/vendor/pngjs/filter-pack.js +0 -173
- package/src/vendor/pngjs/filter-parse-sync.js +0 -21
- package/src/vendor/pngjs/filter-parse.js +0 -175
- package/src/vendor/pngjs/format-normaliser.js +0 -95
- package/src/vendor/pngjs/interlace.js +0 -84
- package/src/vendor/pngjs/packer-sync.js +0 -54
- package/src/vendor/pngjs/packer.js +0 -130
- package/src/vendor/pngjs/paeth-predictor.js +0 -16
- package/src/vendor/pngjs/parser-sync.js +0 -113
- package/src/vendor/pngjs/parser.js +0 -275
- package/src/vendor/pngjs/png-sync.js +0 -12
- package/src/vendor/pngjs/sync-inflate.js +0 -165
- package/src/vendor/pngjs/sync-reader.js +0 -47
package/package.json
CHANGED
package/src/binary/wa-binary.js
CHANGED
|
@@ -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
|
-
|
|
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:
|
|
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,5 +1,4 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
|
-
import { generateMessageIDV2 } from '../utils/wa-protocol-core.js'
|
|
3
2
|
|
|
4
3
|
const MESSAGE_EDIT_TYPE = 14
|
|
5
4
|
|
|
@@ -487,24 +486,7 @@ export class AIRichBuilder {
|
|
|
487
486
|
|
|
488
487
|
async send(jid, { forwarded, quoted, quotedParticipant, botJid, bypassDownload = true, ...sendOptions } = {}) {
|
|
489
488
|
if (!this._client) throw new Error('AIRichBuilder.send() needs a client — use sock.aiRich() or new AIRichBuilder(sock)')
|
|
490
|
-
|
|
491
|
-
const richResponse = sent?.message?.botForwardedMessage?.message?.richResponseMessage
|
|
492
|
-
if (!bypassDownload || !sent?.key?.id || !richResponse?.unifiedResponse) return sent
|
|
493
|
-
try {
|
|
494
|
-
const userId = this._client.user?.id ?? this._client.authState?.creds?.me?.id
|
|
495
|
-
const edit = this.buildEdit(jid, sent.key, sent.message)
|
|
496
|
-
await this._client.relayMessage(jid, edit, {
|
|
497
|
-
messageId: generateMessageIDV2(userId),
|
|
498
|
-
additionalAttributes: { edit: '1' },
|
|
499
|
-
additionalNodes: sendOptions.additionalNodes,
|
|
500
|
-
useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
|
|
501
|
-
statusJidList: sendOptions.statusJidList
|
|
502
|
-
})
|
|
503
|
-
} catch (error) {
|
|
504
|
-
error.relayedKey = sent.key
|
|
505
|
-
throw error
|
|
506
|
-
}
|
|
507
|
-
return sent
|
|
489
|
+
return this._client.sendMessage(jid, { aiRich: this, forwarded, quoted, quotedParticipant, botJid }, { ...sendOptions, bypassDownload })
|
|
508
490
|
}
|
|
509
491
|
}
|
|
510
492
|
|
package/src/foundation/cache.js
CHANGED
|
@@ -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
|
-
|
|
11
|
-
|
|
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
|
-
|
|
24
|
-
|
|
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.
|
|
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
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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.
|
|
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.
|
|
76
|
-
this.dispose(entry.value, key)
|
|
144
|
+
this._remove(key, entry)
|
|
77
145
|
return true
|
|
78
146
|
}
|
|
79
147
|
|
|
80
148
|
clear() {
|
|
81
|
-
|
|
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
|
|
@@ -1,90 +1,13 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
2
|
import { once } from 'node:events'
|
|
3
|
-
import { promises as fs } from 'node:fs'
|
|
4
3
|
import { Boom } from './boom.js'
|
|
5
4
|
|
|
6
5
|
// Dependency-free image thumbnails. Used when none of sharp / @napi-rs/image / jimp is installed,
|
|
7
6
|
// so a missing optional library never results in a media message without jpegThumbnail
|
|
8
|
-
// (the recipient sees that as a grey box).
|
|
9
|
-
// 1. built-in decoder (vendored jpeg-js + pngjs) for JPEG / PNG
|
|
10
|
-
// 2. ffmpeg for everything else (webp, gif, bmp, ...) and for big files, so the event loop is not
|
|
11
|
-
// blocked by a pure-JS decode of a multi-megapixel photo
|
|
7
|
+
// (the recipient sees that as a grey box). Uses ffmpeg.
|
|
12
8
|
|
|
13
|
-
const JPEG_QUALITY = 50
|
|
14
|
-
const BUILTIN_PREFERRED_MAX_BYTES = 2 * 1024 * 1024
|
|
15
9
|
const FFMPEG_TIMEOUT_MS = 15_000
|
|
16
10
|
|
|
17
|
-
const isJpeg = b => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff
|
|
18
|
-
const isPng = b => b.length > 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47
|
|
19
|
-
|
|
20
|
-
async function readHeader(path) {
|
|
21
|
-
const handle = await fs.open(path, 'r')
|
|
22
|
-
try {
|
|
23
|
-
const header = Buffer.alloc(16)
|
|
24
|
-
const { bytesRead } = await handle.read(header, 0, 16, 0)
|
|
25
|
-
return header.subarray(0, bytesRead)
|
|
26
|
-
} finally {
|
|
27
|
-
await handle.close()
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
async function decodeRaster(buffer) {
|
|
32
|
-
if (isJpeg(buffer)) {
|
|
33
|
-
const { default: decode } = await import('../vendor/jpeg-js/decoder.js')
|
|
34
|
-
return decode(buffer, { useTArray: true, formatAsRGBA: true, tolerantDecoding: true })
|
|
35
|
-
}
|
|
36
|
-
if (isPng(buffer)) {
|
|
37
|
-
const { read } = await import('../vendor/pngjs/png-sync.js')
|
|
38
|
-
return read(buffer)
|
|
39
|
-
}
|
|
40
|
-
throw new Boom('unsupported image format for built-in decoder')
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// area-average downscale; transparent pixels are composited over white (JPEG has no alpha)
|
|
44
|
-
function resizeToRgba({ data, width: sw, height: sh }, dw, dh) {
|
|
45
|
-
const out = Buffer.allocUnsafe(dw * dh * 4)
|
|
46
|
-
const xr = sw / dw
|
|
47
|
-
const yr = sh / dh
|
|
48
|
-
for (let dy = 0; dy < dh; dy++) {
|
|
49
|
-
const y0 = Math.floor(dy * yr)
|
|
50
|
-
const y1 = Math.min(sh, Math.max(y0 + 1, Math.ceil((dy + 1) * yr)))
|
|
51
|
-
for (let dx = 0; dx < dw; dx++) {
|
|
52
|
-
const x0 = Math.floor(dx * xr)
|
|
53
|
-
const x1 = Math.min(sw, Math.max(x0 + 1, Math.ceil((dx + 1) * xr)))
|
|
54
|
-
let r = 0
|
|
55
|
-
let g = 0
|
|
56
|
-
let b = 0
|
|
57
|
-
for (let y = y0; y < y1; y++) {
|
|
58
|
-
let i = (y * sw + x0) * 4
|
|
59
|
-
for (let x = x0; x < x1; x++, i += 4) {
|
|
60
|
-
const a = data[i + 3] / 255
|
|
61
|
-
r += data[i] * a + 255 * (1 - a)
|
|
62
|
-
g += data[i + 1] * a + 255 * (1 - a)
|
|
63
|
-
b += data[i + 2] * a + 255 * (1 - a)
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
const n = (y1 - y0) * (x1 - x0)
|
|
67
|
-
const o = (dy * dw + dx) * 4
|
|
68
|
-
out[o] = Math.round(r / n)
|
|
69
|
-
out[o + 1] = Math.round(g / n)
|
|
70
|
-
out[o + 2] = Math.round(b / n)
|
|
71
|
-
out[o + 3] = 255
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return out
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
async function builtinThumb(buffer, width) {
|
|
78
|
-
const image = await decodeRaster(buffer)
|
|
79
|
-
if (!image?.width || !image?.height || !image.data?.length) throw new Boom('could not decode image')
|
|
80
|
-
const dw = Math.max(1, Math.min(width, image.width)) // never upscale
|
|
81
|
-
const dh = Math.max(1, Math.round((image.height * dw) / image.width))
|
|
82
|
-
const { default: encode } = await import('../vendor/jpeg-js/encoder.js')
|
|
83
|
-
const rgba = resizeToRgba(image, dw, dh)
|
|
84
|
-
const { data } = encode({ data: rgba, width: dw, height: dh }, JPEG_QUALITY)
|
|
85
|
-
return { buffer: Buffer.from(data), original: { width: image.width, height: image.height } }
|
|
86
|
-
}
|
|
87
|
-
|
|
88
11
|
async function runFfmpeg(command, args, input) {
|
|
89
12
|
const child = spawn(command, args, { stdio: [Buffer.isBuffer(input) ? 'pipe' : 'ignore', 'pipe', 'pipe'] })
|
|
90
13
|
const out = []
|
|
@@ -134,33 +57,9 @@ async function ffmpegThumb(input, width) {
|
|
|
134
57
|
* @returns {Promise<{ buffer: Buffer, original: { width?: number, height?: number } }>}
|
|
135
58
|
*/
|
|
136
59
|
export async function extractImageThumbFallback(input, width = 32) {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
size = input.length
|
|
142
|
-
} else {
|
|
143
|
-
header = await readHeader(input)
|
|
144
|
-
size = (await fs.stat(input)).size
|
|
145
|
-
}
|
|
146
|
-
const decodable = isJpeg(header) || isPng(header)
|
|
147
|
-
const big = size > BUILTIN_PREFERRED_MAX_BYTES
|
|
148
|
-
const attempts = []
|
|
149
|
-
if (decodable) {
|
|
150
|
-
const builtin = async () => builtinThumb(Buffer.isBuffer(input) ? input : await fs.readFile(input), width)
|
|
151
|
-
attempts.push(builtin)
|
|
152
|
-
if (big) attempts.unshift(() => ffmpegThumb(input, width))
|
|
153
|
-
else attempts.push(() => ffmpegThumb(input, width))
|
|
154
|
-
} else {
|
|
155
|
-
attempts.push(() => ffmpegThumb(input, width))
|
|
156
|
-
}
|
|
157
|
-
const errors = []
|
|
158
|
-
for (const attempt of attempts) {
|
|
159
|
-
try {
|
|
160
|
-
return await attempt()
|
|
161
|
-
} catch (err) {
|
|
162
|
-
errors.push(err?.message ?? String(err))
|
|
163
|
-
}
|
|
60
|
+
try {
|
|
61
|
+
return await ffmpegThumb(input, width)
|
|
62
|
+
} catch (err) {
|
|
63
|
+
throw new Boom(`could not generate image thumbnail (install sharp, @napi-rs/image or jimp, or ffmpeg): ${err?.message ?? String(err)}`)
|
|
164
64
|
}
|
|
165
|
-
throw new Boom(`could not generate image thumbnail (install sharp, @napi-rs/image or jimp, or ffmpeg): ${errors.join(' | ')}`)
|
|
166
65
|
}
|
|
@@ -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
|
+
}
|
package/src/signal/libsignal.js
CHANGED
|
@@ -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:
|
|
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.
|
|
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.
|
|
428
|
+
migratedSessionCache.close()
|
|
427
429
|
lidMapping.close()
|
|
428
430
|
},
|
|
429
431
|
|
package/src/socket/chats.js
CHANGED
|
@@ -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:
|
|
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:
|
|
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:
|
|
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.
|
|
1108
|
+
messageRetryManager.close();
|
|
1109
1109
|
}
|
|
1110
1110
|
});
|
|
1111
1111
|
const fullSock = {
|
|
@@ -1390,6 +1390,23 @@ export const makeMessagesSocket = (config) => {
|
|
|
1390
1390
|
});
|
|
1391
1391
|
}
|
|
1392
1392
|
|
|
1393
|
+
if ('aiRich' in content && content.aiRich && options.bypassDownload !== false && fullMsg.key?.id && fullMsg.message?.botForwardedMessage?.message?.richResponseMessage?.unifiedResponse) {
|
|
1394
|
+
try {
|
|
1395
|
+
const edit = new AIRichBuilder().buildEdit(jid, fullMsg.key, fullMsg.message);
|
|
1396
|
+
await relayMessage(jid, edit, {
|
|
1397
|
+
messageId: generateMessageIDV2(userJid),
|
|
1398
|
+
additionalAttributes: { edit: '1' },
|
|
1399
|
+
additionalNodes: options.additionalNodes,
|
|
1400
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
1401
|
+
statusJidList: options.statusJidList
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
catch (error) {
|
|
1405
|
+
error.relayedKey = fullMsg.key;
|
|
1406
|
+
throw error;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1393
1410
|
if ('album' in content) {
|
|
1394
1411
|
const { delayMs = 1500 } = options;
|
|
1395
1412
|
for (const albumMedia of content.album) {
|
|
@@ -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
|
|