@hiroosy/baileys-lite 0.0.3 → 0.3.0

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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,47 +1,23 @@
1
- /**
2
- * Native audio duration reader (seconds) — replaces `music-metadata` for the one thing lite used it for:
3
- * `metadata.format.duration`.
4
- *
5
- * Supported containers (formulas mirror music-metadata 11.x):
6
- * Ogg Opus (granule(last page) - preSkip) / 48000
7
- * Ogg Vorbis granule(last page) / sampleRate
8
- * WAV (fact.dwSampleLength | dataSize/blockAlign) / sampleRate (data chunk clamped to file size)
9
- * FLAC STREAMINFO.totalSamples / sampleRate
10
- * MP4/M4A first audio track mdhd.duration / mdhd.timeScale (+ fragmented mp4, mvhd not used)
11
- * MP3 / ADTS Xing/Info frame count, CBR from file size, or full frame scan
12
- * AIFF / AIFF-C COMM.numSampleFrames / sampleRate (80-bit float)
13
- * Matroska / WebM Segment > Info > Duration x TimecodeScale
14
- * AMR-NB / AMR-WB frame count x 20 ms
15
- *
16
- * Returns `undefined` when the duration cannot be determined with confidence (unknown container, truncated
17
- * header, ...) — callers may then fall back to something else. It never guesses.
18
- */
19
1
  import { createReadStream } from 'node:fs'
20
2
  import { open, stat } from 'node:fs/promises'
21
3
 
22
- /* ------------------------------ helpers ------------------------------ */
23
-
24
4
  const u32be = (b, o) => b.readUInt32BE(o)
25
5
  const u64be = (b, o) => Number(b.readBigUInt64BE(o))
26
6
  const ascii = (b, o, n) => b.toString('latin1', o, o + n)
27
7
 
