{"_id":"@japofc/baileys","_rev":"28-60f3fe9b55533f874247d02d347751c3","name":"@japofc/baileys","dist-tags":{"new":"2.4.7-new","latest":"2.4.8"},"versions":{"2.4.7-new":{"name":"@japofc/baileys","version":"2.4.7-new","keywords":["anti-ban","automation","baileys","baileys-api","baileys-bot","baileys-esm","baileys-fork","baileys-fork-jap","baileys-javascript","baileys-js","baileys-library","baileys-md","baileys-multi-device","baileys-multidevice","baileys-node","baileys-nodejs","baileys-whatsapp","baileys-whatsapp-api","baileys-whatsapp-bot","bot-framework","buttons","chatbot","group-management","interactive-messages","jap","jap-baileys","jap-baileys-md","jap-whatsapp","japbaileys","japofc","multi-device","newsletter","sticker","termux","voip","whatsapp","whatsapp-api","whatsapp-api-baileys","whatsapp-automation","whatsapp-baileys","whatsapp-bot","whatsapp-bot-baileys","whatsapp-multi-device","whatsapp-web","whatsapp-web-baileys"],"author":{"name":"JAPofc"},"license":"MIT","_id":"@japofc/baileys@2.4.7-new","maintainers":[{"name":"japofc","email":"kielsahaz@gmail.com"}],"homepage":"https://github.com/JAPofc/baileys#readme","bugs":{"url":"https://github.com/JAPofc/baileys/issues"},"bin":{"japofc-baileys":"lib/cli.js"},"dist":{"shasum":"9d2ebdf02b38245eee6b0827f5029396e5dd3991","tarball":"https://registry.npmjs.org/@japofc/baileys/-/baileys-2.4.7-new.tgz","fileCount":615,"integrity":"sha512-XxFJIcq0/PUvkR/HAhXsJ4SPU83nK95K62ivSKENxLFe/xYzpDsFW/d5igDUHXRZ1U2FcdseOBs+YIrpoTOExQ==","signatures":[{"sig":"MEUCIBoVPx/kEd5nNomLdiKwDXQBln5AWNyhNDVvXMi08MuVAiEAsWl4YmjNJjcQwdLW8Yg4Ns5WRNLu6UWP/2Q3ZumcCtw=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"sig":"MEQCIDkBy7Lbj18t2mPz9ZBytlpwc/7JucDdufYCo1rwLBt3AiANTslmcRhK9jgsu47Sj4W3HGm9pqM+u1MyUkUyTfMMow==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":26914759},"main":"./lib/index.js","type":"module","types":"./lib/index.d.ts","module":"./lib/index.js","engines":{"node":">=20.0.0"},"exports":{".":{"types":"./lib/index.d.ts","import":"./lib/index.js","default":"./lib/index.js"},"./lib/*":{"types":"./lib/*.d.ts","import":"./lib/*.js","default":"./lib/*.js"},"./WAProto":{"types":"./WAProto/index.d.ts","import":"./WAProto/index.js","default":"./WAProto/index.js"},"./lib/*.js":{"types":"./lib/*.d.ts","import":"./lib/*.js","default":"./lib/*.js"},"./WAProto/*":{"types":"./WAProto/*.d.ts","import":"./WAProto/*.js","default":"./WAProto/*.js"},"./WAProto/*.js":{"types":"./WAProto/*.d.ts","import":"./WAProto/*.js","default":"./WAProto/*.js"},"./package.json":"./package.json"},"gitHead":"ceec6b2d80b8f3269163a703a1f8aa579a1d71ee","scripts":{"test":"node --test","wa:check":"node lib/cli.js wa","test:types":"tsc -p tests/tscheck/tsconfig.json","release:check":"npm test && npm run test:types && npm audit && npm pack --dry-run","voip:fetch-wasm":"node --experimental-websocket ./scripts/fetch-wasm-resources.mjs","capture:protocol":"node examples/protocol-capture-bot.js","voip:verify-wasm":"CALL_WASM_FETCH_MODE=pinned node ./scripts/fetch-wasm-resources.mjs"},"_npmUser":{"name":"japofc","email":"kielsahaz@gmail.com"},"repository":{"url":"git+https://github.com/JAPofc/baileys.git","type":"git"},"_npmVersion":"11.17.0","description":"Feature-rich WhatsApp Multi-Device library for Node.js — interactive messages, native flows, polls, newsletters, VoIP, mini-apps and everyday bot utilities.","directories":{},"resolutions":{"tar":"^7.5.11","tmp":"^0.2.5","socks":"^2.8.8","flatted":"^3.4.2","basic-ftp":"^5.2.4","handlebars":"^4.7.9","ip-address":"^10.1.1","underscore":"^1.13.8","markdown-it":"^14.1.1","ajv@npm:^6.12.4":"^6.14.0","yaml@npm:^2.6.1":"^2.8.4","glob@npm:^10.2.2":"^10.5.0","glob@npm:^10.5.0":"^10.5.0","glob@npm:^10.3.10":"^10.5.0","js-yaml@npm:^4.1.0":"^4.1.1","js-yaml@npm:^3.13.1":"^3.14.2","minimatch@npm:^3.0.4":"^3.1.5","minimatch@npm:^3.1.2":"^3.1.5","minimatch@npm:^5.0.1":"^5.1.8","minimatch@npm:^9.0.4":"^9.0.9","minimatch@npm:^9.0.5":"^9.0.9","picomatch@npm:^2.0.4":"^2.3.2","picomatch@npm:^2.3.1":"^2.3.2","picomatch@npm:^4.0.0":"^4.0.4","picomatch@npm:^4.0.2":"^4.0.4","brace-expansion@npm:^1.1.7":"^1.1.13","brace-expansion@npm:^2.0.1":"^2.0.3"},"_nodeVersion":"26.3.1","dependencies":{"ws":"^8.22.0","jimp":"^1.6.1","long":"^5.3.2","pino":"^10.3.1","fflate":"^0.8.3","p-queue":"^9.3.3","libsignal":"^6.0.0","lru-cache":"^11.5.3","@hapi/boom":"^10.0.1","protobufjs":"^8.8.0","async-mutex":"^0.5.0","music-metadata":"^11.16.1","@adiwajshing/keyed-db":"^0.2.4","@cacheable/node-cache":"^3.0.1"},"_hasShrinkwrap":false,"packageManager":"npm@10.8.2","devDependencies":{"jsqr":"^1.4.0","typedoc":"^0.28.20","typescript":"6.0.x","@types/node":"^26.6.3"},"peerDependencies":{"pg":"^8.13.0","axios":"*","sharp":"*","mysql2":"^3.11.0","ioredis":">=5.4.1 <7","mongodb":">=6.10.0 <8","@roamhq/wrtc":"*","audio-decode":">=2.2.3 <4","ffmpeg-static":">=5.0.0","fluent-ffmpeg":"^2.1.3","@napi-rs/image":">=1.12.0 <2","better-sqlite3":">=11.0.0 <13","link-preview-js":">=3.0.0 <5","@ffmpeg-installer/ffmpeg":">=1.1.0"},"optionalDependencies":{"whatsapp-rust-bridge":"0.5.5"},"peerDependenciesMeta":{"pg":{"optional":true},"axios":{"optional":true},"sharp":{"optional":true},"mysql2":{"optional":true},"ioredis":{"optional":true},"mongodb":{"optional":true},"@roamhq/wrtc":{"optional":true},"audio-decode":{"optional":true},"ffmpeg-static":{"optional":true},"fluent-ffmpeg":{"optional":true},"@napi-rs/image":{"optional":true},"better-sqlite3":{"optional":true},"link-preview-js":{"optional":true},"@ffmpeg-installer/ffmpeg":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/baileys_2.4.7-new_1790894395926_0.1453302283831841","host":"s3://npm-registry-packages-npm-production"}},"2.4.8":{"_id":"@japofc/baileys@2.4.8","bin":{"japofc-baileys":"lib/cli.js"},"bugs":{"url":"https://github.com/JAPofc/baileys/issues"},"dist":{"shasum":"35590acf2952fe05158e1d3958fce063bd2ed889","tarball":"https://registry.npmjs.org/@japofc/baileys/-/baileys-2.4.8.tgz","fileCount":659,"integrity":"sha512-kXYL3hxyYQXk7ADqNCi8hW5WaVFPE8jtXwPWtpwYGK66GsGM6u1fpcaAAckLgRBgsV5vZEIWLxbgWjERoK14XA==","signatures":[{"sig":"MEQCICarxOmFmXn/VGbYB/2NYTrXNIIWvnOoI7yK+74ahXEsAiAL99rFH4mVPkD4NwxItiHWankNg1NoAMrK8ZMnPE2Nbg==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIFFPJbSEhMhlwp1r71cwn2QRY42bhpyxHmdqMuc6HXWyAiEAlz6peua46q2bhnWTMiTg2wftfEcGDLpVcrSv/aqdcHg="}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@japofc%2fbaileys@2.4.8","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":26597999},"main":"./lib/index.js","name":"@japofc/baileys","type":"module","types":"./lib/index.d.ts","author":{"name":"JAPofc"},"module":"./lib/index.js","engines":{"node":">=20.0.0"},"exports":{".":{"types":"./lib/index.d.ts","import":"./lib/index.js","default":"./lib/index.js"},"./lib/*":{"types":"./lib/*.d.ts","import":"./lib/*.js","default":"./lib/*.js"},"./WAProto":{"types":"./WAProto/index.d.ts","import":"./WAProto/index.js","default":"./WAProto/index.js"},"./lib/*.js":{"types":"./lib/*.d.ts","import":"./lib/*.js","default":"./lib/*.js"},"./WAProto/*":{"types":"./WAProto/*.d.ts","import":"./WAProto/*.js","default":"./WAProto/*.js"},"./WAProto/*.js":{"types":"./WAProto/*.d.ts","import":"./WAProto/*.js","default":"./WAProto/*.js"},"./package.json":"./package.json"},"gitHead":"e8f5e26e6ae89d7714fa51e266b9a35e0da86568","license":"GPL-3.0-or-later","scripts":{"test":"node --test","wa:check":"node lib/cli.js wa","test:types":"tsc -p tests/tscheck/tsconfig.json","release:check":"npm test && npm run test:types && npm audit && npm pack --dry-run","voip:fetch-wasm":"node --experimental-websocket ./scripts/fetch-wasm-resources.mjs","capture:protocol":"node examples/protocol-capture-bot.js","voip:verify-wasm":"CALL_WASM_FETCH_MODE=pinned node ./scripts/fetch-wasm-resources.mjs"},"version":"2.4.8","_npmUser":{"name":"japofc","email":"kielsahaz@gmail.com"},"homepage":"https://github.com/JAPofc/baileys#readme","keywords":["anti-ban","automation","baileys","baileys-api","baileys-bot","baileys-esm","baileys-fork","baileys-fork-jap","baileys-javascript","baileys-js","baileys-library","baileys-md","baileys-multi-device","baileys-multidevice","baileys-node","baileys-nodejs","baileys-whatsapp","baileys-whatsapp-api","baileys-whatsapp-bot","bot-framework","buttons","chatbot","group-management","interactive-messages","jap","jap-baileys","jap-baileys-md","jap-whatsapp","japbaileys","japofc","multi-device","newsletter","sticker","termux","voip","whatsapp","whatsapp-api","whatsapp-api-baileys","whatsapp-automation","whatsapp-baileys","whatsapp-bot","whatsapp-bot-baileys","whatsapp-multi-device","whatsapp-web","whatsapp-web-baileys"],"repository":{"url":"git+https://github.com/JAPofc/baileys.git","type":"git"},"_npmVersion":"10.9.9","description":"Feature-rich WhatsApp Multi-Device library for Node.js — interactive messages, native flows, polls, newsletters, VoIP, mini-apps and everyday bot utilities.","directories":{},"maintainers":[{"name":"japofc","email":"kielsahaz@gmail.com"}],"resolutions":{"tar":"^7.5.11","tmp":"^0.2.5","socks":"^2.8.8","flatted":"^3.4.2","basic-ftp":"^5.2.4","handlebars":"^4.7.9","ip-address":"^10.1.1","underscore":"^1.13.8","markdown-it":"^14.1.1","ajv@npm:^6.12.4":"^6.14.0","yaml@npm:^2.6.1":"^2.8.4","glob@npm:^10.2.2":"^10.5.0","glob@npm:^10.5.0":"^10.5.0","glob@npm:^10.3.10":"^10.5.0","js-yaml@npm:^4.1.0":"^4.1.1","js-yaml@npm:^3.13.1":"^3.14.2","minimatch@npm:^3.0.4":"^3.1.5","minimatch@npm:^3.1.2":"^3.1.5","minimatch@npm:^5.0.1":"^5.1.8","minimatch@npm:^9.0.4":"^9.0.9","minimatch@npm:^9.0.5":"^9.0.9","picomatch@npm:^2.0.4":"^2.3.2","picomatch@npm:^2.3.1":"^2.3.2","picomatch@npm:^4.0.0":"^4.0.4","picomatch@npm:^4.0.2":"^4.0.4","brace-expansion@npm:^1.1.7":"^1.1.13","brace-expansion@npm:^2.0.1":"^2.0.3"},"_nodeVersion":"22.23.4","dependencies":{"ws":"^8.22.0","jimp":"^1.6.1","long":"^5.3.2","fflate":"^0.8.3","p-queue":"^9.3.3","libsignal":"^6.0.0","lru-cache":"^11.5.3","@hapi/boom":"^10.0.1","protobufjs":"^8.8.0","async-mutex":"^0.5.0","music-metadata":"^11.16.1","@adiwajshing/keyed-db":"^0.2.4","@cacheable/node-cache":"^3.0.1"},"_hasShrinkwrap":false,"packageManager":"npm@10.8.2","devDependencies":{"jsqr":"^1.4.0","pino":"^10.3.1","typedoc":"^0.28.20","typescript":"6.0.x","@types/node":"^26.6.3"},"peerDependencies":{"pg":"^8.13.0","pino":"^8 || ^9 || ^10","axios":"*","sharp":">=0.35.5","mysql2":"^3.11.0","ioredis":">=5.4.1 <7","mongodb":">=6.10.0 <8","@roamhq/wrtc":"*","audio-decode":">=2.2.3 <4","ffmpeg-static":">=5.0.0","fluent-ffmpeg":"^2.1.3","@napi-rs/image":">=1.12.0 <2","better-sqlite3":">=11.0.0 <13","link-preview-js":">=3.0.0 <5","@ffmpeg-installer/ffmpeg":">=1.1.0"},"optionalDependencies":{"whatsapp-rust-bridge":"0.5.5"},"peerDependenciesMeta":{"pg":{"optional":true},"pino":{"optional":true},"axios":{"optional":true},"sharp":{"optional":true},"mysql2":{"optional":true},"ioredis":{"optional":true},"mongodb":{"optional":true},"@roamhq/wrtc":{"optional":true},"audio-decode":{"optional":true},"ffmpeg-static":{"optional":true},"fluent-ffmpeg":{"optional":true},"@napi-rs/image":{"optional":true},"better-sqlite3":{"optional":true},"link-preview-js":{"optional":true},"@ffmpeg-installer/ffmpeg":{"optional":true}},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/baileys_2.4.8_1794862059688_0.8171610600503504"}}},"time":{"created":"2026-09-11T07:47:48.693Z","modified":"2026-11-16T20:47:41.911Z","2.0.1":"2026-09-11T01:28:22.115Z","2.1.0":"2026-09-11T07:47:49.064Z","2.2.0":"2026-09-11T10:10:51.647Z","2.3.0":"2026-09-11T22:25:10.858Z","2.4.0":"2026-09-12T09:55:38.821Z","2.4.1":"2026-09-17T08:59:51.527Z","2.4.2":"2026-09-24T13:15:29.191Z","2.4.3":"2026-09-28T12:02:30.456Z","2.4.4":"2026-09-28T20:07:35.150Z","2.4.5":"2026-09-29T10:21:39.265Z","2.4.6":"2026-09-30T14:24:54.827Z","2.4.7":"2026-10-01T22:18:03.673Z","2.4.7-new":"2026-10-01T22:39:56.135Z","2.4.8":"2026-11-16T20:47:39.995Z"},"bugs":{"url":"https://github.com/JAPofc/baileys/issues"},"author":{"name":"JAPofc"},"license":"GPL-3.0-or-later","homepage":"https://github.com/JAPofc/baileys#readme","keywords":["anti-ban","automation","baileys","baileys-api","baileys-bot","baileys-esm","baileys-fork","baileys-fork-jap","baileys-javascript","baileys-js","baileys-library","baileys-md","baileys-multi-device","baileys-multidevice","baileys-node","baileys-nodejs","baileys-whatsapp","baileys-whatsapp-api","baileys-whatsapp-bot","bot-framework","buttons","chatbot","group-management","interactive-messages","jap","jap-baileys","jap-baileys-md","jap-whatsapp","japbaileys","japofc","multi-device","newsletter","sticker","termux","voip","whatsapp","whatsapp-api","whatsapp-api-baileys","whatsapp-automation","whatsapp-baileys","whatsapp-bot","whatsapp-bot-baileys","whatsapp-multi-device","whatsapp-web","whatsapp-web-baileys"],"repository":{"url":"git+https://github.com/JAPofc/baileys.git","type":"git"},"description":"Feature-rich WhatsApp Multi-Device library for Node.js — interactive messages, native flows, polls, newsletters, VoIP, mini-apps and everyday bot utilities.","maintainers":[{"name":"japofc","email":"kielsahaz@gmail.com"}],"readme":"<div align=\"center\" id=\"top\">\n\n<img src=\"./Media/japofc-logo.png\" width=\"140\" alt=\"JAPofc logo\" />\n\n# @japofc/baileys\n\n### ⚡ The maintained WhatsApp Web API for Node.js\n\n<em>Typed ESM&nbsp;·&nbsp;always-current WA&nbsp;Web versioning&nbsp;·&nbsp;protocol-safe tooling&nbsp;·&nbsp;140+ production bot utilities</em>\n\n<br/>\n\n<!-- identity -->\n<p>\n<a href=\"https://www.npmjs.com/package/@japofc/baileys\"><img src=\"https://img.shields.io/npm/v/@japofc/baileys?color=25D366&label=npm&logo=npm&logoColor=white&style=for-the-badge\" alt=\"npm version\" /></a>\n<a href=\"https://www.npmjs.com/package/@japofc/baileys\"><img src=\"https://img.shields.io/npm/dt/@japofc/baileys?color=128C7E&label=downloads&logo=npm&logoColor=white&style=for-the-badge\" alt=\"npm downloads\" /></a>\n<a href=\"./LICENSE\"><img src=\"https://img.shields.io/badge/license-GPL--3.0--or--later-555?style=for-the-badge\" alt=\"GPL-3.0-or-later license\" /></a>\n</p>\n\n<!-- quality -->\n<p>\n<img src=\"https://img.shields.io/badge/node-%E2%89%A5%2020-3C873A?style=flat-square&logo=node.js&logoColor=white\" alt=\"Node >=20\" />\n<img src=\"https://img.shields.io/badge/module-ESM-F7DF1E?style=flat-square&logo=javascript&logoColor=black\" alt=\"ESM only\" />\n<img src=\"https://img.shields.io/badge/types-bundled%20.d.ts-3178C6?style=flat-square&logo=typescript&logoColor=white\" alt=\"TypeScript types\" />\n<img src=\"https://img.shields.io/badge/tests-1804%20passing-2ecc71?style=flat-square&logo=nodedotjs&logoColor=white\" alt=\"tests passing\" />\n<img src=\"https://img.shields.io/badge/audit-0%20vulnerabilities-2ecc71?style=flat-square&logo=npm&logoColor=white\" alt=\"npm audit clean\" />\n</p>\n\n<p>\n<a href=\"https://whatsapp.com/channel/0029VbEVFrILtOjAOu4FXa3r\"><img src=\"https://img.shields.io/badge/Follow%20on%20WhatsApp-JAPofc%20Channel-25D366?style=for-the-badge&logo=whatsapp&logoColor=white\" alt=\"JAPofc WhatsApp Channel\" /></a>\n</p>\n\n<h4>\n\n[📦 Install](#install)&nbsp;·&nbsp;[🚀 Quick start](#quick-start)&nbsp;·&nbsp;[🔥 Features](#-features)&nbsp;·&nbsp;[💡 Examples](#-usage-examples)&nbsp;·&nbsp;[📘 TypeScript](#-typescript-support)&nbsp;·&nbsp;[❓ FAQ](#-faq--troubleshooting)&nbsp;·&nbsp;[🇮🇩 Bahasa Indonesia](./README.id.md)\n\n</h4>\n\n</div>\n\n---\n\n<table>\n<tr>\n<td width=\"33%\" valign=\"top\" align=\"center\">\n\n### 🔌 Reliable core\n\nPredictable socket, auto WA-Web version resolution, reconnect + anti-ban toolkit — **no hidden side effects**.\n\n</td>\n<td width=\"33%\" valign=\"top\" align=\"center\">\n\n### 🧩 Batteries included\n\nButtons, native flows, carousel, AIRich cards, polls, channels, VoIP, and **140+ bot utilities**.\n\n</td>\n<td width=\"33%\" valign=\"top\" align=\"center\">\n\n### 🛡️ Production-ready\n\nBundled `.d.ts`, multi-backend auth, credential redaction, session tools — **1804 tests, 0 vulns**.\n\n</td>\n</tr>\n</table>\n\n<details>\n<summary><b>📑 Table of contents</b> — click to expand</summary>\n\n<br/>\n\n> **Getting started** &nbsp;›&nbsp; [Install](#install) · [Quick start](#quick-start) · [Overview](#overview) · [Installation](#-installation) · [Authentication](#-authentication) · [Store backends](#️-store-backends)\n>\n> **What's inside** &nbsp;›&nbsp; [Comparison](#-comparison) · [Built with](#-built-with) · [Features](#-features) · [Exclusive J.AP enhancements](#-exclusive-jap-enhancements) · [New in v2.4.5](#-new-in-v245)\n>\n> **Messaging** &nbsp;›&nbsp; [Usage examples](#-usage-examples) · [Message helpers](#-message-helpers) · [Channels, history & transcripts](#-channels-history--transcripts) · [WA 2026 catch-up](#-wa-2026-catch-up)\n>\n> **Calls & sync** &nbsp;›&nbsp; [Voice & video calls](#-voice--video-calls) · [User sync queries](#-user-sync-queries) · [Username management](#-username-management)\n>\n> **Toolkit** &nbsp;›&nbsp; [Everyday utilities](#-everyday-utilities) · [Security pack](#-security-pack) · [Bot framework](#-bot-framework) · [Utility modules](#-utility-modules)\n>\n> **Reference** &nbsp;›&nbsp; [Recommended environment](#-recommended-environment) · [TypeScript support](#-typescript-support) · [FAQ & troubleshooting](#-faq--troubleshooting) · [Contributing](#-contributing) · [Credits](#-credits) · [Maintainer](#-maintainer)\n\n</details>\n\n---\n\n## Install\n\n```bash\nnpm i @japofc/baileys\n```\n\nNode.js 20+ is required. The package is ESM-only and has no install/postinstall scripts.\n\n## Quick start\n\n```js\nimport makeWASocket, { useMultiFileAuthState } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useMultiFileAuthState('auth_info')\nconst sock = makeWASocket({ auth: state, printQRInTerminal: true })\n\nsock.ev.on('creds.update', saveCreds)\nsock.ev.on('messages.upsert', async ({ messages }) => {\n  const msg = messages[0]\n  if (!msg?.message || msg.key.fromMe) return\n  await sock.sendMessage(msg.key.remoteJid, { text: 'pong' }, { quoted: msg })\n})\n```\n\n## Overview\n\n`@japofc/baileys` is a production-oriented WhatsApp Web library for bot builders who need predictable socket behavior, complete TypeScript declarations, and maintained utilities without hidden side effects.\n\n- Current WA Web fallback version plus `makeWASocketAuto()` for live version resolution.\n- Full WAProto declarations and deep package exports for installed-package consumers.\n- Auth backends for files, SQLite, Redis, MongoDB, MySQL, and PostgreSQL.\n- Interactive messages, native flows, carousel, AIRich cards, channels/newsletters, status helpers, and bot modules.\n- Hardened media/link fetching, credential redaction, session tools, reconnect helpers, and protocol-capture tooling.\n- **No implicit group/channel join or follow.** Join/follow helpers remain available, but they only run when your code explicitly calls them.\n\n---\n\n## 🆚 Comparison\n\nHow `@japofc/baileys` stacks up against other Baileys libraries:\n\n| Capability | `@japofc/baileys` | Other forks (typical) |\n|---|:---:|:---:|\n| Native Flow buttons (V1/V2/V3) | ✅ | ⚠️ partial |\n| Carousel messages | ✅ | ❌ |\n| Rich response cards (AIRich) | ✅ | ❌ |\n| Commerce flow (catalog/order/payment) | ✅ | ⚠️ partial |\n| Voice calling (VoIP) | ✅ experimental | ❌ |\n| Multi-backend store (SQL/Mongo/Redis) | ✅ | ⚠️ partial |\n| Full `.d.ts` TypeScript definitions | ✅ | ⚠️ partial |\n| User sync queries (WAUSync) | ✅ | ✅ |\n| Username management (check/set/pin/recommend) | ✅ | ❌ |\n| Bot framework (middleware, session, stats) | ✅ | ❌ |\n| Built-in QR render (terminal/SVG/PNG, zero deps) | ✅ | ❌ needs `qrcode-terminal` |\n| Auto WA Web version resolution | ✅ | ❌ hardcoded |\n| Status mentions (notify users/groups of your status) | ✅ | ❌ |\n| Anti-ban toolkit (warmup ramps, group-op ceilings, disconnect classifier, Gaussian jitter) | ✅ | ❌ |\n| Crash-message shield (mention bombs, zalgo, RTLO spoofing) | ✅ | ❌ |\n| Session doctor + portable/encrypted session strings | ✅ | ❌ |\n| Community/bot modules (economy, games, rental, moderation — 140+ utils) | ✅ | ❌ |\n| Sticker EXIF branding | ✅ pure JS | ⚠️ needs `node-webpmux` |\n| CLI (`doctor` / `session` / `sticker` / `export` / `wa`) | ✅ | ❌ |\n| Credential-redacting logger | ✅ | ❌ |\n\n> This table describes package-level features, not performance benchmarks. PRs to update or correct it are welcome via [Contributing](#-contributing).\n\n---\n\n## 🧰 Built With\n\n<p>\n<img src=\"https://img.shields.io/badge/node.js-%2343853D.svg?style=for-the-badge&logo=node.js&logoColor=white\" alt=\"Node.js\"/>\n<img src=\"https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E\" alt=\"JavaScript\"/>\n<img src=\"https://img.shields.io/badge/esm-%23F7DF1E.svg?style=for-the-badge&logo=javascript&logoColor=black\" alt=\"ESM\"/>\n<img src=\"https://img.shields.io/badge/websocket-%23000000.svg?style=for-the-badge&logo=socket.io&logoColor=white\" alt=\"WebSocket\"/>\n<img src=\"https://img.shields.io/badge/signal%20protocol-%233A76F0.svg?style=for-the-badge&logo=signal&logoColor=white\" alt=\"Signal Protocol\"/>\n<img src=\"https://img.shields.io/badge/protobuf-%23345?style=for-the-badge&logo=google&logoColor=white\" alt=\"Protobuf\"/>\n<img src=\"https://img.shields.io/badge/npm-%23CB3837.svg?style=for-the-badge&logo=npm&logoColor=white\" alt=\"npm\"/>\n</p>\n\n<p>\n<a href=\"https://skillicons.dev\">\n  <img src=\"https://skillicons.dev/icons?i=nodejs,js,ts,npm,docker,redis,mongodb,mysql,postgresql,sqlite\" alt=\"Tech stack icons\"/>\n</a>\n</p>\n\n---\n\n## 🔥 Features\n\n<table>\n<tr>\n<th align=\"center\">💬 Interactive Messages</th>\n<th align=\"center\">🛒 Commerce & Business</th>\n<th align=\"center\">🧩 Utility Features</th>\n</tr>\n<tr>\n<td valign=\"top\">\n\n- Native Flow\n- Buttons (V1 / V2 / V3)\n- Lists\n- Carousel Messages\n- Poll & Quiz Messages\n- Rich Response Messages (AIRich)\n- HTML cards (experimental)\n- CTA / Reply / URL Buttons\n- Call Buttons\n- OTP Buttons\n- Authentication Buttons\n\n</td>\n<td valign=\"top\">\n\n- Catalog Message\n- Order Details\n- Order Status\n- Review & Pay\n- Payment Status\n- Payment Method\n- Track Order\n- Reorder\n- Cancel Order\n\n</td>\n<td valign=\"top\">\n\n- Group Status Support\n- Mention All\n- Lottie Sticker Support\n- Newsletter Support\n- ExternalAdReply Helper\n- View Once Support\n- Rich Formatting\n- Code Highlighting\n\n</td>\n</tr>\n</table>\n\n<table>\n<tr>\n<th align=\"center\">🔐 Auth & Storage</th>\n<th align=\"center\">📞 Realtime</th>\n<th align=\"center\">🛠 Developer Tooling</th>\n</tr>\n<tr>\n<td valign=\"top\">\n\n- Multi-file auth state\n- Single-file auth state\n- SQLite auth state\n- Cache-manager auth state\n- In-memory store\n- SQLite / MongoDB / MySQL /\n  PostgreSQL / Redis store adapters\n\n</td>\n<td valign=\"top\">\n\n- Voice calling (VoIP, WASM engine)\n- User sync queries (WAUSync)\n- Presence / status / device lookup\n- Event buffer for high-volume bots\n\n</td>\n<td valign=\"top\">\n\n- Full TypeScript definitions (`.d.ts`)\n- Anti-delete & anti-edit detection (recover deleted messages, capture pre-edit content)\n- Message search helpers\n- Auto-reply engine\n- Scheduling helpers\n- Message retry manager\n\n</td>\n</tr>\n</table>\n\n---\n\n## ✨ Exclusive J.AP Enhancements\n\n### Audio Group Status Fix\nAudio status uses a more compatible implementation to avoid unsupported-version errors on older WhatsApp clients.\n\n### AIRich — the rich-response message builder\nA chainable builder (`AIRich`, also exported as `AIJap` / `LeafRich` / `JapAI` / `JapRich`) with 40+ `add*()`/`set*()` methods covering headings, formatted text (hyperlinks/citations/LaTeX), code blocks, tables, image/video/product/post cards, task & progress cards, tip banners, and quick-reply suggestions — the kind of rich card layout you'd normally only see from an official AI/assistant-style bot. See [Usage Examples](#airich--rich-response-cards) below.\n\n### Interactive buttons\n\n`sendMessage()` routes interactive content through the handler set, so all of these send\nas the message type they name — no extra helper, no manual `relayMessage`:\n\n```ts\n// native-flow shorthands: id = quick_reply, url = cta_url, copy = cta_copy,\n// call = cta_call, sections = single_select, webview, flow, catalog, … (~30 of them)\nawait sock.sendMessage(jid, {\n    text: 'Pick one',\n    footer: 'powered by JAP',\n    nativeFlow: [\n        { text: 'Yes', id: '.yes' },\n        { text: 'Open', url: 'https://example.com' },\n        { text: 'Copy code', copy: 'JAP2026' }\n    ]\n})\n\n// or hand-built native-flow buttons, for anything the shorthands do not cover\nawait sock.sendMessage(jid, {\n    text: 'Do you agree?',\n    title: 'Confirmation',\n    interactiveButtons: [\n        { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: 'Yes', id: '.yes' }) }\n    ]\n})\n```\n\nThe same path handles `interactiveMessage`, carousels, `requestPaymentMessage`,\n`productMessage`, `groupInviteMessage`, `eventMessage`, `pollResultMessage` and\n`groupStatusMessage`. Each returns a normal `WAMessage` and is emitted on\n`messages.upsert` like any other send. Pass `{ disableJapyea: true }` in the options to\nforce the core message builder instead.\n\nA button shape that matches no shorthand is now **rejected with an error** rather than\nsent as an invisible empty button, so a typo fails loudly at send time.\n\n### Knowing when an app-state sync was only partial\n\n`decodePatches()` no longer pretends a collection is synced when one of its patches could\nnot be applied. The state it returns is the last patch that actually applied **and**\nverified, and the failure is reported instead of swallowed:\n\n```js\nconst { state, mutationMap, incomplete, synced } = await decodePatches(/* … */)\n\nif (!synced) {\n    // incomplete = { version, reason: 'decode-failed' | 'lthash-mismatch', error? }\n    console.warn(`app state stopped at v${state.version}, patch v${incomplete.version} failed`)\n}\n```\n\nPersist `state` as usual — because it never runs ahead of the mutations it actually\ndelivered, the next resync re-fetches the missing patches instead of skipping them. The\nsocket does this for you: an incomplete sync is retried with a full snapshot, the same way\na thrown sync error already was.\n\n### Telling fatal disconnects apart\n\nNot every close deserves a reconnect. `classifyDisconnect()` labels each one and\n`autoReconnect()` acts on it:\n\n| close | what happens |\n| --- | --- |\n| `connectionReplaced` (440) | **stops** — another process owns this session; reconnecting starts a kick-war |\n| `forbidden` (403) | **stops** — the number is restricted; retrying can escalate it |\n| `multideviceMismatch` (411) | **stops** — re-pair required |\n| `loggedOut` (401) | **stops** — credentials are dead |\n| `badSession` (500) | retries, and only stops after **3 in a row** (`badSessionStreak`) |\n| `connectionLost`, `timedOut`, `restartRequired`, … | retries with backoff, as before |\n\n```ts\nconst manager = autoReconnect(() => makeWASocket({ auth: state }), {\n    badSessionStreak: 3, // default\n    onFatal: ({ verdict, message, badSessions }) => {\n        console.error(message) // \"⚔️ [conflict 440] … ↳ FATAL: STOP this process. …\"\n        if (verdict.category === 'auth') void wipeAuthFolder()\n    }\n})\n```\n\n`explainDisconnect(code)` gives the same one-liner for any code, and\n`explainDisconnect(code, { streak: 2 })` reports `2/3 in a row — retrying` instead of\ndeclaring a corrupt session on the first bad decrypt. Set `reconnectOnFatal: true` to opt\nback into the old always-retry behaviour.\n\n### Fetching from your own intranet\n\nThe SSRF guard that protects link previews and `getHttpStream()` rejects loopback,\nprivate, link-local and cloud-metadata addresses — including IPv4-mapped IPv6 such as\n`[::ffff:169.254.169.254]`. To reach one specific internal host, exempt just that host\ninstead of disabling the guard:\n\n```ts\nawait assertSafeHttpUrl(url, { allowHosts: ['media.lan', '127.0.0.1'] })\n```\n\n`allowPrivate: true` still exists, but it switches the check off for *every* host — prefer\n`allowHosts` when the URL can come from anywhere.\n\n### Checking a rate limit without spending it\n\n`createRateLimiter()` (used by `withPairingGuard`) can be asked for a verdict without\nconsuming anything:\n\n```ts\nconst { allowed, retryAfterMs } = limiter.peek(phoneNumber)\nif (!allowed) {\n    console.log(`try again in ${Math.ceil(retryAfterMs / 1000)}s`)\n}\n\nconsole.log(`${limiter.remaining(phoneNumber)} pairing attempts left this hour`)\n```\n\n`peek()` leaves both the window and `stats` untouched — only `check()` spends a slot. The\npairing guard uses exactly this, so a request it refuses no longer costs you budget.\n\n### Keeping a persistent store bounded\n\n`maxMessagesPerChat` only caps what is hydrated into memory — the backend keeps every\nmessage that was ever written through. Trim it yourself:\n\n```ts\nconst stored = await store.countStoredMessages(jid) // what is really on disk\nconst removed = await store.pruneStoredMessages(jid, 5_000) // keep the newest 5k\n```\n\n`pruneStoredMessages()` deletes oldest-first and returns how many rows went; `keep: 0`\nclears the chat. The in-memory view is untouched (it is already capped).\n\n### Which ffmpeg am I using?\n\n```ts\nimport { inspectFfmpegPath, setFfmpegPath } from '@japofc/baileys'\n\nconst { path, source, rejected } = await inspectFfmpegPath()\nconsole.log(path, 'via', source) // e.g. '/usr/bin/ffmpeg via PATH'\nfor (const r of rejected) {\n    console.warn(`skipped ${r.source} \"${r.path}\": ${r.problem}`)\n}\n```\n\nA candidate is only accepted if it is an executable regular file, so a path that lost its\n`+x` bit — or a typo in `FFMPEG_PATH` — is skipped instead of being handed to `spawn()`,\nand auto-detection carries on to `ffmpeg-static` / the system binary. `rejected` tells you\nexactly what was passed over and why.\n\n### Waiting for an event\n\n`waitForEvent` awaits the next matching event and detaches its listener on every exit path\n— resolve, timeout, abort, or a throwing predicate — so the usual \"do something, then wait\nfor the confirming event\" pattern stops leaking listeners.\n\n```ts\nimport { waitForEvent } from '@japofc/baileys'\n\n// wait for the metadata of one specific group\nconst update = await waitForEvent(sock.ev, 'groups.update', {\n    pick: updates => updates.find(u => u.id === groupJid), // undefined keeps waiting\n    timeoutMs: 10_000\n})\n\n// or keep the whole payload, with an abort signal instead of a timeout\nconst upsert = await waitForEvent(sock.ev, 'messages.upsert', {\n    filter: up => up.type === 'notify',\n    timeoutMs: 0,\n    signal: controller.signal\n})\n```\n\n`timeoutMs` defaults to 30 s; `0` or a negative value disables it. Remember that buffered\nevents arrive consolidated, so the payload is whatever the flush produced — that is what\n`pick` is for.\n\n### HTML cards — experimental\n\nWhatsApp's rich-response surface also carries an **unshipped** primitive that renders a full\nHTML/CSS/JS document inside the chat card, in the client's own sandboxed webview. Its\ninternal typename is `FOAHtmlPrimitiveDemoDONOTUSE` — the `DemoDONOTUSE` suffix is\nWhatsApp's own feature-flag naming, not a warning from this library.\n\n```js\nawait sock.sendMessage(jid, {\n    html: `<!doctype html><html><head><style>\n      body { background:#111b21; color:#e9edef; font-family:system-ui; text-align:center; padding:24px }\n      button { background:#00a884; color:#0b141a; border:0; border-radius:10px; padding:12px 24px; font-weight:bold }\n    </style></head><body>\n      <h2>Mini Clicker</h2><div id=\"n\" style=\"font-size:36px\">0</div>\n      <button onclick=\"document.getElementById('n').textContent = ++c\">TAP ME</button>\n      <script>let c = 0</script>\n    </body></html>`\n})\n```\n\n- Several cards at once: `{ html: [docA, docB] }`.\n- Mix it with the other primitives: `{ richResponse: [{ text: 'play:' }, { html: doc }] }`.\n- Allow-list origins the document may reach with `{ html: doc, trustedSources: ['https://example.com'] }`.\n- Socket-free helpers: `assessHtmlCard(html)` / `assertHtmlCard(html)` (non-empty string, 256 KiB\n  default ceiling, byte-accurate), plus `buildHtmlPrimitiveSection()` and\n  `buildHtmlUnifiedResponse()` if you assemble the payload yourself.\n\n> **Treat this as experimental.** It is not a documented, stable message type: rendering\n> depends on the recipient's client build and may disappear without notice. Markup is sent\n> verbatim — never interpolate untrusted input into it.\n\n### Native Flow Expansion\n\nEvery shorthand below is a key you put on a button object in `nativeFlow: [...]`; the\nright-hand column is the native-flow `name` that goes on the wire. `text` sets the label\non all of them, `icon` is optional.\n\n| shorthand | native-flow name | | shorthand | native-flow name |\n| --- | --- | --- | --- | --- |\n| `id` | `quick_reply` | | `card` | `card_message` |\n| `reply` | `quick_reply` | | `orderDetails` | `order_details` |\n| `url` (or `urlBtn`) | `cta_url` | | `orderStatus` | `order_status` |\n| `copy` | `cta_copy` | | `reviewAndPay` | `review_and_pay` |\n| `call` (or `phoneNumber`) | `cta_call` | | `paymentStatus` | `payment_status` |\n| `sections` | `single_select` | | `paymentMethod` | `payment_method` |\n| `webview` / `openWebview` | `open_webview` | | `trackOrder` | `track_order` |\n| `reminder` | `cta_reminder` | | `reorder` | `reorder` |\n| `cancelReminder` | `cta_cancel_reminder` | | `cancelOrder` | `cancel_order` |\n| `address` | `address_message` | | `clearChat: true` | `clear_chat` |\n| `location: true` | `send_location` | | `screen` | `navigateToScreen` |\n| `catalog` | `catalog_message` | | `flow` | `flow` |\n| `products` | `mpm` | | `voiceCall` / `videoCall` | `voice_call` / `video_call_button` |\n\n```js\nawait sock.sendMessage(jid, {\n    text: 'Order #1234',\n    nativeFlow: [\n        { text: 'Track', trackOrder: 'ORD-1234' },\n        { text: 'Open app', webview: { url: 'https://shop.example/track', inAppWebview: true } },\n        { text: 'Menu', sections: [{ title: 'Help', rows: [{ title: 'Contact us', id: '.cs' }] }] }\n    ]\n})\n```\n\n**`open_webview` is a real in-app WebView button** and is its own native-flow name — it is\nnot the same thing as `cta_url`'s `webview_interaction` flag, which modern WhatsApp clients\nignore. Pass a url string or `{ url, title?, inAppWebview? }`.\n\n**Not supported, on purpose:** `otp_button` / `authentication_button` are WhatsApp Business\nPlatform (Cloud API) template buttons gated behind Meta template approval — no MD-protocol\nlibrary can produce them. The old `call_button` / `url_button` / `reply_button` names come\nfrom the deprecated `buttonsMessage` system and are silently ignored by current clients;\n`phoneNumber`, `urlBtn` and `reply` above are their working equivalents. Commerce buttons\n(`card_message`, `order_*`, `review_and_pay`, `payment_*`) only render when the ids resolve\nto a real Commerce order on your catalog/business account; `flow` needs a published Flow ID.\n\n### System Notification Filter\n\nMessages include:\n\n```js\nmessage.isSystemNotification\n```\n\nUseful for filtering:\n\n- E2E notices\n- Meta service notices\n- Other system-generated messages\n\n---\n\n## 📦 Installation\n\n```bash\nnpm install @japofc/baileys\n```\n\nDirectly from GitHub:\n\n```bash\nnpm install github:JAPofc/baileys\n```\n\n> Requires **Node.js 20+** — enforced at import time with a clear error (no install scripts: this package deliberately ships **zero** `preinstall`/`postinstall` hooks, so `npm ci --ignore-scripts` and strict supply-chain policies work out of the box).\n\n> **Coming from `@whiskeysockets/baileys`?** Migration is usually a one-line import change — see [MIGRATION.md](./MIGRATION.md).\n\n### Optional peer dependencies\n\nEverything below is **optional** — the socket works without any of them. Install only what the features you use need; missing ones fail with a clear install hint instead of a silent crash.\n\n| Package | Compatible versions | Unlocks |\n|---|---|---|\n| `sharp` | any | Fast image resizing/processing (used by the message builders' `Toolkit.resize`) |\n| `@napi-rs/image` | `~1.12.x` | Lighter native alternative to `sharp` for image ops |\n| `jimp` | bundled (`^1.6.x`) | Pure-JS image fallback when neither of the above is installed — ships as a regular dependency, nothing to install |\n| `fluent-ffmpeg` | `^2.1.3` | Audio/video conversion for media messages |\n| `ffmpeg-static` | `>=5.0.0` | Bundled ffmpeg **binary** — auto-detected, zero config (~80MB; not available for Termux/Android, use `pkg install ffmpeg` there) |\n| `@ffmpeg-installer/ffmpeg` | `>=1.1.0` | Alternative bundled ffmpeg binary — also auto-detected |\n| `audio-decode` | `^2.2.3` | Audio waveform/duration extraction (voice notes, VoIP capture) |\n| `link-preview-js` | `^3.x` | Rich link previews for URLs in outgoing text messages |\n| `better-sqlite3` | `^11.x` (Node 20 ABI) | SQLite auth state, SQLite store adapter, **and** the [Bot Framework](#-bot-framework)'s `SQLiteStore`/`StatsManager` |\n| `mongodb` | `^6.10+` | MongoDB store adapter |\n| `mysql2` | `^3.11+` | MySQL store adapter |\n| `pg` | `^8.13+` | PostgreSQL store adapter |\n| `ioredis` | `^5.4+` | Redis store adapter |\n| `@roamhq/wrtc` | any (platform-dependent native bindings) | Native WebRTC bindings for [voice calling](#-voice--video-calls) |\n| `axios` | any (optional) | Fallback HTTP client for URL thumbnails in button messages — **not required**: the built-in `fetch` (Node 18+) is used first |\n\nThe version column mirrors this package's `peerDependencies` ranges — those are the ranges the test suite runs against. Newer majors usually work but aren't verified; `npm ls <pkg>` + `printEnvironmentReport()` (below) will tell you what you actually have.\n\n#### ffmpeg: how it's found\n\nEvery feature that shells out to ffmpeg (video thumbnails, sticker conversion, voice-note conversion, VoIP audio feeding) resolves the binary through one central resolver, in this order:\n\n1. **Your override** — `setFfmpegPath('/path/to/ffmpeg')` (exported from the package) or the `FFMPEG_PATH` env var\n2. **`ffmpeg-static`** — if installed, its bundled binary is used automatically\n3. **`@ffmpeg-installer/ffmpeg`** — same, as an alternative\n4. **System `ffmpeg`** on your `PATH`\n\nSo on a normal server you can just `npm i ffmpeg-static` and never think about it. On **Termux/Android** (where neither npm package ships a binary) install the system one instead — it's picked up automatically:\n\n```sh\npkg install ffmpeg\n```\n\nIf nothing is found, the feature fails with a per-platform install hint instead of a cryptic `spawn ffmpeg ENOENT`.\n\n#### Check your environment (doctor)\n\nWondering why some feature doesn't work? One call diagnoses everything — Node version, which optional deps are installed, where ffmpeg was found, the active image backend:\n\n```js\nimport { printEnvironmentReport } from '@japofc/baileys'\nawait printEnvironmentReport() // prints a full report + returns the snapshot\n// or the raw-data version without printing:\nimport { checkEnvironment } from '@japofc/baileys'\nconst env = await checkEnvironment() // { ok, platform, node, ffmpeg, imageBackend, optionalDeps, warnings }\n```\n\nOr straight from the terminal, no code needed:\n\n```sh\nnpx @japofc/baileys doctor    # exit code 0 = all good, 1 = warnings\nnpx @japofc/baileys version\nnpx @japofc/baileys export dump.json --format csv --out chat.csv   # WAMessage JSON → transcript\n```\n\n---\n\n## 🚀 Quick Start\n\n```js\nimport { makeWASocketAuto, useMultiFileAuthState } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useMultiFileAuthState('auth_info')\n\n// makeWASocketAuto resolves the freshest WA Web version before connecting\n// (WA sw.js -> fork -> fallback), preventing stale-version pairing 405s.\n// Prefer sync? `makeWASocket({ auth: state })` still works exactly as before.\nconst sock = await makeWASocketAuto({\n    auth: state\n})\n\n// persist credentials whenever Baileys updates them\nsock.ev.on('creds.update', saveCreds)\n\nsock.ev.on('connection.update', (update) => {\n    const { connection, qr } = update\n\n    // Easiest: pass `printQRInTerminal: true` to makeWASocket and the QR is\n    // drawn automatically with the built-in zero-dependency renderer.\n    // Manual/custom rendering from the event also works:\n    //   import { renderQRToTerminal, qrToSVG, qrToPNG } from '@japofc/baileys'\n    //   if (qr) console.log(renderQRToTerminal(qr))          // terminal (▀▄█)\n    //   if (qr) fs.writeFileSync('qr.svg', qrToSVG(qr))      // for a web UI\n    //   if (qr) fs.writeFileSync('qr.png', qrToPNG(qr))      // raster (send anywhere)\n    if (qr) console.log('Got a pairing QR')\n\n    if (connection === 'open') console.log('🍃 Connected!')\n})\n\nsock.ev.on('messages.upsert', ({ messages }) => {\n    const msg = messages[0]\n    if (!msg.message || msg.key.fromMe) return\n    console.log('New message from', msg.key.remoteJid)\n})\n```\n\n**Production tip** — wrap the socket in `autoReconnect()` and disconnect handling is done for you (exponential backoff, never reconnects on `loggedOut`, immediate reconnect after pairing):\n\n```js\nimport { makeWASocketAuto, autoReconnect, useMultiFileAuthState } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useMultiFileAuthState('auth_info')\nconst manager = autoReconnect(() => makeWASocketAuto({ auth: state, printQRInTerminal: true }), {\n    onSocket: sock => {\n        sock.ev.on('creds.update', saveCreds)\n        sock.ev.on('messages.upsert', handler) // re-attached on every reconnect\n    },\n    onLoggedOut: () => console.log('delete auth_info/ and re-pair'),\n})\nawait manager.start()\n```\n\nFull runnable version: [`examples/auto-reconnect-bot.js`](./examples/auto-reconnect-bot.js).\n\n**Observability** — attach `createDebugMonitor()` for a safe, structured snapshot\n(connection state, disconnect reason, uptime, message latency percentiles, send-retry\ncounts, Signal error tallies, VoIP/WASM state, memory). It **never** contains QR\npayloads, pairing codes, auth keys, tokens, or private keys — the whole snapshot is\npassed through `redactSecrets()` before it is returned, so it's safe to log or attach\nto bug reports as-is:\n\n```js\nimport { createDebugMonitor } from '@japofc/baileys'\n\nconst monitor = createDebugMonitor(sock)\n// later — in a health endpoint, cron log, or crash handler:\nconsole.log(JSON.stringify(monitor.getDebugInfo(), null, 2))\n// { connection: { state, uptimeMs, lastDisconnect: { code, reason } },\n//   messages: { received, decryptFailed, latencyMs: { p50, p90, p99 } },\n//   sendRetries, signalErrors: { noSession, badMac, ... }, voip, memory }\n```\n\n**Experimental protocol capture** — new WhatsApp features should not be faked from\nwishful thinking; first capture the consenting test account's BinaryNode shape, redact\nsecrets, then add a high-level wrapper once the wire contract is known:\n\n```js\nimport { bindProtocolCapture } from '@japofc/baileys'\n\nconst capture = bindProtocolCapture(sock, { file: './wa-protocol.ndjson' })\n// trigger the feature on a paired official client/test account\n// each line is redacted JSON: { direction, summary, node }\nawait capture.close()\n```\n\n---\n\n## 🔐 Authentication\n\nFour auth-state backends ship out of the box. All return the same `{ state, saveCreds }` shape expected by `makeWASocket({ auth })`, so they're drop-in interchangeable.\n\n| Function | Storage | Best for |\n|---|---|---|\n| `useMultiFileAuthState(folder)` | One JSON file per key, on disk | Default choice — simple, debuggable, works everywhere |\n| `useSingleFileAuthState(fileName)` | One JSON file, on disk | Small bots where a single file is easier to manage/back up |\n| `useSqliteAuthState(opts)` | SQLite (`better-sqlite3`) | Bots that already use SQLite, or want auth in one embedded DB file |\n| `useCacheManagerAuthState(store, sessionKey)` | Any [`cacheable`](https://www.npmjs.com/package/@cacheable/node-cache)-compatible store | Multi-session hosting panels, Redis-backed setups |\n| `useRedisAuthState(opts)` | Redis (`ioredis` **or** node-redis client) | Multi-instance bots, fast shared session storage |\n| `useMongoAuthState(opts)` | MongoDB (`mongodb` collection) | Bots already on Mongo; one document per key |\n| `usePostgresAuthState(opts)` | Postgres (`pg` Pool/Client) | Production deployments on Postgres; table auto-created |\n| `useMySQLAuthState(opts)` | MySQL/MariaDB (`mysql2/promise`) | Shared-hosting setups; table auto-created |\n| `makeAuthStateFromStore(store)` | **Any** key-value backend you implement | Custom databases — implement 5 small methods and you're done |\n\n```js\nimport { makeWASocket, useMultiFileAuthState } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useMultiFileAuthState('auth_info')\nconst sock = makeWASocket({ auth: state })\nsock.ev.on('creds.update', saveCreds)\n```\n\n### Pairing code login (no QR)\n\n```js\nimport { makeWASocket, useMultiFileAuthState, formatPairingCode } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useMultiFileAuthState('auth_info')\nconst sock = makeWASocket({ auth: state, printQRInTerminal: false })\nsock.ev.on('creds.update', saveCreds)\n\nif (!state.creds.registered) {\n    const code = await sock.requestPairingCode('628123456789') // full international number\n    console.log('Pairing code:', formatPairingCode(code))      // \"ABCD-EFGH\"\n}\n\n// custom 8-char code (Crockford base32: 1-9, A-Z minus I/O/U)\nawait sock.requestPairingCode('628123456789', 'JAPJAP12')\n```\n\nInput is validated up front with clear errors instead of the classic silent server-side failures: formatting noise (`+`, spaces, dashes) is stripped, a leading `00` international call prefix is removed automatically, and the two big footguns throw immediately — **local-format numbers** (`08123...` instead of `628123...`, the #1 cause of \"the pairing code never arrives\") and numbers over the 15-digit E.164 maximum. The same check is exported standalone as `normalizePairingPhone(phone)`. For public-facing bots, rate-limit pairing attempts with [`withPairingGuard`](#-security-pack).\n\n```js\n// SQLite variant\nimport { makeWASocket, useSqliteAuthState } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useSqliteAuthState({ database: './auth.db' })\nconst sock = makeWASocket({ auth: state })\nsock.ev.on('creds.update', saveCreds)\n```\n\nAll four database adapters accept either an **existing client/collection** (recommended — you control pooling and lifecycle) or a `uri` (the driver is lazily imported only then; none are hard dependencies):\n\n```js\n// Redis variant — works with ioredis AND node-redis\nimport { makeWASocket, useRedisAuthState } from '@japofc/baileys'\n\nconst { state, saveCreds } = await useRedisAuthState({ client: myRedis, session: 'bot-1' })\nconst sock = makeWASocket({ auth: state })\nsock.ev.on('creds.update', saveCreds)\n```\n\n`useMultiFileAuthState` also exports `pruneStaleAuthFiles(folder, options)` to clean up old sender-key files on a schedule — useful for long-running bots that accumulate thousands of stale key files.\n\n---\n\n## 🗄️ Store Backends\n\n`makeInMemoryStore()` from `lib/Store` gives you the classic in-memory chat/contact/message cache. For anything that needs to survive a restart, `makePersistentStore()` (from `PersistentStore.js`) wraps one of five backends behind the same interface:\n\n| Backend | Function |\n|---|---|\n| SQLite | `createSqliteStoreAdapter(opts)` |\n| MongoDB | `createMongoStoreAdapter(opts)` |\n| MySQL | `createMysqlStoreAdapter(opts)` |\n| PostgreSQL | `createPostgresStoreAdapter(opts)` |\n| Redis | `createRedisStoreAdapter(opts)` |\n\n```js\nimport { makeWASocket, makeInMemoryStore } from '@japofc/baileys'\n\nconst store = makeInMemoryStore({})\nstore.readFromFile('./baileys_store.json')\nsetInterval(() => store.writeToFile('./baileys_store.json'), 10_000)\n\nconst sock = makeWASocket({ /* ...auth etc */ })\nstore.bind(sock.ev)\n```\n\n---\n\n## 💡 Usage Examples\n\n### Buttons & Native Flow\n\n```js\nimport { Button } from '@japofc/baileys'\n\nawait new Button(sock)\n    .setTitle('Promo Spesial')\n    .setBody('Diskon 20% cuma hari ini')\n    .setFooter('@japofc/baileys')\n    .addReply('Klaim Sekarang', 'claim_promo')\n    .addUrl('Lihat Katalog', 'https://example.com/catalog')\n    .addCall('Hubungi Kami', '628123456789')\n    .send(jid)\n```\n\n### Poll\n\n```js\nimport { Poll } from '@japofc/baileys'\n\nawait new Poll(sock)\n    .setName('Mau makan apa hari ini?')\n    .addOptions(['Fried Rice', 'Chicken Noodles', 'Meatballs'])\n    .setSelectable(1)\n    .send(jid)\n```\n\n> **v2.4.7** — the poll builder now validates before it sends. Duplicate options are\n> rejected (poll results are bucketed by option text, so duplicates used to merge into\n> one result), `setEndDate()` throws on an unparseable date instead of wiring\n> `endTime: NaN`, and `setQuiz()` can no longer be combined with\n> `setAnnouncementGroup()` (that path emits `pollCreationMessageV2`, which has no\n> `correctAnswer` field, so the quiz was silently dropped). Quiz polls are also finally\n> readable: `getAggregateVotesInPollMessage()` now recognises `pollCreationMessageV5`.\n\n```js\nconst poll = new Poll(sock)\n    .setName('Quiz: ibu kota Indonesia?')\n    .addOptions(['Jakarta', 'Bandung', 'Surabaya'])\n    .setQuiz('Jakarta')\n\npoll.validate()        // [] when safe to send — collects every problem at once\npoll.assertValid()     // throws the first problem (build()/send() run this for you)\npoll.countOptions()    // 3\npoll.getOptions()      // ['Jakarta', 'Bandung', 'Surabaya'] (a copy)\npoll.removeOption('Surabaya')\nPoll.MAX_OPTIONS       // 12 — enforced, like MAX_NAME_LENGTH (255) / MAX_OPTION_LENGTH (100)\n\nawait poll.send(jid)\n```\n\n### Carousel\n\n> Cards are usually built with `Button(...).toCard()` first. Media cards work as before, and v2.4.7 also allows valid text/button-only carousel cards (WhatsApp renders them) via `addTextCard()` or a `Button(...).toCard()` card with no media header.\n\n```js\nimport { Button, Carousel } from '@japofc/baileys'\n\nconst cardA = await new Button(sock)\n    .setImage('https://example.com/a.jpg')\n    .setTitle('Produk A')\n    .addUrl('Lihat', 'https://example.com/a')\n    .toCard()\n\nconst cardB = await new Button(sock)\n    .setImage('https://example.com/b.jpg')\n    .setTitle('Produk B')\n    .addUrl('Lihat', 'https://example.com/b')\n    .toCard()\n\nawait new Carousel(sock)\n    .setBody('Pilih salah satu produk di bawah ini')\n    .addCard([cardA, cardB])\n    .send(jid)\n\n// Text/button-only card, no image required:\nawait new Carousel(sock)\n    .setBody('Quick actions')\n    .addTextCard({\n        title: 'Support',\n        text: 'Choose an action',\n        buttons: [\n            { id: 'faq', text: 'FAQ' },\n            { webview: 'https://example.com/help', text: 'Open Help' }\n        ]\n    })\n    .send(jid)\n```\n\n### AIRich — rich response cards\n\n```js\nimport { AIRich } from '@japofc/baileys'\n\nawait new AIRich(sock)\n    .addHeading('Order Summary')\n    .addText('Your order is being processed.')\n    .addTable([\n        ['Item', 'Qty'],\n        ['Iced Latte', '2']\n    ])\n    .addTip('Orders are usually ready in 15 minutes')\n    .addSuggest('Track Order')\n    .send(jid)\n```\n\nFor the common case, v2.4.7 also exports a one-liner wrapper around the same builder:\n\n```js\nimport { sendJapRich, jap } from '@japofc/baileys'\n\nawait sendJapRich(sock, jid, {\n    title: 'Order Summary',\n    markdown: '# Paid\\nYour order is being processed.',\n    actions: { text: 'Track', url: 'https://example.com/order/123' },\n    suggestions: ['Track Order', 'Contact Support']\n})\n\n// Or keep chaining after the shortcut builds the card:\nawait jap(sock, '# Quick Report').addTip('Generated now').send(jid)\n```\n\nNeutral aliases (`sendRich`, `Rich`, `createRich`, `buildRich`) remain available, but the JAP-branded helpers (`jap`, `japRich`, `createJapRich`, `buildJapRich`, `sendJapRich`) are the preferred names for new code.\n\n**Since v2.4.8 the socket speaks rich directly** — no free function, no passing `sock` around:\n\n```js\nawait sock.sendJapRich(jid, { title: 'Order Summary', markdown: '# Paid', suggestions: ['Track'] })\nawait sock.sendJapTable(jid, [['Item', 'Qty'], ['Coffee', '2']], { title: 'Cart' })\nawait sock.sendJapLatex(jid, 'E = mc^2')\n\n// sendMessage() routes these shapes too\nawait sock.sendMessage(jid, { table: [['Item', 'Qty'], ['Coffee', '2']], title: 'Cart' })\nawait sock.sendMessage(jid, { latex: '\\\\frac{a}{b}' })\nawait sock.sendMessage(jid, { jap: { markdown: '# Hi', suggestions: ['More'] } })\n```\n\n`sendRich` / `sendTable` / `sendLatex` are neutral aliases of the three socket methods, and\n`{ disableJapyea: true }` opts a call out of the auto-routing layer entirely.\n\nThe one-liner now covers **every** AIRich primitive — `latex`, `task(s)`, `widget(s)`,\n`progressStatus`, `thinking`, `quotaUpsell`, `bloks`, `reels`, `post(s)`, `product(s)`,\n`socialEntity`, `inlineVideo`, `contentItems`, `generating` — and a key it does not recognise\nis now an error with a suggestion (`unknown key 'tabel' (did you mean 'table'?)`) instead of\na silently blank card. Pass `{ allowUnknown: true }` to carry your own extra fields through,\nand import `ONE_LINER_KEYS` if you want to validate input yourself.\n\n`AIRich` supports `{ id, insertAt }` on every `add*()`/`set*()` call, so you can insert a block relative to one you added earlier instead of always appending to the end — handy for streaming/edit-in-place style responses combined with `sendEdit(jid, id)`.\n\n**`streamText()` — the \"AI typing\" effect.** One bubble that grows via in-place edits (exactly how Meta AI streams its answers), instead of flooding the chat:\n\n```js\n// sends once, then patches the same bubble until the full text is out\nawait new AIRich(sock).streamText(jid, longAnswer, {\n    chunkSize: 120,  // ~chars per reveal (split at word boundaries)\n    intervalMs: 900, // pause between edits (min 300)\n    cursor: ' ▍'     // shown while streaming, removed at the end ('' disables)\n})\n// works alongside other blocks too: addHeading()/addTable() first, then streamText()\n```\n\n**`readRichMessage()` — the reader half.** Parse a received rich card (from any AI/assistant-style bot) back into structured blocks instead of staring at opaque proto:\n\n```js\nimport { readRichMessage } from '@japofc/baileys'\n\nsock.ev.on('messages.upsert', ({ messages }) => {\n    const rich = readRichMessage(messages[0])\n    if (!rich.found) return\n    rich.blocks      // [{ type: 'heading', text }, { type: 'code', language, code },\n                     //  { type: 'table', rows, headerRows }, { type: 'text', text, entities }, …]\n    rich.suggestions // every suggestion-pill text\n    rich.text        // flat text rendering of the whole card\n})\n```\n\nHandles both wire forms (unified-response payload + proto submessages fallback), resolves inline link entities back to `[label](url)`, re-joins syntax-highlighted code spans, never throws — non-rich input returns `{ found: false }`. Round-trip tested against the AIRich builder itself.\n\nOther builders worth knowing about: **`ButtonV2`** (simpler quick-reply-only buttons), **`ButtonV3`** (`loadFrom(msg)` to edit an existing template message in place), and **`Toolkit`** (static helpers: `Toolkit.resize()`, `Toolkit.fetchBuffer()`, `Toolkit.waitAllPromises()`, `Toolkit.extractIE()` for parsing `[label](url)` links/citations/LaTeX out of plain text).\n\n### 📁 Builders Folder Map (`lib/Builders/`)\n\nEvery message builder lives in its own file under `lib/Builders/`, so you can trace exactly where a class comes from instead of digging through one giant `MessageBuilder.js`. `index.js` is just the barrel file that re-exports everything below (plus their aliases) for the top-level `import { ... } from '@japofc/baileys'` syntax.\n\n| File | Exports | What it's for |\n|---|---|---|\n| `shared.js` | `Toolkit`, `BaseBuilder`, `RowBuilder` | The shared foundation every other builder is built on. `BaseBuilder` holds the common chainable `send()`/context-info plumbing, `RowBuilder` is the shared row/section helper, and `Toolkit` is the static-helper grab bag (`resize`, `fetchBuffer`, `waitAllPromises`, `extractIE`, media-duration/preview helpers). Nothing here is meant to be instantiated directly in bot code — it exists so `Button`, `Poll`, `Carousel`, etc. don't each reimplement the same plumbing. |\n| `Button.js` | `Button`, `CardBuilder` | The main interactive/native-flow button builder — headers (image/video/document), CTA helpers (`addUrl`, `addCall`, `addReply`, and the wider native-flow set), and `.toCard()` to turn a button message into a `Carousel` card. |\n| `ButtonV2.js` | `ButtonV2` | A lighter-weight legacy `buttonsMessage` variant limited to up to 3 quick-reply buttons — includes `validate()`/`assertValid()`, `countButtons()`/`getButtons()`/`clearButtons()`, and relays with the same canonical `getBizBinaryNode()` envelope as the socket path. |\n| `ButtonV3.js` | `ButtonV3` | Built around `loadFrom(msg)` — loads an existing `templateMessage` (e.g. one you fetched or that was quoted) so you can edit it in place. Also validates hydrated quick-reply/url/call buttons and relays with the canonical biz node. |\n| `Carousel.js` | `Carousel` | Chains `Button(...).toCard()` results into a swipeable card carousel. Accepts media cards and text/button-only cards (`addTextCard()`), validates before send, and is capped at `Carousel.MAX_CARDS` (10) since WhatsApp silently truncates anything beyond that. |\n| `Poll.js` | `Poll` | Poll/vote message builder — question, options, single/multi-select, hidden-voter mode, correct-answer marking, expiry. |\n| `AIRich.js` | `AIRich` (+ aliases `ORich`, `AIJap`, `LeafRich`, `JapAI`, `JapRich`, `RichJap`) | The rich AI-assistant-style response builder described above — headings, formatted text, tables, media/product/post cards, task/progress cards, tip banners, quick-reply suggestions. |\n| `Rich.js` | `jap`, `japRich`, `createJapRich`, `buildJapRich`, `sendJapRich` (+ neutral aliases `Rich`, `createRich`, `buildRich`, `sendRich`) | One-liner convenience wrapper over `AIRich` for common cards (`markdown`, `text`, `actions`, `suggestions`, media, etc.) without replacing the full chainable builder. |\n| `A2UI.js` | `A2UI`, `sendA2UIWidget` | Lower-level A2UI/Bloks widget builder. Builds the flat `components` tree (Column/Row → `children`, Card/Button → `child`, Modal → `trigger`/`content`) that Bloks widgets expect and sends it through the same `getBizBinaryNode()` path as `Button`/`ButtonV2`, so the wire-level node always matches the button names actually sent. |\n| `JapBaileys.js` | `JapBaileys` | A unified builder **hub** — one object that wraps all the builders above behind short method names (`.button()`, `.buttonV2()`, `.buttonV3()`, `.carousel()`, `.poll()`, `.airich()`, `.rich()`, `.a2ui()`), plus PascalCase aliases (`.Button()`, `.Carousel()`, `.Poll()`, `.AIRich()`, `.Rich()`, `.A2UI()`) for developers who prefer that naming style. |\n| `index.js` | everything above, plus `MESSAGE_BUILDER_VERSION` | The barrel file — re-exports every builder and its aliases so `import { Button, Poll, AIRich, JapBaileys } from '@japofc/baileys'` works without reaching into individual files. `MESSAGE_BUILDER_VERSION` tracks the builder API surface's own version, independent of the package version. |\n\n**Unified hub example** — useful if you'd rather carry one object around than import each builder individually:\n\n```js\nimport { JapBaileys } from '@japofc/baileys'\n\nconst vx = new JapBaileys(sock)\n\nawait vx.button()\n    .setTitle('Promo Spesial')\n    .addReply('Klaim Sekarang', 'claim_promo')\n    .send(jid)\n\nawait vx.poll()\n    .setName('Mau makan apa hari ini?')\n    .addOptions(['Fried Rice', 'Chicken Noodles'])\n    .send(jid)\n```\n\n---\n\n### 📌 Pin / Keep in Chat\n\n```js\n// Pin a message for 7 days (default 24h), unpin, keep / unkeep in disappearing chats\nawait sock.sendPin(jid, msg.key, { durationSec: 7 * 86400 })\nawait sock.sendUnpin(jid, msg.key)\nawait sock.sendKeep(jid, msg.key)\nawait sock.sendUnkeep(jid, msg.key)\n```\n\n### 📅 Event\n\n```js\nawait sock.sendEvent(jid, {\n    name: 'Weekly Meeting',\n    description: 'Bahas progres bot',\n    startDate: new Date('2026-09-15T10:00:00+07:00'),\n    endDate: new Date('2026-09-15T11:00:00+07:00'),\n    location: { name: 'Office', address: 'Jakarta' },\n    extraGuestsAllowed: true\n})\n```\n\n### 📞 Scheduled Call\n\nNative scheduled-call message (the \"Schedule call\" card with a join reminder):\n\n```js\n// 'voice' (default) or 'video'\nawait sock.sendScheduledCall(jid, {\n    title: 'Daily standup',\n    scheduledAt: new Date('2026-09-15T09:00:00+07:00'),\n    callType: 'video'\n})\n\n// Cancel it later (needs the creation message's key)\nawait sock.cancelScheduledCall(jid, creationMsg.key)\n```\n\n### 📱 Mini App\n\nTwo modes — pass `url`, `flow`, or both (two buttons):\n\n```js\nimport { sendMiniApp } from '@japofc/baileys'\n\nawait sendMiniApp(sock, jid, {\n    title: 'My Mini App',\n    body: 'Tap the button to open the app 👇',\n    // 1) webview mode: rich card + CTA opening your web app\n    //    (in-app webview when supported, else the browser)\n    url: 'https://myapp.example.com',\n    params: { ref: 'wa-bot' }, // → appended as ?ref=wa-bot\n    buttonText: '🚀 Open App',\n    // 2) Flows mode: TRUE native in-chat mini app (forms/screens inside\n    //    WhatsApp, no browser). Needs a published Flow ID from Flows Manager.\n    flow: { id: '123456789', cta: '📝 Isi Form', screen: 'WELCOME' },\n    thumbnail: 'https://myapp.example.com/icon.png' // url or Buffer\n})\n// or as a socket method: await sock.sendMiniApp(jid, { ... })\n```\n\n---\n\n## 📨 Message Helpers\n\nHigh-level one-liners for modern message types — validated, with friendly aliases:\n\n```js\nawait sock.sendLocation(jid, { lat: -6.2, lng: 106.8, name: 'Jakarta' });\nawait sock.sendContact(jid, { name: 'John', vcard: 'BEGIN:VCARD\\n...' });\nawait sock.sendGroupInvite(jid, { code: 'AbC123', jid: groupJid, subject: 'Community' });\nawait sock.sendPaymentRequest(jid, { currency: 'IDR', amount: 50000, note: 'coffee ☕' });\nawait sock.sendInvoice(jid, { note: 'INV-001' });\nawait sock.sendPollOption(jid, pollKey, ['New option']);\nawait sock.sendEventInvite(jid, { eventTitle: 'Party', startTime: new Date(...) });\nawait sock.sendNewsletterInvite(jid, { newsletterJid, newsletterName: 'News' });\n\n// Poll upgrades (already wired end-to-end):\nawait sock.sendPoll(jid, {\n  name: 'Jam berapa?', values: ['Pagi', 'Sore'],\n  endDate: new Date('2026-09-16T00:00:00Z'), // auto-close\n  hideVoter: true,      // anonymous poll\n  canAddOption: true,   // voters may add options\n});\n```\n\nMusic messages are experimental — the proto is correct but interop with official\nclients is unverified (see [Honestly not implemented](#honestly-not-implemented-and-why)):\n\n```js\nawait sock.sendMusic(jid, { songUri, artworkUri, embeddedMusic: { songId, title, author } });\n```\n\n**Escape hatch:** every content key also works inline via `sendMessage`, and `{ raw: true, <AnyMessageField>: {...} }`\npasses any proto field through untouched — full `WAProto` coverage with zero wrapper lag:\n\n```js\nawait sock.sendMessage(jid, { raw: true, musicMessage: { songUri } });\n```\n\nTypeScript consumers get a typed `AnyMessageContent` (`import type { AnyMessageContent } from '@japofc/baileys'`).\n\n## 🧰 Channels, History & Transcripts\n\n**Channel management** (live queries):\n\n```js\nawait sock.newsletterDelete(channelJid)\nawait sock.newsletterAdminCount(channelJid)\nawait sock.newsletterJoinInvite('invite-code')\nawait sock.newsletterChangeOwner(channelJid, newOwnerJid) // experimental\nawait sock.communityGetInviteCode(communityJid)\n// ...plus existing follow/unfollow/mute/react/fetch + full community CRUD\n```\n\n**Group history sharing** for new members (forwards recent messages to their DM):\n\n```js\nimport { getGroupHistoryFromStore } from '@japofc/baileys'\nconst messages = getGroupHistoryFromStore(store, groupJid, 10)\nawait sock.shareGroupHistory({ groupJid, members: newMemberJid, messages, greeting: true })\n```\n\n**Voice-note transcription** (pluggable provider — cloud Whisper or your own):\n\n```js\nimport { openAIWhisperProvider } from '@japofc/baileys'\nconst provider = openAIWhisperProvider({ apiKey: process.env.OPENAI_API_KEY })\nconst { text } = await sock.transcribeMessage(voiceNoteMsg, { provider })\n```\n\n**Mini-app deep links** (HMAC-signed params your web app can verify):\n\n```js\nimport { createMiniAppLink, parseMiniAppParams, buildFlowDataExchange } from '@japofc/baileys'\nconst link = createMiniAppLink('https://app.example.com/', { uid: '123' }, { secret: 's3cr3t' })\nparseMiniAppParams(link, { secret: 's3cr3t' }) // → { uid: '123' } (throws if tampered)\nbuildFlowDataExchange('navigate', { screen: 'HOME' }) // Flows data_exchange payload\n```\n\n**A2UI widgets** now include `Slider`, `Switch`, `List`, `ProgressBar`, `Avatar`,\n`Badge`, `Spacer`, and `Tabs` alongside the existing Text/Image/Video/Button/Card/Modal\nset (all ref-validated at `build()`).\n\n## 🔐 Security Pack\n\nDrop-in hardening for auth state, secrets, and abuse — all in\n`lib/Utils/auth-secure.js`, covered by `tests/security.test.js` (incl. fuzzing).\n\n```js\nimport {\n  useEncryptedFileAuthState, secureLogger, withPairingGuard,\n  createQRGuard, backupAuthState, writeAuthIntegrity, repairAuthState, secureLogout\n} from '@japofc/baileys'\n\n// 1. AES-256-GCM encrypted auth state (reads legacy plaintext, migrates on save)\nconst { state, saveCreds } = await useEncryptedFileAuthState('./auth', { password: process.env.AUTH_PW })\n\n// A damaged creds.json (wrong password, truncated, empty, not JSON) throws instead of\n// silently minting a new identity on top of your session — since v2.4.8 that guard covers\n// legacy plaintext files too. Recover with restoreAuthState()/repairAuthState(), or delete\n// the folder on purpose to reset.\nconst sock = makeWASocket({\n  auth: state,\n  logger: secureLogger(pino({ level: 'info' })), // 7. redacts qr/tokens/keys in every log line\n})\n\n// 2. pairing-code rate limit: 5/hour per number, 30s between attempts\nwithPairingGuard(sock, { maxPerHour: 5, minIntervalMs: 30_000 })\n\n// 3. QR fist-guard: handle the first QR, swallow re-emits for 60s\nconst qrGuard = createQRGuard({ ttlMs: 60_000 })\nsock.ev.on('connection.update', ({ qr }) => { qr = qrGuard.handle(qr); if (qr) show(qr) })\n\n// 6/8. encrypted backup + integrity snapshot\nawait backupAuthState('./auth', './auth.jabackup', { password: process.env.BACKUP_PW })\nawait writeAuthIntegrity('./auth', { secret: process.env.INT_PW })\n\n// 9. repair corrupt stores (quarantines + restores creds from backup)\nawait repairAuthState('./auth', { password: process.env.AUTH_PW, backupFile: './auth.jabackup', backupPassword: process.env.BACKUP_PW })\n\n// 4. logout + overwrite/unlink every auth file + scrub in-memory creds\nawait secureLogout(sock, { authFolder: './auth' })\n```\n\nSingle-file variant: `useEncryptedSingleFileAuthState(file, { password })`.\n\n## 🆕 WA 2026 catch-up\n\nWhatsApp 2026 features, wired into JAP-Baileys. Everything here was audited against the\nlatest official clients — only gaps were added; what already worked is just documented.\n\n### Usernames (chat without phone numbers)\n\n```js\nawait sock.checkUsername('japstore');            // availability\nawait sock.setUsername('japstore');              // claim it\nawait sock.reserveUsername('japstore');          // reserve it (2026 reservation flow)\nawait sock.findUserByUsername('japstore');       // USync lookup → JID\nconst u = await sock.fetchContactUsernames(['62812@s.whatsapp.net']);\n```\n\n### Editable polls (`editPoll`)\n\nPolls are editable for ~15 minutes after creation (server-side rule):\n\n```js\nconst sent = await sock.sendPoll(jid, { name: 'Jam berapa?', values: ['Pagi', 'Sore'] });\nawait sock.editPoll(jid, sent.key, { name: 'Jam berapa?', values: ['Pagi', 'Siang', 'Sore'] });\n```\n\n### Mass mention (`sendMentionAll`)\n\n```js\nawait sock.sendMentionAll(groupJid, 'Announcement: meeting at 9!');\n```\n\n> In groups with 32+ members `@all` is admin-only and the rule is enforced\n> server-side — non-admin calls are silently dropped by WhatsApp.\n\n### Status mentions (`sendStatusMention`)\n\nPost a status and notify specific users or whole groups — they get the\n\"mentioned you in their status\" bubble linking to your status:\n\n```js\n// text status, mention two users\nawait sock.sendStatusMention({ text: 'Big announcement! 🎉' }, [\n    '62812xxx@s.whatsapp.net',\n    '62813xxx@s.whatsapp.net',\n])\n\n// image status, mention an entire group (every member is notified)\nawait sock.sendStatusMention({ image: buffer, caption: 'New drop 🔥' }, [groupJid])\n```\n\nWorks with any status content (`text`, `image`, `video`, `audio`). Pace the\nnotification fan-out with `{ delayMs }` in options (default 1500 ms per jid).\n\n### Event reminders\n\n```js\nawait sock.sendMessage(jid, {\n  event: {\n    title: 'Meeting', description: 'Q3', startDate: new Date('2026-09-15T09:00:00+07:00'),\n    reminder: true, reminderOffsetSec: 1800, // remind 30 min before start\n  }\n});\n```\n\n### Sender phone from LID events (`resolveSenderPn`)\n\nFixes LID-only payloads (e.g. call offers where `caller_pn` is missing):\n\n```js\nsock.ev.on('messages.upsert', async ({ messages }) => {\n  for (const m of messages) console.log(await sock.resolveSenderPn(m)); // '62812…' | null\n});\n```\n\n### View-once voice notes\n\n`sendVoiceNote()` content composes with `viewOnce`:\n\n```js\nawait sock.sendMessage(jid, { ...(await buildVoiceNoteContent('./a.ogg')), viewOnce: true });\n```\n\n### Member tags (groups)\n\nAlready exposed — no new code, documented here:\n\n```js\nawait sock.updateMemberLabel({ groupJid, lid, label: 'Admin' });\n```\n\n### Honestly not implemented (and why)\n\n- **Voice message transcripts** — generated on-device by official clients only; there is\n  no transcript API on the wire.\n- **Group message history sharing (native)** — WhatsApp began rolling out the official\n  \"Group Message History\" feature (share the last 25–100 messages with a newly added\n  member, E2EE, admin-controlled) in Feb 2026. Its wire format still hasn't been captured\n  by any public library (re-verified 28 Sep 2026 by downloading and API-diffing upstream\n  Baileys 7.0.0-rc14 plus the 8 largest living forks — none carry it). Until it is, this repo ships an honest *workaround* —\n  `shareGroupHistory()` forwards recent messages into the new member's DM — which is NOT\n  the native flow (no in-group history bubble, no \"history shared\" notice). If you need\n  native behaviour, the only path today is an official client.\n- **Music messages (interoperability)** — the `MusicMessage` proto struct round-trips\n  fine and `sendMusic()` emits it, but real interop needs provider catalog IDs\n  (Spotify/Apple) plus an artwork upload flow that official clients negotiate privately;\n  no public capture exists (re-verified Sep 2026). Messages built with made-up IDs render\n  as a plain preview or nothing at all on official clients — treat `sendMusic()` as\n  experimental and test against a real device before shipping. What v2.4.1 *does* fix:\n  unknown `embeddedMusic` fields used to be silently dropped by the proto encoder\n  (a typo'd key just vanished from the wire) — they now throw a clear 400 listing the\n  supported field names. For the modern music-on-status surface, see\n  `withMusicAttribution()` below.\n- ~~`mediaKeyDomain`~~ — **now IMPLEMENTED** (kept here for history). Backported from rc14 onto all 5 media types\n  (`Audio/Document/Image/Sticker/VideoMessage`, enum `UNSET/E2EE_CHAT/STATUS/CAPI/BOT`)\n  with a send passthrough: `sendMessage(jid, { image: buf, mediaKeyDomain: 1 })`.\n  Unset by default (recommended — the server labels it). Skipped only on\n  `MMSThumbnailMetadata`, where upstream's field number 8 collides with the newer\n  `messageHistoryMetadata` in our proto.\n\n## 🆕 Everyday Utilities\n\nOne-liners for daily bot work (also usable standalone — see `examples/`):\n\n```js\n// 📊 Poll (chats/groups) + Quiz (channels only)\nawait sock.sendPoll(jid, { name: 'What to eat?', options: ['Rice', 'Noodles'] })\nawait sock.sendQuiz(channelJid, { name: 'Quiz', options: ['A', 'B'], correctAnswer: 'A' })\n\n// 🎙️ Voice note — auto-converts mp3/wav/… to Opus PTT (needs fluent-ffmpeg)\nawait sock.sendVoiceNote(jid, './hello.mp3') // path | Buffer | { url }\n\n// 📞 Tag everyone (visible @list vs hidden)\nawait sock.tagAll(groupJid, 'Meeting at 10!')\nawait sock.hideTag(groupJid, 'Announcement 📢')\n\n// 🔍 LID → phone number (best-effort, null when unknown)\nawait sock.getPhoneNumber('12345@lid') // → '62812…'\nawait sock.getLidForPhone('62812…')    // reverse lookup\n\n// 🧍 Humanized send — typing… + natural delay + per-chat queue\nawait sock.sendHumanized(jid, { text: 'Hello!' })\n\n// 🛡️ Send Guard — global anti-ban pacing baked into sendMessage()\nconst sock = makeWASocket({\n    sendRateLimit: {\n        messagesPerMinute: 20, // global token-bucket ceiling (0 = off)\n        perChatDelayMs: 1500,  // minimum gap between sends to the same chat\n        jitterRatio: 0.2       // ±20% randomness so timing never looks robotic\n    }\n})\nawait sock.sendMessage(jid, { text: 'auto-paced 🛡️' })            // paced\nawait sock.sendMessage(jid, { text: 'now!' }, { skipRateLimit: true }) // bypass\n\n// ✅ Delivery tracking — await the server ack of an outgoing message\nconst msg = await sock.sendMessage(jid, { text: 'important!' })\nawait sock.waitForMessageAck(msg.key.id) // resolves on ack, rejects on\n                                         // server error / 60s timeout\n\n// ✅ One-call variant — send + await the ack, race-free (waiter registered\n// BEFORE the send goes out, so a fast ack can never slip through)\nconst { message, ack } = await sock.sendMessageAcked(jid, { text: 'critical!' }, { ackTimeoutMs: 30_000 })\n\n// 📣 Broadcast to many jids — paced, per-jid outcomes, never dies mid-run\nconst report = await sock.sendBroadcast(jids, { text: 'promo!' }, { delayMs: 1500 })\n// { sent: [...], failed: [{ jid, error }], total }\n\n// 🔗 Group invite links\nextractGroupInviteCode('https://chat.whatsapp.com/AbCdEf…') // 'AbCdEf…'\nawait sock.joinGroupViaLink('https://chat.whatsapp.com/AbCdEf…')\n\n// 🏷️ Parse @mentions out of text → ready for sendMessage\nconst mentions = parseMentions(text) // ['62812…@s.whatsapp.net', …]\nawait sock.sendMessage(jid, { text, mentions })\n\n// 🤖 Meta AI chat (experimental — needs Meta AI on the account/region)\nconst { text } = await sock.askMetaAI('Explain black holes!')\n```\n\n**Command router** for prefix bots (`!menu`, `.sticker`) with middleware + auto-help:\n\n```js\nimport { createRouter } from '@japofc/baileys'\nconst router = createRouter({ prefix: '!' })\nrouter.command('ping', async (ctx) => ctx.reply('pong! 🏓'), { desc: 'Check bot' })\nrouter.attach(sock) // → detach()\n```\n\n**Status / channel schedulers** (in-memory):\n\n```js\nimport { StatusScheduler, ChannelScheduler, StatusHelper } from '@japofc/baileys'\nnew StatusScheduler(sock).schedule(StatusHelper.text('Pagi! ☀️'), new Date('2026-09-11T06:00:00+07:00'))\nnew ChannelScheduler(sock).schedule(channelJid, { text: 'Update' }, Date.now() + 3600_000)\n```\n\n**Music attribution on statuses** (`StatusAttribution.Type.MUSIC` — the official\nDec-2025 \"add music to your status\" surface, wire-verified against WAProto):\n\n```js\nimport { StatusHelper, withMusicAttribution } from '@japofc/baileys'\n\nconst status = withMusicAttribution(\n  StatusHelper.text('vibes 🎵'),\n  { title: 'Song Name', authorName: 'Artist', songId: '<catalog-id>' }\n)\nawait StatusHelper.send(sock, status, jidList)\n```\n\n> Official clients resolve the song via Meta's licensed catalog, so `songId`\n> must be a real catalog id for the music chip to render there. The attribution\n> struct itself is wire-correct either way (round-trip covered by tests).\n\n**Chat export & statistics** (offline — official \"Export chat\" format, JSON, CSV):\n\n```js\nimport { exportChatAsText, exportChatAsCSV, chatStatistics } from '@japofc/baileys'\n\n// messages: WAMessage[] from your store / anti-delete cache / messages.upsert\nconsole.log(exportChatAsText(messages))\n// 14/09/2026, 10.32 - J.AP: halo!\n// 14/09/2026, 10.33 - Rina: <Media omitted>\n\nfs.writeFileSync('chat.csv', exportChatAsCSV(messages))\n\nconst stats = chatStatistics(messages)\n// { total, bySender, byKind, byHour[24], byWeekday[7], topWords, ... }\n```\n\nAlso available with zero code: `npx @japofc/baileys export dump.json --format text|json|csv`.\n\n**Offline bot testing (`createMockSocket`)** — test your bot logic in CI with\nzero WhatsApp account, zero network, zero ban risk:\n\n```js\nimport { createMockSocket, createRouter } from '@japofc/baileys'\nimport assert from 'assert'\n\nconst mock = createMockSocket()\nmyBotSetup(mock.sock)              // your real bot code, unchanged\n\nawait mock.receiveText('628xx@s.whatsapp.net', '!ping')\nconst reply = await mock.waitForReply()\nassert.equal(reply.content.text, 'pong! 🏓')\n```\n\nSame `ev` surface and `sendMessage()` signature as the live socket; outgoing\nmessages are REAL `proto.WebMessageInfo` objects built through the same\n`generateWAMessage()` pipeline. Supports group injection, quoted replies,\nconnection lifecycle simulation, read-receipt/presence capture, and\n`reset()` between tests. Honest scope: it does not emulate WhatsApp servers —\nrate limits, sessions, and encryption are out of scope by design.\n\n`npm test` runs the offline suite (`tests/`, 1226 tests, no network needed).\n\n---\n\n## 🆕 New in v2.4.5\n\nFresh helpers added this release. All are exported from the package root and fully typed.\n\n### 🗳️ Poll manager — track who voted what (`createPollManager`)\n\n`getAggregateVotesInPollMessage` is stateless and double-counts a voter who changes their mind (WhatsApp re-sends the voter's *full* selection on every change). `createPollManager` keeps that state — each voter counts once, latest choice wins:\n\n```js\nimport { createPollManager } from '@japofc/baileys'\n\nconst polls = createPollManager()\nconst sent = await sock.sendMessage(jid, { poll: { name: 'Lunch?', values: ['Pizza', 'Sushi'], selectableCount: 1 } })\npolls.register(sent) // remembers options + key\n\n// feed it decrypted votes (option names, sha256 hex, or the raw hash Buffers WA sends):\npolls.applyVote(sent.key.id, voterJid, ['Pizza'])\n\npolls.tally(sent.key.id)   // [{ name:'Pizza', count, voters:[] }, ...]\npolls.winner(sent.key.id)  // { winners:['Pizza'], count } (tie-aware)\nconsole.log(polls.render(sent.key.id)) // live bar chart\n```\n\n### ❤️‍🩹 Session-health monitor (`createSessionHealthMonitor`)\n\nDetects bursts of undecryptable messages (a dead Signal session / Bad-MAC drift) per contact and alerts you — purely observational, never throws into your event loop:\n\n```js\nimport { createSessionHealthMonitor } from '@japofc/baileys'\n\nconst health = createSessionHealthMonitor({ badMacThreshold: 3, windowMs: 60_000 })\nhealth.bind(sock)\nhealth.onUnhealthy(({ jid, failures }) => console.warn(`${jid} session looks broken (${failures} decrypt fails)`))\nhealth.onRecover(({ jid }) => console.log(`${jid} recovered`))\n```\n\nShips with `canonicalizeJid()` and `makeJidCanonicalizer(sock)` to key a contact by one identity across the PN/LID split.\n\n### 🔁 Message de-dupe / idempotency (`createMessageDedupe`)\n\nStops double-replies when WhatsApp re-delivers a message (reconnect, history sync, placeholder","readmeFilename":"README.md"}