@zervonexx/baileys 5.0.1 → 5.0.2

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.
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync, existsSync } from 'fs'
1
+ import { readFileSync } from 'fs'
2
2
  import { fileURLToPath } from 'url'
3
3
  import Long from 'long'
4
4
 
@@ -10,11 +10,6 @@ const KIND = [
10
10
  { k: 'string' }, { k: 'bytes' }, { k: 'varint', s: 'enum' }, { k: 'varint', s: 'long' }, { k: 'varint', s: 'zigzaglong' },
11
11
  ]
12
12
 
13
- const SCALAR_TC = {
14
- int32: 0, uint32: 0, sint32: 1, bool: 2, fixed64: 3, sfixed64: 3, double: 4,
15
- fixed32: 5, sfixed32: 5, float: 6, string: 7, bytes: 8, int64: 10, uint64: 10, sint64: 11,
16
- }
17
-
18
13
  const isLongLike = v => v !== null && typeof v === 'object' && 'low' in v && 'high' in v
19
14
  const longToBigInt = v => (v.unsigned ? BigInt(v.high >>> 0) : BigInt(v.high | 0)) * 4294967296n + BigInt(v.low >>> 0)
20
15
  const anyToBigInt = v => typeof v === 'bigint' ? v : isLongLike(v) ? longToBigInt(v) : BigInt(Math.trunc(Number(v)))
@@ -212,46 +207,6 @@ function makeCodec(TABLE, enumIndex) {
212
207
  }
213
208
  }
214
209
 