28
- /* ------------------------------ Ogg ------------------------------ */
29
-
30
8
  const oggDuration = buf => {
31
- // Mirrors music-metadata's OggParser: pages are read in order; a stream's `lastPageHeader` is recorded when
32
- // its page header is parsed (BEFORE the page body is read), so a file cut inside a page body still records
33
- // that page's granule. `endOfStream` is true only when reading threw EndOfStream (file cut mid-header/body).
9
+
34
10
  const streams = new Map()
35
11
  let pos = 0
36
12
  let endOfStream = false
37
13
  while (true) {
38
14
  if (pos + 27 > buf.length) {
39
- // PageHeader needs 27 bytes; if there is nothing left at all this is a clean end, otherwise a cut header
15
+
40
16
  if (pos < buf.length) endOfStream = true
41
- else endOfStream = true // readToken at EOF also throws EndOfStream in music-metadata
17
+ else endOfStream = true
42
18
  break
43
19
  }
44
- if (ascii(buf, pos, 4) !== 'OggS') break // OggContentError -> warning; not an end-of-stream
20
+ if (ascii(buf, pos, 4) !== 'OggS') break
45
21
  const headerType = buf[pos + 5]
46
22
  const granule = buf.readBigInt64LE(pos + 6)
47
23
  const serial = buf.readUInt32LE(pos + 14)
@@ -53,14 +29,14 @@ const oggDuration = buf => {
53
29
  }
54
30
  s.pageNumber = buf.readUInt32LE(pos + 18)
55
31
  if (pos + 27 + nseg > buf.length) {
56
- endOfStream = true // SegmentTable read hits EOF; lastPageHeader is NOT yet updated for this page
32
+ endOfStream = true
57
33
  break
58
34
  }
59
35
  let dataLen = 0
60
36
  for (let i = 0; i < nseg; i++) dataLen += buf[pos + 27 + i]
61
37
  const dataStart = pos + 27 + nseg
62
38
  if (dataStart + dataLen > buf.length) {
63
- endOfStream = true // page body cut short: music-metadata throws before parsePage of the consumer runs
39
+ endOfStream = true
64
40
  break
65
41
  }
66
42
  if (headerType & 0x02) {
@@ -77,21 +53,18 @@ const oggDuration = buf => {
77
53
  }
78
54
  }
79
55
  if (headerType & 0x04) s.closed = true
80
- else if (!(headerType & 0x02)) s.fullPages++ // a complete page that is neither first nor last
56
+ else if (!(headerType & 0x02)) s.fullPages++
81
57
  s.pageCount++
82
58
  s.last = { granule, lastPage: !!(headerType & 0x04) }
83
59
  pos = dataStart + dataLen
84
- // music-metadata stops early after page 12 unless a consumer wants the last page (Opus/Vorbis do) — so it keeps going
60
+
85
61
  if ([...streams.values()].every(x => x.closed)) break
86
62
  }
87
63
  for (const s of streams.values()) {
88
64
  if (!s.last || !s.sampleRate) continue
89
65
  if (!(endOfStream || s.last.lastPage)) continue
90
66
  if (s.last.granule < 0n) continue
91
- // music-metadata (Vorbis only): on a truncated file it calls flush() -> parseFullPage() on the pages queued so
92
- // far; with nothing queued (file ends after the identification page, before the comment page completes) that
93
- // reads an empty array and THROWS RangeError. A throw leaves the caller's `seconds` unset, so the faithful
94
- // equivalent is `undefined` — never a fabricated 0. (Measured: cut in bytes 58..3997 of a Vorbis file.)
67
+
95
68
  if (s.codec === 'vorbis' && endOfStream && !s.last.lastPage && s.fullPages === 0 && s.pageCount > 0) return undefined
96
69
  const g = Number(s.last.granule)
97
70
  if (s.codec === 'opus') return (g - s.preSkip) / 48000
@@ -100,8 +73,6 @@ const oggDuration = buf => {
100
73
  return undefined
101
74
  }
102
75
 
103
- /* ------------------------------ WAV ------------------------------ */
104
-
105
76
  const wavDuration = buf => {
106
77
  if (ascii(buf, 0, 4) !== 'RIFF' || ascii(buf, 8, 4) !== 'WAVE') return undefined
107
78
  let pos = 12
@@ -120,18 +91,16 @@ const wavDuration = buf => {
120
91
  } else if (id === 'data') {
121
92
  let chunkSize = size
122
93
  const remaining = buf.length - body
123
- if (remaining < chunkSize) chunkSize = remaining // "data chunk length exceeding file length"
94
+ if (remaining < chunkSize) chunkSize = remaining
124
95
  const samples = fact !== undefined ? fact : chunkSize === 0xffffffff ? undefined : chunkSize / blockAlign
125
96
  if (samples && sampleRate) return samples / sampleRate
126
97
  return undefined
127
98
  }
128
- pos = body + size + (size % 2) // chunks are word aligned
99
+ pos = body + size + (size % 2)
129
100
  }
130
101
  return undefined
131
102
  }
132
103
 
133
- /* ------------------------------ FLAC ------------------------------ */
134
-
135
104
  const flacDuration = buf => {
136
105
  if (ascii(buf, 0, 4) !== 'fLaC') return undefined
137
106
  let pos = 4
@@ -140,27 +109,25 @@ const flacDuration = buf => {
140
109
  const type = h & 0x7f
141
110
  const len = (buf[pos + 1] << 16) | (buf[pos + 2] << 8) | buf[pos + 3]
142
111
  if (type === 0) {
143
- // STREAMINFO (34 bytes): ... sampleRate(20) channels(3) bps(5) totalSamples(36)
112
+
144
113
  if (len !== 34) return undefined
145
- // music-metadata only reports once the whole 34-byte STREAMINFO block is present (a cut inside it is not trusted)
114
+
146
115
  if (pos + 4 + 34 > buf.length) return undefined
147
116
  const o = pos + 4
148
117
  const sampleRate = ((buf[o + 10] << 16) | (buf[o + 11] << 8) | buf[o + 12]) >> 4
149
118
  const totalSamples = (buf[o + 13] & 0x0f) * 2 ** 32 + buf.readUInt32BE(o + 14)
150
119
  return totalSamples > 0 && sampleRate ? totalSamples / sampleRate : undefined
151
120
  }
152
- if (h & 0x80) break // last metadata block, no STREAMINFO seen
121
+ if (h & 0x80) break
153
122
  pos += 4 + len
154
123
  }
155
124
  return undefined
156
125
  }
157
126
 
158
- /* ------------------------------ MP4 / M4A ------------------------------ */
159
-
160
127
  const CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'stbl', 'moof', 'traf', 'mvex'])
161
128
 
