Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
ci(engine): exercise the real Baileys and browser libraries
Yudhi Armyndharis337ac0f9d701
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 260757cfc..bdc23c394 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -416,6 +416,11 @@ jobs:- name: Build projectrun: npm run build+ # Every jest lane stubs @whiskeysockets/baileys, so this is the one place the real library+ # types and unwraps inbound messages, through the compiled adapter. Needs the build above.+ - name: Run inbound messages through the real Baileys library+ run: npm run test:engine-real+- name: Upload build artifactsuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7with:@@ -506,6 +511,14 @@ jobs:OPENWA_SMOKE_IMAGE: openwa-ci:non-root-smokerun: ./scripts/smoke-test-non-root.sh+ # Boot never loads Baileys (imported on the first session start) or launches the browser+ # whatsapp-web.js drives, so a broken Dockerfile patch or a missing library would otherwise+ # pass every gate. Hermetic: no network, no WhatsApp account.+ - name: Load both engine libraries in the image+ env:+ OPENWA_SMOKE_IMAGE: openwa-ci:non-root-smoke+ run: ./scripts/smoke-test-engine-libs.sh+# Re-point the branch tag at the image this run built, by digest. The head check sits seconds# before the re-point rather than a whole build before it: a run whose commit has been# superseded leaves the tag to the newer run.diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 1430b0c48..2af2fa07b 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -385,6 +385,10 @@ jobs:- name: Build projectrun: npm run build+ # Same lane as ci.yml's build job: inbound messages through the real Baileys library.+ - name: Run inbound messages through the real Baileys library+ run: npm run test:engine-real+# ──── Create GitHub Release ───────────────────────────────────────release:name: GitHub Release@@ -575,7 +579,24 @@ jobs:IMAGE: ${{ steps.image.outputs.ref }}run: OPENWA_SMOKE_IMAGE="$IMAGE" ./scripts/smoke-test-non-root.sh+ # Boot below proves the image starts, not that either engine can: Baileys is imported on the+ # first session start and the browser is launched per session, and both differ by+ # architecture. Hermetic, so a WhatsApp outage cannot block a release. Both architectures are+ # tried even if the first fails, and the boot check below still runs, so logs name both.+ # arm64 runs under QEMU on this amd64 runner, so there the script runs the browser binary+ # instead of launching it.+ - name: Load both engine libraries on each architecture+ env:+ IMAGE: ${{ steps.image.outputs.ref }}+ run: |+ rc=0+ for platform in linux/amd64 linux/arm64; do+ OPENWA_SMOKE_IMAGE="$IMAGE" OPENWA_SMOKE_PLATFORM="$platform" ./scripts/smoke-test-engine-libs.sh || rc=1+ done+ exit "$rc"+- name: Boot + liveness check on each architecture+ if: ${{ !cancelled() }}env:IMAGE: ${{ steps.image.outputs.ref }}run: |diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 937dc790b..552a3d5cc 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -40,6 +40,8 @@ npm --prefix dashboard run test:unit| `npm run test:e2e` | Run smoke-level e2e tests from `test/` || `npm run test:pg-smoke` | Run the PostgreSQL migration and UUID-default smoke test || `npm run test:scripts` | Run the repo-level script tests on the Node test runner |+| `npm run build && npm run test:engine-real` | Feed inbound messages through the real Baileys library and built adapter |+| `OPENWA_SMOKE_IMAGE=<image> ./scripts/smoke-test-engine-libs.sh` | Import Baileys and launch the browser inside a built image || `./scripts/smoke-test-backup-restore.sh` | Run the backup/restore smoke test used by the `scripts-smoke` job || `npm run lint` | Run backend ESLint with type-aware rules || `npm run format:check` | Check Prettier formatting for backend source and specs |@@ -268,8 +270,8 @@ request's superseded run; push runs on `main` are never cancelled or queued behi| `dashboard` | dashboard install, lint, formatting, type-check, i18n parity, build, unit tests || `scripts-smoke` | shellcheck on `docker-entrypoint.sh` and every `scripts/*.sh`, plus the backup/restore smoke test || `chart` | helm lint, helm template with default and fully-toggled values, kubeconform on both renders, the rendered-behaviour check, actionlint on the workflows |-| `build` | backend build after lint/audit/test/dashboard/scripts-smoke/chart jobs pass |-| `docker` | multi-arch Docker build on pushes and pull requests, then `scripts/smoke-test-non-root.sh` against the built image so the entrypoint's root→openwa drop is verified, not assumed; publishes to GHCR only on push, so fork pull requests validate both architectures without publishing. A push publishes `:<sha>` from the build and moves the branch tag (`:main`, `:develop`) to that image only after the non-root smoke passes and only while the commit is still the branch head |+| `build` | backend build after lint/audit/test/dashboard/scripts-smoke/chart jobs pass, then `test:engine-real`, which feeds proto-built inbound messages through the real Baileys library and the compiled adapter (every jest lane stubs Baileys) |+| `docker` | multi-arch build on pushes and pull requests, then against the built image `scripts/smoke-test-non-root.sh` (the entrypoint's root→openwa drop) and `scripts/smoke-test-engine-libs.sh` (imports Baileys, launches the browser; emulated arm64 only runs its binary). Publishes only on push: `:<sha>` from the build, then the branch tag (`:main`) once the smokes pass and only while the commit is still the branch head |SDK CI is defined in `.github/workflows/sdk-ci.yml` and is path-filtered to SDK sources plus servercontract surfaces that SDKs mirror (`src/**/dto/**`, `src/**/*.controller.ts`, `src/**/*.service.ts`, and@@ -357,7 +359,9 @@ Live WhatsApp checks require an operator-owned account and should not be part of## 9.9 Known Gaps-- No default CI job exercises a real WhatsApp connection.+- No default CI job exercises a real WhatsApp connection. The engine libraries themselves are exercised+ hermetically: `test:engine-real` runs the real Baileys helpers over the compiled adapter, and the image+ smoke imports Baileys and launches the browser, neither of which needs WhatsApp to be reachable.- The default `test` job uses SQLite; PostgreSQL 16 is only exercised by the dedicated `test-postgres` job.- No default CI job exercises S3/MinIO or Docker socket proxy integration. (Redis is no longer a gap: the`test` job starts a `redis:7-alpine` service container so the queue-on e2e suite has a broker. That suitediff --git a/package.json b/package.jsonindex 46676b7d7..b979be595 100644--- a/package.json+++ b/package.json@@ -48,6 +48,7 @@"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand","test:e2e": "jest --config ./test/jest-e2e.json","test:pg-smoke": "node scripts/pg-uuid-smoke.js",+ "test:engine-real": "node --test test/engine-real/baileys-inbound.spec.mjs","typeorm": "typeorm-ts-node-commonjs","typeorm:prod": "typeorm","migration:create": "npm run typeorm -- migration:create src/database/migrations/$npm_config_name",diff --git a/scripts/smoke-test-engine-libs.sh b/scripts/smoke-test-engine-libs.shnew file mode 100755index 000000000..bd9db5f72--- /dev/null+++ b/scripts/smoke-test-engine-libs.sh@@ -0,0 +1,69 @@+#!/bin/sh+# Smoke test: load both WhatsApp engine libraries inside the built image, the way a session does.+# Usage: OPENWA_SMOKE_IMAGE=<image> [OPENWA_SMOKE_PLATFORM=linux/arm64] ./scripts/smoke-test-engine-libs.sh+# Requires Docker. Needs no network and no WhatsApp account.+#+# Booting the image proves neither engine works. Baileys is ESM and imported lazily on the first+# session start, so a patch the Dockerfile applies to it, or a dependency missing on one+# architecture, only fails once a user starts a session. whatsapp-web.js loads at boot, but the+# browser it drives is launched per session and differs by architecture (Chrome for Testing on+# amd64, Debian's chromium on arm64). Each probe runs through the real entrypoint, so it executes+# as the openwa user with the directories the entrypoint prepares.+set -e++IMAGE="${OPENWA_SMOKE_IMAGE:?set OPENWA_SMOKE_IMAGE to the image under test}"+if [ -n "${OPENWA_SMOKE_PLATFORM:-}" ]; then+ set -- --platform "$OPENWA_SMOKE_PLATFORM"+ LABEL="$OPENWA_SMOKE_PLATFORM"+else+ set --+ LABEL="host platform"+fi++echo "==> [$LABEL] Importing @whiskeysockets/baileys with ENGINE_TYPE=baileys..."+# The names the Baileys adapter reads from the module. A rename upstream, or a patched file that no+# longer parses, fails here instead of on a user's first session.+docker run --rm "$@" -e ENGINE_TYPE=baileys "$IMAGE" node -e "+import('@whiskeysockets/baileys')+ .then(m => {+ const used = ['default', 'initAuthCreds', 'makeCacheableSignalKeyStore', 'fetchLatestBaileysVersion',+ 'fetchLatestWaWebVersion', 'normalizeMessageContent', 'getContentType', 'downloadMediaMessage', 'BufferJSON',+ 'proto', 'DisconnectReason', 'S_WHATSAPP_NET', 'ALL_WA_PATCH_NAMES', 'CALL_VIDEO_PREFIX', 'CALL_AUDIO_PREFIX'];+ const missing = used.filter(name => m[name] === undefined);+ if (missing.length > 0 || typeof m.default !== 'function') throw new Error('missing exports: ' + missing.join(', '));+ console.log('PASS: Baileys loaded with every export the adapter uses');+ })+ .catch(error => { console.error('FAIL:', error); process.exit(1); });+"++# A platform other than the Docker daemon's own runs under QEMU user emulation (arm64 on the amd64+# release runner), where a full browser launch is slow and unreliable. There the probe executes the+# browser binary instead, which still fails on a missing shared library or a binary built for the+# wrong architecture. The daemon's own platform gets the full launch.+NATIVE="linux/$(docker version --format '{{.Server.Arch}}')"+if [ -n "${OPENWA_SMOKE_PLATFORM:-}" ] && [ "$OPENWA_SMOKE_PLATFORM" != "$NATIVE" ]; then+ echo "==> [$LABEL] Loading whatsapp-web.js and running the image's browser binary (emulated, no launch)..."+ docker run --rm "$@" "$IMAGE" sh -c "node -e \"require('whatsapp-web.js')\" && \"\$PUPPETEER_EXECUTABLE_PATH\" --version"+ echo "PASS: whatsapp-web.js loaded and the browser binary runs"+else+ echo "==> [$LABEL] Loading whatsapp-web.js and launching the image's browser..."+ # The same launch options the engine uses by default (configuration.ts): the image's+ # PUPPETEER_EXECUTABLE_PATH and the default PUPPETEER_ARGS.+ docker run --rm "$@" "$IMAGE" node -e "+ require('whatsapp-web.js');+ require('puppeteer')+ .launch({+ executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,+ headless: true,+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],+ })+ .then(async browser => {+ console.log('PASS: browser launched: ' + (await browser.version()));+ await browser.close();+ })+ .catch(error => { console.error('FAIL:', error); process.exit(1); });+ "+fi++echo ""+echo "Engine library smoke passed on $LABEL"diff --git a/src/common/release-gate-parity.spec.ts b/src/common/release-gate-parity.spec.tsindex 4508a27dd..ee22a3005 100644--- a/src/common/release-gate-parity.spec.ts+++ b/src/common/release-gate-parity.spec.ts@@ -1,5 +1,7 @@import * as fs from 'fs';+import * as os from 'os';import * as path from 'path';+import { spawnSync } from 'child_process';import * as yaml from 'js-yaml';import { executableLines } from './workflow-lines';@@ -191,3 +193,118 @@ describe('released images carry a verifiable build-provenance attestation', () =expect(item).toMatch(/earlier images carry no attestation/);});});++/**+ * Every jest lane stubs @whiskeysockets/baileys and puppeteer, and boot never loads Baileys or+ * launches the browser, so nothing ran either engine library before a release. Two hermetic checks+ * close that: the real-library inbound lane over the build, and the in-image library smoke on every+ * architecture the release publishes.+ */+describe('both paths exercise the real engine libraries', () => {+ type EngineStep = { run?: string; env?: Record<string, string> };+ const jobRun = (file: string, job: string): string => {+ const workflow = yaml.load(fs.readFileSync(path.join(workflowDir, file), 'utf8')) as {+ jobs?: Record<string, { steps?: EngineStep[] }>;+ };+ const steps = workflow.jobs?.[job]?.steps ?? [];+ if (steps.length === 0) throw new Error(`${file} has no "${job}" job: the parity spec drifted`);+ return steps.map(step => executableLines(step.run ?? '')).join('\n');+ };++ it.each(['ci.yml', 'release.yml'])('%s build job runs the real-library lane', file => {+ expect(jobRun(file, 'build')).toContain('npm run test:engine-real');+ });++ it('ci.yml loads both engine libraries in the built image', () => {+ expect(jobRun('ci.yml', 'docker')).toContain('./scripts/smoke-test-engine-libs.sh');+ });++ it('release.yml loads both engine libraries on both architectures', () => {+ const run = jobRun('release.yml', 'boot-smoke');+ expect(run).toContain('./scripts/smoke-test-engine-libs.sh');+ expect(run).toMatch(/for platform in linux\/amd64 linux\/arm64/);+ expect(run).toContain('OPENWA_SMOKE_PLATFORM="$platform"');+ });++ // A failure on one architecture must not hide the other's result: both are probed, the step+ // still fails, and the boot check after it still runs and reports.+ it('release.yml probes both architectures and still boots them when one fails', () => {+ type Step = { name?: string; if?: string; run?: string };+ const workflow = yaml.load(fs.readFileSync(path.join(workflowDir, 'release.yml'), 'utf8')) as {+ jobs?: Record<string, { steps?: Step[] }>;+ };+ const steps = workflow.jobs?.['boot-smoke']?.steps ?? [];+ const libs = steps.findIndex(step => (step.run ?? '').includes('./scripts/smoke-test-engine-libs.sh'));+ const boot = steps.findIndex(step => /docker run --platform/.test(step.run ?? ''));+ expect(libs).toBeGreaterThan(-1);+ expect(boot).toBeGreaterThan(libs);+ expect(steps[boot].if).toBe('${{ !cancelled() }}');++ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'engine-libs-'));+ try {+ fs.mkdirSync(path.join(dir, 'scripts'));+ const stub = path.join(dir, 'scripts', 'smoke-test-engine-libs.sh');+ fs.writeFileSync(stub, '#!/bin/sh\necho "$OPENWA_SMOKE_PLATFORM" >> probed\nexit 1\n', { mode: 0o755 });+ // The runner's default shell for `run:` steps.+ const result = spawnSync('bash', ['--noprofile', '--norc', '-eo', 'pipefail', '-c', steps[libs].run ?? ''], {+ cwd: dir,+ env: { ...process.env, IMAGE: 'img' },+ });+ expect(result.status).not.toBe(0);+ expect(fs.readFileSync(path.join(dir, 'probed'), 'utf8').trim().split('\n')).toEqual([+ 'linux/amd64',+ 'linux/arm64',+ ]);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });++ // A full browser launch under QEMU user emulation is slow and unreliable, and the release gate+ // cannot fail on an emulator fault. An emulated platform runs the browser binary instead; the+ // daemon's own platform, and the host-platform run in ci.yml, still launch it.+ it.each([+ [undefined, true],+ ['linux/amd64', true],+ ['linux/arm64', false],+ ])('the engine library smoke on %s launches the browser: %s', (platform, launches) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'engine-libs-docker-'));+ try {+ const calls = path.join(dir, 'calls');+ fs.writeFileSync(+ path.join(dir, 'docker'),+ `#!/bin/sh\nif [ "$1" = version ]; then echo amd64; exit 0; fi\nprintf '%s\\n@@end@@\\n' "$*" >> '${calls}'\n`,+ { mode: 0o755 },+ );+ const env: NodeJS.ProcessEnv = { ...process.env, PATH: `${dir}:${process.env.PATH}`, OPENWA_SMOKE_IMAGE: 'img' };+ delete env.OPENWA_SMOKE_PLATFORM;+ if (platform) env.OPENWA_SMOKE_PLATFORM = platform;+ const result = spawnSync('sh', [path.join(__dirname, '..', '..', 'scripts', 'smoke-test-engine-libs.sh')], {+ env,+ });+ expect(result.status).toBe(0);+ const runs = fs.readFileSync(calls, 'utf8').split('@@end@@\n').filter(Boolean);+ expect(runs).toHaveLength(2);+ const browser = runs[1];+ expect(browser).toContain("require('whatsapp-web.js')");+ if (platform) expect(browser).toContain(`--platform ${platform}`);+ if (launches) {+ expect(browser).toContain('.launch(');+ } else {+ expect(browser).not.toContain('.launch(');+ expect(browser).toContain('--version');+ }+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });++ it('the lane script names the spec it runs', () => {+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')) as {+ scripts: Record<string, string>;+ };+ const specs = (pkg.scripts['test:engine-real'] ?? '').split(/\s+/).filter(token => token.endsWith('.spec.mjs'));+ expect(specs.length).toBeGreaterThan(0);+ for (const spec of specs) expect(fs.existsSync(path.join(__dirname, '..', '..', spec))).toBe(true);+ });+});diff --git a/src/engine/adapters/baileys-auth-store.spec.ts b/src/engine/adapters/baileys-auth-store.spec.tsindex 99cdfb6b4..135f3e7fb 100644--- a/src/engine/adapters/baileys-auth-store.spec.ts+++ b/src/engine/adapters/baileys-auth-store.spec.ts@@ -177,3 +177,33 @@ describe('useAtomicMultiFileAuthState', () => {expect(logger.warn).toHaveBeenCalled();});});++// scripts/smoke-test-engine-libs.sh imports the real Baileys module in the built image and fails on a+// missing export. Its list has to follow what the adapter reads, or an upstream rename ships unnoticed.+describe('engine library smoke export list', () => {+ const root = path.join(__dirname, '..', '..', '..');+ const script = fs.readFileSync(path.join(root, 'scripts', 'smoke-test-engine-libs.sh'), 'utf8');+ const used = [.../const used = \[([^\]]*)\]/.exec(script)![1].matchAll(/'([^']+)'/g)].map(m => m[1]);++ it('covers every export the auth store takes from the module', () => {+ const source = fs.readFileSync(path.join(__dirname, 'baileys-auth-store.ts'), 'utf8');+ const picked = /Pick<typeof BaileysLib, ([^>]+)>/+ .exec(source)![1]+ .match(/'[^']+'/g)!+ .map(n => n.slice(1, -1));+ expect(picked.length).toBeGreaterThan(0);+ expect(used).toEqual(expect.arrayContaining(picked));+ });++ it('lists only exports the engine code still uses', () => {+ const dir = path.join(root, 'src', 'engine');+ const code = fs+ .readdirSync(dir, { recursive: true, encoding: 'utf8' })+ .filter(f => f.endsWith('.ts') && !f.endsWith('.spec.ts'))+ .map(f => fs.readFileSync(path.join(dir, f), 'utf8'))+ .join('\n')+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/^\s*\/\/.*$/gm, '');+ expect(used.filter(name => name !== 'default' && !new RegExp(`\\b${name}\\b`).test(code))).toEqual([]);+ });+});diff --git a/test/engine-real/baileys-inbound.spec.mjs b/test/engine-real/baileys-inbound.spec.mjsnew file mode 100644index 000000000..b5a9e531c--- /dev/null+++ b/test/engine-real/baileys-inbound.spec.mjs@@ -0,0 +1,198 @@+/**+ * Inbound Baileys messages through the REAL library and the compiled adapter code.+ *+ * Every jest lane maps @whiskeysockets/baileys to a stub whose getContentType is a bare mock and whose+ * normalizeMessageContent is a hand-written copy, so no test ever ran the helpers that decide an+ * inbound message's type in production. This lane imports the real library, builds each message with+ * its own protobuf classes, and feeds it through the compiled BaileysEvents.handleMessagesUpsert, the+ * handler the socket's messages.upsert event reaches. A library upgrade that changes how a message is+ * typed or unwrapped fails here, not on a user's session.+ *+ * Runs over dist/, so it needs `npm run build` first: `npm run build && npm run test:engine-real`.+ * No network, no socket, no WhatsApp account: media downloads are switched off, so a media message+ * resolves to the omitted marker.+ */+import test from 'node:test';+import assert from 'node:assert/strict';+import { createRequire } from 'node:module';++process.env.MEDIA_DOWNLOAD_ENABLED = 'false';++const require = createRequire(import.meta.url);+const lib = await import('@whiskeysockets/baileys');+const { BaileysEvents } = require('../../dist/engine/adapters/baileys-events.js');+const { ConcurrencyLimiter } = require('../../dist/common/utils/concurrency-limiter.js');++const SELF = '[email protected]';+const PEER = '[email protected]';+const GROUP = '[email protected]';+const LID = '123456789012345@lid';+const silent = { log() {}, debug() {}, verbose() {}, warn() {}, error() {} };++/**+ * Feed one message through the upsert handler and resolve with whichever callback it reaches first.+ * A message that reaches none resolves as 'none' once the handler has had time to settle.+ */+function deliver(object) {+ const message = lib.proto.WebMessageInfo.fromObject({ messageTimestamp: 1_700_000_000, ...object });+ return new Promise(resolve => {+ const to = kind => payload => resolve({ kind, payload });+ const noop = () => undefined;+ const events = new BaileysEvents({+ getSocket: () => ({ updateMediaMessage: noop }),+ getSocketOrNull: () => null,+ logger: silent,+ toNeutralJid: jid => jid.replace('@s.whatsapp.net', '@c.us'),+ normalizedSelfJid: () => SELF,+ loadLib: () => Promise.resolve(lib),+ getFetchDispatcher: () => undefined,+ inboundLimiter: new ConcurrencyLimiter(2),+ recordKeyLidMappings: noop,+ recordMessage: noop,+ recordMessageEdit: noop,+ putStoredMessage: () => undefined,+ updateStoredMessage: () => undefined,+ consumeOwnSend: () => false,+ getStoredMessage: () => undefined,+ getOnMessage: () => to('message'),+ getOnMessageCreate: () => to('create'),+ getOnMessageRevoked: () => to('revoked'),+ getOnMessageEdited: () => to('edited'),+ getOnMessageReaction: () => to('reaction'),+ getOnMessageAck: () => undefined,+ getOnGroupEvent: () => undefined,+ getOnCall: () => undefined,+ getOnPresenceUpdate: () => undefined,+ getOnCallOutcome: () => undefined,+ });+ events.handleMessagesUpsert({ messages: [message], type: 'notify' });+ setTimeout(() => resolve({ kind: 'none' }), 2000).unref();+ });+}++const inbound = (id, message, key = {}) => ({ key: { id, remoteJid: PEER, fromMe: false, ...key }, message });++test('a conversation message is text with its body', async () => {+ const { kind, payload } = await deliver(inbound('A1', { conversation: 'hello' }));+ assert.equal(kind, 'message');+ assert.equal(payload.type, 'text');+ assert.equal(payload.body, 'hello');+ assert.equal(payload.from, '[email protected]');+});++test('an extendedText message is text with its body', async () => {+ const { payload } = await deliver(inbound('A2', { extendedTextMessage: { text: 'see https://example.com' } }));+ assert.equal(payload.type, 'text');+ assert.equal(payload.body, 'see https://example.com');+});++test('an image is an image with its caption and the omitted media marker', async () => {+ const { payload } = await deliver(+ inbound('A3', { imageMessage: { caption: 'a photo', mimetype: 'image/jpeg', fileLength: 1024 } }),+ );+ assert.equal(payload.type, 'image');+ assert.equal(payload.body, 'a photo');+ assert.equal(payload.media?.omitted, true);+ assert.equal(payload.media?.mimetype, 'image/jpeg');+});++test('a push-to-talk audio is a voice message', async () => {+ const { payload } = await deliver(inbound('A4', { audioMessage: { ptt: true, mimetype: 'audio/ogg; codecs=opus' } }));+ assert.equal(payload.type, 'voice');+ assert.equal(payload.media?.omitted, true);+});++test('a plain document is a document with its mimetype', async () => {+ const { payload } = await deliver(+ inbound('A5', { documentMessage: { mimetype: 'application/pdf', fileName: 'a.pdf' } }),+ );+ assert.equal(payload.type, 'document');+ assert.equal(payload.media?.mimetype, 'application/pdf');+});++test('a captioned document is unwrapped, with the caption as its body', async () => {+ const { payload } = await deliver(+ inbound('A6', {+ documentWithCaptionMessage: {+ message: { documentMessage: { mimetype: 'application/pdf', fileName: 'b.pdf', caption: 'the report' } },+ },+ }),+ );+ assert.equal(payload.type, 'document');+ assert.equal(payload.body, 'the report');+});++test('a disappearing-chat wrapper is typed by its inner content', async () => {+ const { payload } = await deliver(+ inbound('A7', { ephemeralMessage: { message: { extendedTextMessage: { text: 'gone soon' } } } }),+ );+ assert.equal(payload.type, 'text');+ assert.equal(payload.body, 'gone soon');+});++test('a view-once wrapper is typed by its inner content', async () => {+ const { payload } = await deliver(+ inbound('A8', { viewOnceMessageV2: { message: { imageMessage: { mimetype: 'image/jpeg', viewOnce: true } } } }),+ );+ assert.equal(payload.type, 'image');+});++// Real messages carry these sidecar keys beside the content; the real getContentType skips them.+test('messageContextInfo and senderKeyDistributionMessage do not change the type', async () => {+ const { payload } = await deliver(+ inbound('A9', {+ senderKeyDistributionMessage: { groupId: GROUP },+ messageContextInfo: { messageSecret: Buffer.alloc(32, 1) },+ conversation: 'with sidecars',+ }),+ );+ assert.equal(payload.type, 'text');+ assert.equal(payload.body, 'with sidecars');+});++test('a reaction reaches the reaction callback, not onMessage', async () => {+ const { kind, payload } = await deliver(+ inbound('A10', { reactionMessage: { key: { id: 'TARGET1', remoteJid: PEER, fromMe: true }, text: '👍' } }),+ );+ assert.equal(kind, 'reaction');+ assert.equal(payload.messageId, 'TARGET1');+ assert.equal(payload.reaction, '👍');+});++test('an edit reaches the edited callback with the new text', async () => {+ const { kind, payload } = await deliver(+ inbound('A11', {+ protocolMessage: {+ type: lib.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,+ key: { id: 'TARGET2', remoteJid: PEER, fromMe: false },+ editedMessage: { conversation: 'fixed typo' },+ },+ }),+ );+ assert.equal(kind, 'edited');+ assert.equal(payload.messageId, 'TARGET2');+ assert.equal(payload.body, 'fixed typo');+});++test('a delete for everyone reaches the revoked callback', async () => {+ const { kind, payload } = await deliver(+ inbound('A12', {+ protocolMessage: {+ type: lib.proto.Message.ProtocolMessage.Type.REVOKE,+ key: { id: 'TARGET3', remoteJid: PEER, fromMe: false },+ },+ }),+ );+ assert.equal(kind, 'revoked');+ assert.equal(payload.revokedId, 'TARGET3');+});++test('a group message from an @lid participant names its author and flags the lid sender', async () => {+ const { payload } = await deliver(+ inbound('A13', { conversation: 'hi group' }, { remoteJid: GROUP, participant: LID }),+ );+ assert.equal(payload.isGroup, true);+ assert.equal(payload.type, 'text');+ assert.equal(payload.author, LID);+ assert.equal(payload.isLidSender, true);+});