215
- export async function generateTable(protoPath, outPath) {
216
- const pb = await import('protobufjs')
217
- const protobuf = pb.default || pb
218
- const root = await protobuf.load(protoPath)
219
- const msgNames = []
220
- const msgIndex = n => { let i = msgNames.indexOf(n); return i < 0 ? msgNames.push(n) - 1 : i }
221
- const t = {}, e = {}
222
- const build = ns => {
223
- for (const o of Object.values(ns.nested ?? {})) {
224
- const full = o.fullName.replace(/^\./, '')
225
- if (o.values) e[full] = o.values
226
- if (o.fieldsArray) {
227
- const fs = []
228
- for (const f of o.fieldsArray) {
229
- if (f.map) continue
230
- const rt = f.resolvedType
231
- let tc, enumName
232
- if (rt?.fieldsArray !== undefined && rt?.values === undefined) tc = 100 + msgIndex(rt.fullName.replace(/^\./, ''))
233
- else if (rt?.values) { tc = 9; enumName = rt.fullName.replace(/^\./, '') }
234
- else tc = SCALAR_TC[f.type]
235
- const numeric = tc < 100 && tc !== 7 && tc !== 8
236
- const flags = (f.repeated ? 1 : 0) | (f.repeated && numeric && f.packed !== false ? 2 : 0)
237
- if (tc === 9) fs.push([f.name, f.id, 9, flags, enumName])
238
- else if (flags) fs.push([f.name, f.id, tc, flags])
239
- else fs.push([f.name, f.id, tc])
240
- }
241
- fs.sort((a, b) => a[1] - b[1])
242
- t[full] = fs
243
- }
244
- if (o.nested) build(o)
245
- }
246
- }
247
- build(root)
248
- const tmp = outPath + '.tmp'
249
- writeFileSync(tmp, JSON.stringify({ m: msgNames, t, e }))
250
- const { renameSync } = await import('fs')
251
- renameSync(tmp, outPath)
252
- return { types: Object.keys(t).length, enums: Object.keys(e).length }
253
- }
254
-
255
210
  function makeProto(tablePath) {
256
211
  const { m, t, e } = JSON.parse(readFileSync(tablePath, 'utf8'))
257
212
  const TABLE = buildTable(t, m)
@@ -294,22 +249,11 @@ function makeProto(tablePath) {
294
249
  return { proto, codec }
295
250
  }
296
251
 
297
- const isGeneratorRun = process.argv[1] && (process.argv[1] === fileURLToPath(import.meta.url) || process.argv.includes('--generate'))
298
-
299
- if (isGeneratorRun) {
300
- const protoPath = fileURLToPath(new URL('./WAProto.proto', import.meta.url))
301
- const outPath = fileURLToPath(new URL('./WAProto.json', import.meta.url))
302
- generateTable(protoPath, outPath)
303
- .then(r => { process.stdout.write(`[WAProto] Generated: ${r.types} types, ${r.enums} enums\n`); process.exit(0) })
304
- .catch(err => { process.stderr.write(err.message + '\n'); process.exit(1) })
305
- }
306
-
307
252
  const tablePath = fileURLToPath(new URL('./WAProto.json', import.meta.url))
308
253
  const built = { proto: {}, codec: null }
309
254
 
310
255
  export let codec = null
311
256
  export function _reloadProto() {
312
- if (!existsSync(tablePath)) return
313
257
  const loaded = makeProto(tablePath)
314
258
  for (const key of Object.keys(built.proto)) delete built.proto[key]
315
259
  Object.assign(built.proto, loaded.proto)
@@ -317,7 +261,5 @@ export function _reloadProto() {
317
261
  codec = loaded.codec
318
262
  }
319
263
 
320
- if (!isGeneratorRun && existsSync(tablePath)) _reloadProto()
321
-
322
264
  export const proto = built.proto
323
265
  export default built
package/WAProto/index.js CHANGED
@@ -1,96 +1,56 @@
1
- import { existsSync, unlinkSync, readFileSync } from 'fs'
1
+ import { existsSync, readFileSync } from 'fs'
2
2
  import { join, dirname } from 'path'
3
3
  import { fileURLToPath } from 'url'
4
- import { Worker, isMainThread, workerData, parentPort } from 'worker_threads'
5
4
  import logger from '../lib/Utils/logger.js'
6
- import { fetchProtoBundle } from './fetcher.js'
7
- import { generateTable, _reloadProto } from './WAProtoCompile.js'
8
- import { parseBundle } from './parser.js'
5
+ import { _reloadProto } from './WAProtoCompile.js'
9
6
 
10
7
  const __dirname = dirname(fileURLToPath(import.meta.url))
11
8
  const PROTO_FILE = join(__dirname, 'WAProto.proto')
12
9
  const TABLE_FILE = join(__dirname, 'WAProto.json')
13
- const SELF = new URL(import.meta.url)
14
10
 
15
- const log = msg => logger.info(msg)
16
- const err = msg => logger.error(msg)
17
- const del = (...files) => { for (const f of files) { try { if (existsSync(f)) unlinkSync(f) } catch { } } }
18
- const isJsonValid = () => { try { const { m, t } = JSON.parse(readFileSync(TABLE_FILE, 'utf8')); return Array.isArray(m) && m.length > 0 && typeof t === 'object' && Object.keys(t).length > 0 } catch { return false } }
19
-
20
- function runInWorker(data) {
21
- return new Promise((resolve, reject) => {
22
- const w = new Worker(SELF, { workerData: data })
23
- w.once('message', msg => { w.terminate(); msg.ok ? resolve() : reject(new Error(msg.error)) })
24
- w.once('error', reject)
25
- })
11
+ const isJsonValid = () => {
12
+ try {
13
+ const { m, t } = JSON.parse(readFileSync(TABLE_FILE, 'utf8'))
14
+ return Array.isArray(m) && m.length > 0 && typeof t === 'object' && Object.keys(t).length > 0
15
+ } catch { return false }
26
16
  }
27
17
 
28
- async function regenerateFromProto() {
29
- log('Regenerating WAProto.json from existing WAProto.proto...')
30
- await runInWorker({ bundlePath: null, version: null, protoPath: PROTO_FILE, tablePath: TABLE_FILE })
18
+ function boot() {
19
+ if (!existsSync(PROTO_FILE) || !existsSync(TABLE_FILE)) throw new Error('[WAProto] Proto files missing — reinstall the package')
20
+ if (!isJsonValid()) throw new Error('[WAProto] WAProto.json invalid or corrupt — reinstall the package')
31
21
  _reloadProto()
32
- log('Regenerated successfully')
33
22
  }
34
23
 
35
- async function refetch() {
36
- log('Fetching proto bundle from GitHub...')
37
- const { bundle, bundlePath, version } = await fetchProtoBundle()
38
- if (!bundle && !bundlePath) throw new Error('fetchProtoBundle returned no bundle')
39
- await runInWorker({ bundlePath: bundlePath ?? null, bundle: bundle ?? null, version, protoPath: PROTO_FILE, tablePath: TABLE_FILE })
40
- _reloadProto()
41
- log(`Fetched and compiled — WA version ${version}`)
42
- }
24
+ boot()
43
25
 
44
- async function boot() {
45
- const hasProto = existsSync(PROTO_FILE)
46
- const hasJson = existsSync(TABLE_FILE)
26
+ let _versionCache = null
47
27
 
48
- if (hasProto && hasJson) {
49
- if (isJsonValid()) { _reloadProto(); return }
50
- err('WAProto.json is invalid or corrupt — regenerating from proto...')
51
- del(TABLE_FILE)
52
- try { await regenerateFromProto(); return } catch (e) {
53
- err(`Regeneration failed: ${e.message} — refetching from WA Web...`)
54
- del(PROTO_FILE, TABLE_FILE)
55
- await refetch()
56
- }
57
- return
58
- }
59
- if (hasProto && !hasJson) {
60
- log('WAProto.json missing — generating from existing proto...')
61
- try { await regenerateFromProto(); return } catch (e) {
62
- err(`Generation failed: ${e.message} — refetching from WA Web...`)
63
- del(PROTO_FILE, TABLE_FILE)
64
- await refetch()
65
- }
66
- return
28
+ export const WAProtoReady = fetch('https://web.whatsapp.com/sw.js', {
29
+ headers: {
30
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
31
+ 'Referer': 'https://web.whatsapp.com',
32
+ 'Sec-Fetch-Dest': 'script',
33
+ 'Sec-Fetch-Mode': 'no-cors',
34
+ 'Sec-Fetch-Site': 'same-origin',
67
35
  }
68
- if (hasJson && !hasProto) { err('WAProto.proto missing but WAProto.json exists — cannot trust JSON, refetching...'); del(TABLE_FILE); await refetch(); return }
69
-
70
- log('No proto files found — fetching from GitHub...')
71
- await refetch()
72
- }
36
+ })
37
+ .then(res => res.text())
38
+ .then(text => {
39
+ const match = text.match(/client_revision[^0-9]*([0-9]+)/)
40
+ if (!match) throw new Error('[WAProto] client_revision not found in sw.js')
41
+ const revision = parseInt(match[1], 10)
42
+ if (isNaN(revision)) throw new Error(`[WAProto] client_revision is NaN: ${match[1]}`)
43
+ _versionCache = [2, 3000, revision]
44
+ logger.info(`[WAProto] WA version: ${_versionCache.join('.')}`)
45
+ })
46
+ .catch(err => {
47
+ logger.warn(`[WAProto] Version fetch failed: ${err.message}`)
48
+ })
73
49
 
74
- if (!isMainThread) {
75
- const { bundlePath, bundle, version, protoPath, tablePath } = workerData
76
- try {
77
- if (bundlePath || bundle) {
78
- const src = bundlePath ? readFileSync(bundlePath, 'utf8') : bundle
79
- if (bundlePath) unlinkSync(bundlePath)
80
- const { writeFileSync, renameSync } = await import('fs')
81
- const tmp = protoPath + '.tmp'
82
- writeFileSync(tmp, parseBundle(src, version), 'utf8')
83
- renameSync(tmp, protoPath)
84
- }
85
- await generateTable(protoPath, tablePath)
86
- parentPort.postMessage({ ok: true })
87
- } catch (e) {
88
- parentPort.postMessage({ ok: false, error: e.message })
89
- }
90
- } else {
91
- await boot()
50
+ export function getWAVersion() {
51
+ if (!_versionCache) throw new Error('[WAProto] WA version unavailable — fetch failed at boot')
52
+ return _versionCache
92
53
  }
93
54
 
94
- export { proto, codec, generateTable, _reloadProto } from './WAProtoCompile.js'
95
- export { getWAVersion, fetchProtoBundle } from './fetcher.js'
55
+ export { proto, codec, _reloadProto } from './WAProtoCompile.js'
96
56
  export { default } from './WAProtoCompile.js'
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'crypto';
2
- import { proto, getWAVersion } from '../../WAProto/index.js';
2
+ import { proto, getWAVersion, WAProtoReady } from '../../WAProto/index.js'
3
3
  import { makeLibSignalRepository } from '../Signal/index.js';
4
4
  import { Browsers, logger } from '../Utils/index.js';
5
5
  import urlRegexSafe from 'url-regex-safe';
@@ -23,7 +23,8 @@ export const PHONENUMBER_MCC = (() => {
23
23
  })()
24
24
 
25
25
  // version is fetched dynamically from WA Web sw.js via getWAVersion()
26
- const version = await getWAVersion()
26
+ await WAProtoReady
27
+ const version = getWAVersion()
27
28
 
28
29
  export const UNAUTHORIZED_CODES = [401, 403, 419];
29
30
 
@@ -1,6 +1,9 @@
1
1
  import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js'
2
+ import { WAProtoReady } from '../../WAProto/index.js'
2
3
  import { makeMessageBuilderSocket } from './zervonex-handler.js'
3
4
 
5
+ await WAProtoReady
6
+
4
7
  const makeWASocket = (config) => {
5
8
  const newConfig = { ...DEFAULT_CONNECTION_CONFIG, ...config }
6
9
  if (config.shouldSyncHistoryMessage === undefined) {
@@ -61,7 +61,7 @@ export const uploadingNecessaryImagesOfProduct = async (product, waUploadToServe
61
61
 
62
62
  export const uploadingNecessaryImages = (images, waUploadToServer, timeoutMs = 30000) =>
63
63
  Promise.all(images.map(async img => {
64
- if ('url' in img && img.url.toString().includes('.whatsapp.net')) return { url: img.url.toString() }
64
+ if ('url' in img) try { const h = new URL(img.url.toString()).hostname.toLowerCase(); if (h === 'whatsapp.net' || h.endsWith('.whatsapp.net')) return { url: img.url.toString() } } catch { }
65
65
  const { stream } = await getStream(img)
66
66
  const hasher = createHash('sha256')
67
67
  const blocks = []
@@ -1,7 +1,7 @@
1
1
  import { Boom } from '@hapi/boom'
2
2
  import { createHash, randomBytes } from 'crypto'
3
3
  import { createRequire } from 'module'
4
- import { proto, fetchProtoBundle } from '../../WAProto/index.js'
4
+ import { proto, getWAVersion, WAProtoReady } from '../../WAProto/index.js'
5
5
  import { DisconnectReason } from '../Types/index.js'
6
6
  import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js'
7
7
  import { sha256 } from './crypto.js'
@@ -98,8 +98,9 @@ export const bindWaitForEvent = (ev, event) => async (check, timeoutMs) => {
98
98
  export const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connection.update')
99
99
 
100
100
  export const fetchLatestWaWebVersion = async () => {
101
- const { version } = await fetchProtoBundle()
102
- return { version: [2, 3000, parseInt(version)], isLatest: true }
101
+ await WAProtoReady
102
+ const version = getWAVersion()
103
+ return { version, isLatest: true }
103
104
  }
104
105
  export const fetchLatestBaileysVersion = fetchLatestWaWebVersion
105
106
 
@@ -186,9 +187,9 @@ export const waitAllPromises = async value => {
186
187
  export const extractIE = (text, extraEntities = []) => {
187
188
  const entities = [...extraEntities]
188
189
  let out = text
189
- out = out.replace(/\[\[([^:]+):([^\]]+)\]\]/g, (_, key, url) => { entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAILatexItem', latex_expression: '.', font_height: 83.333, padding: 15, latex_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url, url_fallback: url, width: 400, height: 400, expiration_timestamp_ms: Date.now() + 86400000 } } }); return `{{${key}}}.{{/${key}}}` })
190
- out = out.replace(/\[([^\]]+)\]\(>([^)]+)\)/g, (_, display, deeplink) => { const key = `dl_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIDeeplinkInlineEntityMetadata', deeplink, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
191
- out = out.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, (_, display, url) => { const key = `lnk_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIHyperlinkInlineEntityMetadata', url, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
190
+ out = out.replace(/\[\[([^:\]]+):([^\]\[]+)\]\]/g, (_, key, url) => { entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAILatexItem', latex_expression: '.', font_height: 83.333, padding: 15, latex_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url, url_fallback: url, width: 400, height: 400, expiration_timestamp_ms: Date.now() + 86400000 } } }); return `{{${key}}}.{{/${key}}}` })
191
+ out = out.replace(/\[([^\]\[]+)\]\(>([^)]+)\)/g, (_, display, deeplink) => { const key = `dl_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIDeeplinkInlineEntityMetadata', deeplink, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
192
+ out = out.replace(/\[([^\]\[]+)\]\((https?:\/\/[^)]+)\)/g, (_, display, url) => { const key = `lnk_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIHyperlinkInlineEntityMetadata', url, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
192
193
  return { text: out, inline_entities: entities }
193
194
  }
194
195
 
@@ -1,3 +1,4 @@
1
1
  import P from 'pino';
2
- export const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
2
+ const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
3
+ export { logger };
3
4
  export default logger;
@@ -420,7 +420,7 @@ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, {
420
420
 
421
421
  // ─── UPLOAD ───────────────────────────────────────────────────────────────────
422
422
 
423
- export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
423
+ export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''))
424
424
 
425
425
  export const extensionForMediaMessage = message => {
426
426
  const type = Object.keys(message)[0]
@@ -297,13 +297,15 @@ export const prepareWAMessageMedia = async (message, options) => {
297
297
 
298
298
  if (mediaType === 'sticker') {
299
299
  try {
300
- const rawBuf = await toBuffer(uploadData.media)
301
300
  const packName = message.pack || message.packName || options?.pack || options?.packName || 'ZervonexStickers'
302
301
  const authorName = message.author || message.publisher || message.packPublisher || options?.author || options?.publisher || options?.packPublisher || 'Zervonex'
303
- const { buffer } = await compressWebp(rawBuf, { packName, authorName, stickerType: message.stickerType || options?.stickerType || StickerTypes.ROUNDED, quality: message.quality || options?.quality || 80 })
302
+ const { buffer } = await compressWebp(await toBuffer(uploadData.media), { packName, authorName, stickerType: message.stickerType || options?.stickerType || StickerTypes.ROUNDED, quality: message.quality || options?.quality || 80 })
304
303
  uploadData.media = buffer
305
304
  uploadData.stickerSentTs = Date.now()
306
305
  if (message.premium != null) uploadData.premium = message.premium
306
+ const rawAudio = message.audio ?? message.stickerAudio ?? message.audioFooter
307
+ if (rawAudio != null) try { uploadData.audioMessage = (await prepareWAMessageMedia({ audio: rawAudio }, options)).audioMessage } catch (e) { options.logger?.warn({ err: e }, 'sticker audio preparation failed') }
308
+ else if (message.audioMessage != null) uploadData.audioMessage = message.audioMessage
307
309
  } catch (e) { options.logger?.warn({ err: e }, 'sticker formatting failed, sending raw') }
308
310
  }
309
311
 
package/lib/index.js CHANGED
@@ -29,7 +29,7 @@ const info = [
29
29
  '╭──────────────────────────────────────────────────────────────╮',
30
30
  '│ │',
31
31
  '│ ◆ Package › @zervonexx/baileys │',
32
- '│ ◆ Version › 5.0.1 │',
32
+ '│ ◆ Version › 5.0.2 │',
33
33
  '│ ◆ Status › Production Ready │',
34
34
  '│ │',
35
35
  '├──────────────────────────── ◇◆◇ ─────────────────────────────┤',
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@zervonexx/baileys",
4
4
  "type": "module",
5
- "version": "5.0.1",
5
+ "version": "5.0.2",
6
6
  "description": "Advanced WhatsApp Web API built on Baileys — interactive messages, buttons, carousels, products, events, payments, polls, albums, sticker packs and more.",
7
7
  "keywords": [
8
8
  "baileys",
@@ -75,7 +75,6 @@
75
75
  "main": "lib/index.js",
76
76
  "scripts": {
77
77
  "generate:license": "npx license",
78
- "gen:protobuf": "node ./WAProto/index.js",
79
78
  "prepack": "echo 'Zervonex WhatsApp Library'",
80
79
  "prepare": "echo 'Zervonex WhatsApp Library'",
81
80
  "test": "node ./lib/index.js"
@@ -98,8 +97,6 @@
98
97
  "@keyv/redis": "^6.1.0",
99
98
  "@keyv/sqlite": "^6.1.0",
100
99
  "@zanixongroup/uploader": "^2.1.5",
101
- "acorn": "^8.18.0",
102
- "acorn-walk": "^8.3.5",
103
100
  "async-mutex": "^0.5.0",
104
101
  "axios": "^1.20.0",
105
102
  "cache-manager": "^7.2.9",
@@ -118,7 +115,6 @@
118
115
  "p-queue": "^10.0.0",
119
116
  "pino": "^10.4.0",
120
117
  "prismjs": "^1.30.0",
121
- "protobufjs": "^8.8.1",
122
118
  "qrcode-terminal": "^0.12.0",
123
119
  "rlottie": "^0.1.2",
124
120
  "tempy": "^3.2.0",
@@ -1,68 +0,0 @@
1
- import { fetch, Agent } from 'undici'
2
- import { readFileSync, writeFileSync, existsSync, createWriteStream, unlinkSync } from 'fs'
3
- import { pipeline } from 'stream/promises'
4
- import { join, dirname } from 'path'
5
- import { fileURLToPath } from 'url'
6
-
7
- const __dirname = dirname(fileURLToPath(import.meta.url))
8
- const CACHE_FILE = join(__dirname, '.cache.json')
9
- const PROTO_FILE = join(__dirname, 'WAProto.proto')
10
- const BUNDLE_TMP = join(__dirname, 'WAProto.bundle.tmp')
11
- const GITHUB_RAW = 'https://raw.githubusercontent.com/zervonex/baileys/wa-cache'
12
-
13
- const agent = new Agent({ connect: { family: 4, timeout: 60000 } })
14
-
15
- // ── Cache helpers ─────────────────────────────────────────────────────────────
16
-
17
- const readCache = () => { try { return existsSync(CACHE_FILE) ? JSON.parse(readFileSync(CACHE_FILE, 'utf8')) : {} } catch { return {} } }
18
- const writeCache = (data) => writeFileSync(CACHE_FILE, JSON.stringify(data, null, 2), 'utf8')
19
- const isCacheValid = (cache) => !!(cache.version && cache.hash && existsSync(PROTO_FILE))
20
- const hasLocal = (cache) => !!(cache.version && existsSync(PROTO_FILE))
21
- const removeTmp = () => { try { if (existsSync(BUNDLE_TMP)) unlinkSync(BUNDLE_TMP) } catch { } }
22
-
23
- // ── GitHub fetch ──────────────────────────────────────────────────────────────
24
-
25
- async function fetchJSON(file) {
26
- const res = await fetch(`${GITHUB_RAW}/${file}`, { dispatcher: agent })
27
- if (!res.ok) throw new Error(`[WAProto] fetch failed for ${file}: ${res.status}`)
28
- return res.json()
29
- }
30
-
31
- async function fetchBundle() {
32
- const res = await fetch(`${GITHUB_RAW}/WAProto.bundle.js`, { dispatcher: agent })
33
- if (!res.ok) throw new Error(`[WAProto] fetch failed for WAProto.bundle.js: ${res.status}`)
34
- await pipeline(res.body, createWriteStream(BUNDLE_TMP))
35
- }
36
-
37
- // ── Public API ────────────────────────────────────────────────────────────────
38
-
39
- export async function fetchProtoBundle() {
40
- const cache = readCache()
41
- if (isCacheValid(cache)) return { changed: false, version: cache.version }
42
- try {
43
- const { version, hash } = await fetchJSON('wa-version.json')
44
- if (!version || !hash) throw new Error('[WAProto] wa-version.json missing version or hash field')
45
- if (cache.version === String(version) && cache.hash === hash && existsSync(PROTO_FILE)) {
46
- writeCache({ version: String(version), hash })
47
- return { changed: false, version: String(version) }
48
- }
49
- await fetchBundle()
50
- writeCache({ version: String(version), hash })
51
- return { changed: true, bundlePath: BUNDLE_TMP, version: String(version) }
52
- } catch (err) {
53
- removeTmp()
54
- if (hasLocal(cache)) return { changed: false, version: cache.version }
55
- throw new Error(`[WAProto] fetch failed and no local files available: ${err.message}`)
56
- }
57
- }
58
-
59
- export async function getWAVersion() {
60
- const cache = readCache()
61
- if (isCacheValid(cache)) return [2, 3000, parseInt(cache.version)]
62
- try {
63
- const { version } = await fetchJSON('wa-version.json')
64
- return [2, 3000, parseInt(String(version))]
65
- } catch {
66
- return [2, 3000, parseInt(cache.version || '0')]
67
- }
68
- }