162
129
  const mp4Duration = buf => {
163
- const tracks = [] // { handler, timeScale, duration, fragSamples }
130
+ const tracks = []
164
131
  const walk = (start, end, cur) => {
165
132
  let pos = start
166
133
  while (pos + 8 <= end) {
@@ -171,10 +138,9 @@ const mp4Duration = buf => {
171
138
  size = u64be(buf, pos + 8)
172
139
  hdr = 16
173
140
  } else if (size === 0) size = end - pos
174
- // A box that claims more bytes than the file holds means the file is truncated. music-metadata reads
175
- // boxes through a tokenizer and throws EndOfStreamError there; the faithful equivalent is "no duration".
141
+
176
142
  if (size >= hdr && pos + size > end) {
177
- if (type === 'moov') truncated = true // header atom incomplete -> unreliable
143
+ if (type === 'moov') truncated = true
178
144
  size = end - pos
179
145
  } else if (size < hdr) size = Math.min(Math.max(size, hdr), end - pos)
180
146
  const body = pos + hdr
@@ -206,13 +172,11 @@ const mp4Duration = buf => {
206
172
  if (truncated) return undefined
207
173
  const audio = tracks.find(t => t.handler === 'soun' || t.handler === 'audi')
208
174
  if (audio && audio.timeScale > 0 && audio.duration > 0) return audio.duration / audio.timeScale
209
- return undefined // fragmented-only / timeScale 0 cases are not reproduced (caller falls back)
175
+ return undefined
210
176
  }
211
177
 
212
- /* ------------------------------ MP3 / ADTS ------------------------------ */
213
-
214
178
  const MPEG_BITRATES = {
215
- // [version][layer] kbps by index 1..14; version: 1 = MPEG1, 2 = MPEG2/2.5
179
+
216
180
  '1-1': [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448],
217
181
  '1-2': [32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384],
218
182
  '1-3': [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
@@ -220,18 +184,17 @@ const MPEG_BITRATES = {
220
184
  '2-2': [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
221
185
  '2-3': [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]
222
186
  }
223
- const MPEG_SAMPLE_RATES = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] } // keyed by version bits
187
+ const MPEG_SAMPLE_RATES = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] }
224
188
 
225
- /** Parses a 4-byte MPEG audio frame header at `o`. Returns null when it is not a valid frame header. */
226
189
  const mpegHeader = (buf, o) => {
227
190
  if (o + 4 > buf.length || buf[o] !== 0xff || (buf[o + 1] & 0xe0) !== 0xe0) return null
228
- const versionBits = (buf[o + 1] >> 3) & 3 // 3=MPEG1 2=MPEG2 0=MPEG2.5 1=reserved
229
- const layerBits = (buf[o + 1] >> 1) & 3 // 1=III 2=II 3=I 0=reserved (ADTS uses 0)
191
+ const versionBits = (buf[o + 1] >> 3) & 3
192
+ const layerBits = (buf[o + 1] >> 1) & 3
230
193
  const bitrateIdx = buf[o + 2] >> 4
231
194
  const srIdx = (buf[o + 2] >> 2) & 3
232
195
  const padding = (buf[o + 2] >> 1) & 1
233
196
  if (versionBits === 1 || layerBits === 0 || srIdx === 3) return null
234
- const layer = 4 - layerBits // 1,2,3
197
+ const layer = 4 - layerBits
235
198
  const verKey = versionBits === 3 ? 1 : 2
236
199
  if (bitrateIdx === 0 || bitrateIdx === 15) return null
237
200
  const bitrate = MPEG_BITRATES[`${verKey}-${layer}`][bitrateIdx - 1] * 1000
@@ -253,7 +216,7 @@ const id3v2Size = buf => {
253
216
 
254
217
  const mp3Duration = buf => {
255
218
  let pos = id3v2Size(buf)
256
- // find first valid frame header
219
+
257
220
  let first
258
221
  while (pos + 4 <= buf.length) {
259
222
  const h = mpegHeader(buf, pos)
@@ -266,7 +229,6 @@ const mp3Duration = buf => {
266
229
  if (!first) return undefined
267
230
  const hasId3v1 = buf.length >= 128 && ascii(buf, buf.length - 128, 3) === 'TAG'
268
231
 
269
- // Xing / Info tag lives after the side info of the first frame
270
232
  const sideInfo = first.versionBits === 3 ? (first.mono ? 17 : 32) : first.mono ? 9 : 17
271
233
  const tagOff = first.pos + 4 + (first.crc ? 2 : 0) + sideInfo
272
234
  const tag = tagOff + 4 <= buf.length ? ascii(buf, tagOff, 4) : ''
@@ -291,16 +253,15 @@ const mp3Duration = buf => {
291
253
  const m = ver.match(/\d+.\d+/g)
292
254
  if (m) {
293
255
  const [maj, min] = m[0].split('.').map(n => parseInt(n, 10))
294
- if (maj >= 3 && min >= 90) lameMusicLength = buf.readUInt32BE(o + 9 + 0x14) // ExtendedLameHeader.music_length
256
+ if (maj >= 3 && min >= 90) lameMusicLength = buf.readUInt32BE(o + 9 + 0x14)
295
257
  }
296
258
  }
297
- // music-metadata: LAME music_length/1000 first, then overwritten by the frame-count formula if streamSize present
259
+
298
260
  if (streamSize && numFrames !== null) return (numFrames * first.samplesPerFrame) / first.sampleRate
299
261
  if (lameMusicLength !== undefined && lameMusicLength > 0) return lameMusicLength / 1000
300
- // 'Info' tag = CBR marker, fall through to CBR-by-size below
262
+
301
263
  }
302
264
 
303
- // Scan up to 4 frames to detect CBR (all equal bitrates), like music-metadata
304
265
  const bitrates = []
305
266
  let p = first.pos
306
267
  let last
@@ -312,18 +273,17 @@ const mp3Duration = buf => {
312
273
  p += h.frameSize
313
274
  }
314
275
  if (bitrates.length === 4 && bitrates.every(b => b === bitrates[0])) {
315
- // CBR: numberOfSamples = round(mpegSize / frame_size) * samplesPerFrame
276
+
316
277
  const mpegSize = buf.length - first.pos - (hasId3v1 ? 128 : 0)
317
278
  return (Math.round(mpegSize / last.frameSize) * first.samplesPerFrame) / first.sampleRate
318
279
  }
319
280
 
320
- // VBR without Xing: full frame walk
321
281
  let frames = 0
322
282
  p = first.pos
323
283
  while (p + 4 <= buf.length) {
324
284
  const h = mpegHeader(buf, p)
325
285
  if (!h) {
326
- // resync: advance byte-wise to next plausible header
286
+
327
287
  p++
328
288
  continue
329
289
  }
@@ -333,27 +293,20 @@ const mp3Duration = buf => {
333
293
  return frames ? (frames * first.samplesPerFrame) / first.sampleRate : undefined
334
294
  }
335
295
 
336
- /* ------------------------------ ADTS (raw AAC) ------------------------------ */
337
-
338
296
  const ADTS_SAMPLE_RATES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]
339
297
 
340
- /**
341
- * Raw ADTS AAC (`.aac`): every frame carries 1024 samples; duration = frames * 1024 / sampleRate.
342
- * Walks frame by frame using the 13-bit frame length in each header. Like music-metadata the sample rate
343
- * comes from the first frame header.
344
- */
345
298
  const adtsDuration = buf => {
346
299
  let pos = id3v2Size(buf)
347
300
  let frames = 0
348
301
  let sampleRate
349
302
  while (pos + 7 <= buf.length) {
350
- // syncword 0xFFF, layer bits == 00 (this is what distinguishes ADTS from MPEG audio layers)
303
+
351
304
  if (buf[pos] !== 0xff || (buf[pos + 1] & 0xf6) !== 0xf0) {
352
305
  if (frames === 0) {
353
- pos++ // still hunting for the first sync
306
+ pos++
354
307
  continue
355
308
  }
356
- break // garbage after the stream: stop like a decoder would
309
+ break
357
310
  }
358
311
  const sfi = (buf[pos + 2] >> 2) & 0x0f
359
312
  const frameLength = ((buf[pos + 3] & 0x03) << 11) | (buf[pos + 4] << 3) | (buf[pos + 5] >> 5)
@@ -371,8 +324,6 @@ const adtsDuration = buf => {
371
324
  return frames && sampleRate ? (frames * 1024) / sampleRate : undefined
372
325
  }
373
326
 
374
- /* ------------------------------ AIFF / AIFF-C ------------------------------ */
375
-
376
327
  const aiffDuration = buf => {
377
328
  if (ascii(buf, 0, 4) !== 'FORM') return undefined
378
329
  const kind = ascii(buf, 8, 4)
@@ -383,9 +334,9 @@ const aiffDuration = buf => {
383
334
  const size = u32be(buf, pos + 4)
384
335
  const body = pos + 8
385
336
  if (id === 'COMM') {
386
- if (size < 18 || body + size > buf.length) return undefined // the whole COMM chunk (incl. AIFF-C extras) must be present
337
+ if (size < 18 || body + size > buf.length) return undefined
387
338
  const frames = u32be(buf, body + 2)
388
- // 80-bit IEEE extended sample rate: 1 sign + 15 exponent bits, 64-bit mantissa (explicit integer bit)
339
+
389
340
  const exp = buf.readUInt16BE(body + 8) & 0x7fff
390
341
  const mantissa = buf.readBigUInt64BE(body + 10)
391
342
  const sampleRate = Number(mantissa) * 2 ** (exp - 16383 - 63)
@@ -396,14 +347,11 @@ const aiffDuration = buf => {
396
347
  return undefined
397
348
  }
398
349
 
399
- /* ------------------------------ Matroska / WebM ------------------------------ */
400
-
401
- /** EBML variable-length integer at `pos`. `keepMarker` = element IDs keep the length-marker bit, sizes drop it. */
402
350
  const ebmlVint = (buf, pos, keepMarker) => {
403
351
  if (pos >= buf.length) return undefined
404
352
  const first = buf[pos]
405
353
  if (first === 0) return undefined
406
- const len = Math.clz32(first) - 23 // 1..8
354
+ const len = Math.clz32(first) - 23
407
355
  if (pos + len > buf.length) return undefined
408
356
  let value = keepMarker ? first : first & (0xff >> len)
409
357
  let allOnes = (first & (0xff >> len)) === 0xff >> len
@@ -421,7 +369,7 @@ const matroskaDuration = buf => {
421
369
  for (let i = 0; i < n; i++) v = v * 256 + buf[o + i]
422
370
  return v
423
371
  }
424
- // walk `[start, end)` looking for the Segment > Info element; returns true once Info has been fully read
372
+
425
373
  const walk = (start, end, depth) => {
426
374
  let pos = start
427
375
  while (pos < end) {
@@ -432,9 +380,9 @@ const matroskaDuration = buf => {
432
380
  const body = pos + id.length + size.length
433
381
  const bodyEnd = size.unknown ? end : Math.min(end, body + size.value)
434
382
  if (id.value === 0x18538067 && depth === 0) {
435
- if (walk(body, bodyEnd, 1)) return true // Segment
383
+ if (walk(body, bodyEnd, 1)) return true
436
384
  } else if (id.value === 0x1549a966 && depth === 1) {
437
- // Info: TimecodeScale (uint) and Duration (float)
385
+
438
386
  let q = body
439
387
  while (q < bodyEnd) {
440
388
  const cid = ebmlVint(buf, q, true)
@@ -448,7 +396,7 @@ const matroskaDuration = buf => {
448
396
  }
449
397
  return true
450
398
  }
451
- if (size.unknown) return false // cannot skip an unknown-size element that is not the Segment
399
+ if (size.unknown) return false
452
400
  pos = body + size.value
453
401
  }
454
402
  return false
@@ -458,13 +406,9 @@ const matroskaDuration = buf => {
458
406
  return (info.duration * (info.timecodeScale || 1000000)) / 1e9
459
407
  }
460
408
 
461
- /* ------------------------------ AMR (NB and WB) ------------------------------ */
462
-
463
- // total bytes per frame (1 header byte + payload), indexed by frame type; 0 = invalid frame type
464
409
  const AMR_NB_FRAME_BYTES = [13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1]
465
410
  const AMR_WB_FRAME_BYTES = [18, 24, 33, 37, 41, 47, 51, 59, 61, 6, 0, 0, 0, 0, 1, 1]
466
411
 
467
- /** Every AMR frame (any mode, incl. SID and "no data") covers 20 ms. */
468
412
  const amrDuration = buf => {
469
413
  const wb = ascii(buf, 0, 9) === '#!AMR-WB\n'
470
414
  if (!wb && ascii(buf, 0, 6) !== '#!AMR\n') return undefined
@@ -473,17 +417,14 @@ const amrDuration = buf => {
473
417
  let frames = 0
474
418
  while (pos < buf.length) {
475
419
  const size = table[(buf[pos] >> 3) & 0x0f]
476
- if (!size) break // reserved frame type: not a valid stream from here on
477
- if (pos + size > buf.length) break // partial last frame is not counted
420
+ if (!size) break
421
+ if (pos + size > buf.length) break
478
422
  frames++
479
423
  pos += size
480
424
  }
481
425
  return frames ? frames * 0.02 : undefined
482
426
  }
483
427
 
484
- /* ------------------------------ dispatch ------------------------------ */
485
-
486
- /** @param {Buffer} buf @returns {number|undefined} duration in seconds */
487
428
  export const durationFromBuffer = buf => {
488
429
  if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
489
430
  if (buf.length < 12) return undefined
@@ -496,7 +437,7 @@ export const durationFromBuffer = buf => {
496
437
  if (magic === 'FORM') return aiffDuration(buf)
497
438
  if (buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3) return matroskaDuration(buf)
498
439
  if (magic === '#!AM') return amrDuration(buf)
499
- if (buf[0] === 0xff && (buf[1] & 0xf6) === 0xf0) return adtsDuration(buf) // sync + layer 00 = ADTS
440
+ if (buf[0] === 0xff && (buf[1] & 0xf6) === 0xf0) return adtsDuration(buf)
500
441
  if (magic.startsWith('ID3') || (buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0)) return mp3Duration(buf)
501
442
  } catch {
502
443
  return undefined
@@ -504,13 +445,12 @@ export const durationFromBuffer = buf => {
504
445
  return undefined
505
446
  }
506
447
 
507
- /** Accepts a Buffer, a file path, or a Readable stream (same inputs as the old `getAudioDuration`). */
508
448
  export const audioDuration = async input => {
509
449
  if (Buffer.isBuffer(input)) return durationFromBuffer(input)
510
450
  if (typeof input === 'string') {
511
451
  const { size } = await stat(input)
512
452
  if (size > 64 * 1024 * 1024) {
513
- // avoid loading huge files fully: header-only containers only need a prefix, Ogg needs the tail
453
+
514
454
  const fh = await open(input, 'r')
515
455
  try {
516
456
  const head = Buffer.alloc(Math.min(size, 4 * 1024 * 1024))
@@ -1,14 +1,3 @@
1
- /**
2
- * Native PCM decoders for waveform generation (replaces `audio-decode` for the formats that can be decoded exactly
3
- * without a codec library): WAV (PCM 8/16/24/32-bit, IEEE float 32/64, WAVE_FORMAT_EXTENSIBLE) and FLAC.
4
- *
5
- * `decodeChannel0(buffer)` returns the FIRST channel as a Float32Array in [-1, 1], or `undefined` when the container
6
- * is not one of the above (Ogg Opus/Vorbis, MP3, AAC, ... need a real codec: see getAudioWaveform's ffmpeg fallback).
7
- * Values are exactly sample / 2^(bits-1), i.e. what a bit-exact decoder produces.
8
- */
9
-
10
- /* ------------------------------ WAV ------------------------------ */
11
-
12
1
  function decodeWav(buf) {
13
2
  if (buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WAVE') return undefined
14
3
  let pos = 12
@@ -20,7 +9,7 @@ function decodeWav(buf) {
20
9
  if (id === 'fmt ') {
21
10
  let tag = buf.readUInt16LE(body)
22
11
  const bits = buf.readUInt16LE(body + 14)
23
- if (tag === 0xfffe && size >= 26) tag = buf.readUInt16LE(body + 24) // extensible: real format = first 2 bytes of SubFormat
12
+ if (tag === 0xfffe && size >= 26) tag = buf.readUInt16LE(body + 24)
24
13
  fmt = { tag, channels: buf.readUInt16LE(body + 2), blockAlign: buf.readUInt16LE(body + 12), bits }
25
14
  } else if (id === 'data') {
26
15
  if (!fmt || !fmt.channels || !fmt.blockAlign) return undefined
@@ -29,7 +18,7 @@ function decodeWav(buf) {
29
18
  const bytes = fmt.bits >> 3
30
19
  const out = new Float32Array(frames)
31
20
  for (let i = 0; i < frames; i++) {
32
- const o = body + i * fmt.blockAlign // channel 0 is the first sample of each frame
21
+ const o = body + i * fmt.blockAlign
33
22
  let v
34
23
  if (fmt.tag === 1) {
35
24
  if (fmt.bits === 8) v = (buf[o] - 128) / 128
@@ -41,7 +30,7 @@ function decodeWav(buf) {
41
30
  if (bytes === 4) v = buf.readFloatLE(o)
42
31
  else if (bytes === 8) v = buf.readDoubleLE(o)
43
32
  else return undefined
44
- } else return undefined // ADPCM, A-law, mu-law, MP3-in-WAV, ...
33
+ } else return undefined
45
34
  out[i] = v
46
35
  }
47
36
  return out
@@ -51,18 +40,16 @@ function decodeWav(buf) {
51
40
  return undefined
52
41
  }
53
42
 
54
- /* ------------------------------ FLAC ------------------------------ */
55
-
56
43
  class Bits {
57
44
  constructor(buf, pos) {
58
45
  this.buf = buf
59
- this.pos = pos * 8 // bit position
46
+ this.pos = pos * 8
60
47
  }
61
48
  get bytePos() {
62
49
  return this.pos >> 3
63
50
  }
64
51
  read(n) {
65
- // up to 32 bits, unsigned
52
+
66
53
  let v = 0
67
54
  while (n > 0) {
68
55
  const byte = this.buf[this.pos >> 3]
@@ -112,14 +99,14 @@ function readResidual(br, out, offset, blockSize, order) {
112
99
  const q = br.unary()
113
100
  const r = param ? br.read(param) : 0
114
101
  const u = q * 2 ** param + r
115
- out[n++] = u % 2 === 0 ? u / 2 : -(u + 1) / 2 // zig-zag
102
+ out[n++] = u % 2 === 0 ? u / 2 : -(u + 1) / 2
116
103
  }
117
104
  }
118
105
  }
119
106
  }
120
107
 
121
108
  function readSubframe(br, blockSize, bps) {
122
- br.read(1) // padding
109
+ br.read(1)
123
110
  const type = br.read(6)
124
111
  let wasted = 0
125
112
  if (br.read(1)) wasted = br.unary() + 1
@@ -153,7 +140,7 @@ function readSubframe(br, blockSize, bps) {
153
140
  for (let i = order; i < blockSize; i++) {
154
141
  let sum = 0
155
142
  for (let j = 0; j < order; j++) sum += coefs[j] * s[i - 1 - j]
156
- s[i] += shift >= 0 ? Math.floor(sum / div) : sum * 2 ** -shift // arithmetic right shift == floor division
143
+ s[i] += shift >= 0 ? Math.floor(sum / div) : sum * 2 ** -shift
157
144
  }
158
145
  } else throw new Error('FLAC: reserved subframe type')
159
146
  if (wasted) for (let i = 0; i < blockSize; i++) s[i] *= 2 ** wasted
@@ -181,14 +168,14 @@ function decodeFlac(buf) {
181
168
  const br = new Bits(buf, pos)
182
169
  while (br.bytePos + 6 < buf.length) {
183
170
  const sync = br.read(14)
184
- if (sync !== 0x3ffe) break // trailing garbage / end
185
- br.read(2) // reserved + blocking strategy
171
+ if (sync !== 0x3ffe) break
172
+ br.read(2)
186
173
  const bsCode = br.read(4)
187
174
  const srCode = br.read(4)
188
175
  const chAssign = br.read(4)
189
176
  const sizeCode = br.read(3)
190
177
  br.read(1)
191
- // coded frame/sample number: UTF-8 style, 1..7 bytes
178
+
192
179
  const first = br.read(8)
193
180
  let extra = first < 0x80 ? 0 : first < 0xe0 ? 1 : first < 0xf0 ? 2 : first < 0xf8 ? 3 : first < 0xfc ? 4 : first < 0xfe ? 5 : 6
194
181
  while (extra-- > 0) br.read(8)
@@ -198,30 +185,30 @@ function decodeFlac(buf) {
198
185
  if (!blockSize) throw new Error('FLAC: bad block size')
199
186
  if (srCode === 12) br.read(8)
200
187
  else if (srCode === 13 || srCode === 14) br.read(16)
201
- br.read(8) // header CRC-8
188
+ br.read(8)
202
189
  const bps = sizeCode === 0 ? streamBps : SAMPLE_BITS[sizeCode]
203
190
  if (!bps) throw new Error('FLAC: reserved sample size')
204
191
  const nch = chAssign < 8 ? chAssign + 1 : 2
205
192
  const chans = []
206
193
  for (let c = 0; c < nch; c++) {
207
- // the side channel carries one extra bit
194
+
208
195
  const extraBit = (chAssign === 8 && c === 1) || (chAssign === 9 && c === 0) || (chAssign === 10 && c === 1) ? 1 : 0
209
196
  chans.push(readSubframe(br, blockSize, bps + extraBit))
210
197
  }
211
198
  br.align()
212
- br.read(16) // frame CRC-16
213
- // channel 0 after undoing inter-channel decorrelation
199
+ br.read(16)
200
+
214
201
  let ch0 = chans[0]
215
- if (chAssign === 8) ch0 = chans[0] // left/side: channel 0 is left already
202
+ if (chAssign === 8) ch0 = chans[0]
216
203
  else if (chAssign === 9) {
217
- ch0 = new Float64Array(blockSize) // side/right: left = side + right
204
+ ch0 = new Float64Array(blockSize)
218
205
  for (let i = 0; i < blockSize; i++) ch0[i] = chans[0][i] + chans[1][i]
219
206
  } else if (chAssign === 10) {
220
- ch0 = new Float64Array(blockSize) // mid/side: left = (mid*2 + (side&1) + side) / 2
207
+ ch0 = new Float64Array(blockSize)
221
208
  for (let i = 0; i < blockSize; i++) {
222
209
  const side = chans[1][i]
223
210
  const mid = chans[0][i] * 2 + (((side % 2) + 2) % 2)
224
- ch0[i] = (mid + side) / 2 // exact: mid and side always have the same parity
211
+ ch0[i] = (mid + side) / 2
225
212
  }
226
213
  }
227
214
  const scale = 2 ** (bps - 1)
@@ -239,7 +226,6 @@ function decodeFlac(buf) {
239
226
  return total && count > total ? out.subarray(0, total) : out
240
227
  }
241
228
 
242
- /** @returns {Float32Array|undefined} first channel, or undefined if the container is not WAV/FLAC */
243
229
  export function decodeChannel0(buffer) {
244
230
  if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer)
245
231
  if (buffer.length < 12) return undefined
@@ -250,10 +236,6 @@ export function decodeChannel0(buffer) {
250
236
  }
251
237
  }
252
238
 
253
- /**
254
- * The 64-value voice-note waveform (0..100) — same algorithm as upstream's getAudioWaveform:
255
- * 64 equal blocks, mean absolute amplitude per block, scaled so the loudest block is 100.
256
- */
257
239
  export function waveformFromSamples(rawData, samples = 64) {
258
240
  const blockSize = Math.floor(rawData.length / samples)
259
241
  const filtered = []
@@ -1,10 +1,3 @@
1
- /**
2
- * Minimal replacement for `@hapi/boom`.
3
- * Baileys only ever does: `new Boom(message, { statusCode, data })`,
4
- * `err instanceof Boom`, and reads `err.output.statusCode` / `err.data` / `err.isBoom`.
5
- * That's the entire surface reproduced here.
6
- */
7
-
8
1
  const STATUS_TEXT = {
9
2
  400: 'Bad Request',
10
3
  401: 'Unauthorized',
@@ -1,26 +1,10 @@
1
- /**
2
- * Replaces `lru-cache` and `@cacheable/node-cache`.
3
- *
4
- * Covers exactly the surface Baileys uses against both libraries:
5
- * get(key), set(key, value), has(key), delete(key), clear()/flushAll()
6
- * with:
7
- * - ttl (ms): entries expire after this long
8
- * - max: hard cap on entry count (oldest inserted/refreshed evicted first)
9
- * - updateAgeOnGet: a `get()` refreshes the entry's TTL clock (both libs support this)
10
- * - dispose(value, key): called when an entry is evicted, whether by TTL or by `max`
11
- *
12
- * Built on a plain Map (insertion order == recency order once we re-insert on
13
- * touch), with a lazy sweep instead of a per-entry timer so a cache with many
14
- * short-lived entries doesn't spin up thousands of timers.
15
- */
16
-
17
1
  export class Cache {
18
2
  constructor(options = {}) {
19
- this.ttl = options.ttl ?? (options.stdTTL ? options.stdTTL * 1000 : 0) // stdTTL is node-cache's seconds-based option
3
+ this.ttl = options.ttl ?? (options.stdTTL ? options.stdTTL * 1000 : 0)
20
4
  this.max = options.max || Infinity
21
5
  this.updateAgeOnGet = !!options.updateAgeOnGet
22
6
  this.dispose = options.dispose || (() => {})
23
- this._store = new Map() // key -> { value, expiresAt }
7
+ this._store = new Map()
24
8
 
25
9
  if (this.ttl > 0) {
26
10
  this._sweeper = setInterval(() => this._sweep(), Math.min(this.ttl, 60_000))
@@ -52,7 +36,7 @@ export class Cache {
52
36
  }
53
37
  if (this.updateAgeOnGet && this.ttl > 0) {
54
38
  entry.expiresAt = Date.now() + this.ttl
55
- // re-insert to move to the back (most-recently-used) for `max` eviction order
39
+
56
40
  this._store.delete(key)
57
41
  this._store.set(key, entry)
58
42
  }
@@ -60,7 +44,7 @@ export class Cache {
60
44
  }
61
45
 
62
46
  set(key, value) {
63
- if (this._store.has(key)) this._store.delete(key) // re-insert to refresh recency order
47
+ if (this._store.has(key)) this._store.delete(key)
64
48
  this._store.set(key, {
65
49
  value,
66
50
  expiresAt: this.ttl > 0 ? Date.now() + this.ttl : 0
@@ -98,17 +82,14 @@ export class Cache {
98
82
  this._store.clear()
99
83
  }
100
84
 
101
- // node-cache alias
102
85
  flushAll() {
103
86
  this.clear()
104
87
  }
105
88
 
106
- // node-cache alias: `del(key)` (Baileys calls this, e.g. msgRetryCache.del / placeholderResendCache.del)
107
89
  del(key) {
108
90
  return this.delete(key)
109
91
  }
110
92
 
111
- /** node-cache's close(): stop the background sweeper so the process can exit cleanly. */
112
93
  close() {
113
94
  if (this._sweeper) {
114
95
  clearInterval(this._sweeper)
@@ -116,7 +97,6 @@ export class Cache {
116
97
  }
117
98
  }
118
99
 
119
- /** node-cache's mget: returns { [key]: value } for keys that were found (and not expired). */
120
100
  mget(keys) {
121
101
  const result = {}
122
102
  for (const key of keys) {
@@ -126,7 +106,6 @@ export class Cache {
126
106
  return result
127
107
  }
128
108
 
129
- /** node-cache's mset: data is an array of { key, value, ttl? } (ttl currently ignored — per-entry TTL override not needed by Baileys' usage). */
130
109
  mset(data) {
131
110
  for (const item of data) this.set(item.key, item.value)
132
111
  return true
@@ -137,6 +116,5 @@ export class Cache {
137
116
  }
138
117
  }
139
118
 
140
- /** Factory mirroring `new LRUCache(opts)` / `new NodeCache(opts)` call sites. */
141
119
  export const LRUCache = Cache
142
120
  export const NodeCache = Cache