@theokit/gateway-whatsapp 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/backend/cloud/client.ts","../src/backend/cloud/webhook.ts","../src/backend/cloud/index.ts","../src/backend/web/ipc.ts","../src/backend/web/lifecycle.ts","../src/backend/web/index.ts"],"names":["chunkText","BasePlatformAdapter","crypto","path","fs","execSync","spawn","resolve","path2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,IAAM,iBAAA,GAAoB,IAAA;AAEnB,SAAS,iBAAiB,IAAA,EAAwB;AACvD,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,iBAAA;AAAA,IACP,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAA,EAAM,GAAG,CAAA;AAAA,IAC9B,UAAA,EAAY,eAAA;AAAA,IACZ,cAAA,EAAgB,IAAA;AAAA,IAChB,YAAA,EAAc,MAAA;AAAA,IACd,SAAA,EAAW;AAAA,GACZ,CAAA;AACH;;;ACuCO,SAAS,WAAW,CAAA,EAAmB;AAC5C,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAA;AAC/B;AAOA,IAAM,SAAA,GAAY,6BAAA;AAgBX,SAAS,UAAU,CAAA,EAAqB;AAC7C,EAAA,OAAA,CAAQ,CAAA,CAAE,KAAA,CAAM,SAAS,CAAA,IAAK,EAAC,EAAG,GAAA,CAAI,UAAU,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAC9E;AAQO,IAAM,eAAA,GAAN,cAA8BC,2BAAA,CAAoB;AAAA,EAC9C,QAAA,GAAW,UAAA;AAAA,EACH,WAAA;AAAA,EACA,cAAA;AAAA,EACA,UAAA;AAAA;AAAA,EAET,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IAAA,CAAK,cAAc,KAAK,CAAA;AACxB,QAAA;AAAA,MACF,KAAK,QAAA;AACH,QAAA,IAAA,CAAK,aAAa,KAAK,CAAA;AACvB,QAAA;AAAA,MACF,KAAK,OAAA;AACH,QAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,sBAAA,EAAyB,KAAA,CAAM,OAAO;AAAA,CAAI,CAAA;AAC/D,QAAA;AAAA;AACJ,EACF;AACF;AAEA,SAAS,uBAAA,GAAkC;AAGzC,EAAA,OAAYC,eAAA,CAAA,OAAA;AAAA,IACLA,wBAAQ,IAAI,GAAA,CAAI,2PAAe,EAAE,QAAQ,CAAA;AAAA,IAC9C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096\n * window, `\\n\\n` → `\\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,\n * leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered\n * so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst WHATSAPP_MAX_TEXT = 4096;\n\nexport function splitForWhatsApp(text: string): string[] {\n return chunkText(text, {\n limit: WHATSAPP_MAX_TEXT,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n surrogateGuard: true,\n stripLeading: /^\\s+/,\n trimParts: true,\n });\n}\n","/**\n * `WhatsAppAdapter` — WhatsApp platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #2; ADRs D303-D314).\n *\n * Multi-backend (Cloud + Web) — backend chosen via `WhatsAppAdapterOptions.backend`.\n * Backend-agnostic adapter delegates lifecycle + send + subscribe through the\n * `WhatsAppBackend` seam (D303).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n type WhatsAppMessageEvent,\n} from \"@theokit/gateway\";\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppStatusReceipt,\n} from \"./backend-types.js\";\nimport { splitForWhatsApp } from \"./split.js\";\n\n/** Cloud (Meta WhatsApp Business Cloud API) backend config (ADR D304). */\nexport interface WhatsAppCloudConfig {\n /** Meta system-user / phone-number access token. */\n readonly accessToken: string;\n /** Meta-issued phone-number-id (NOT the user-facing phone). */\n readonly phoneNumberId: string;\n /** App secret used to verify `X-Hub-Signature-256` on inbound webhooks. */\n readonly appSecret: string;\n /** Graph API version. Defaults to `v18.0`. */\n readonly apiVersion?: string;\n}\n\n/** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */\nexport interface WhatsAppWebConfig {\n /** Stable session id used to lock the bridge per-workspace. */\n readonly sessionId: string;\n /** Optional override of the bridge script path (defaults to packaged bridge). */\n readonly bridgeScriptPath?: string;\n}\n\n/** Discriminated options shape (ADR D311). */\nexport type WhatsAppAdapterOptions =\n | {\n readonly backend: \"cloud\";\n readonly cloud: WhatsAppCloudConfig;\n /** D309: require @mention in groups. Default `true`. */\n readonly requireMention?: boolean;\n /** Phone id to detect mentions of (digits only). Defaults to `cloud.phoneNumberId`. */\n readonly botPhoneId?: string;\n }\n | {\n readonly backend: \"web\";\n readonly web: WhatsAppWebConfig;\n readonly requireMention?: boolean;\n /** Phone id to detect mentions of (digits only). Required for groups in web mode. */\n readonly botPhoneId?: string;\n };\n\n/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */\nexport function digitsOnly(s: string): string {\n return s.replace(/[^\\d]/g, \"\");\n}\n\n/**\n * Characters that may appear INSIDE a written phone number: digits and the\n * separators people type around them. Anything else — a letter, a comma, a\n * newline — ends the run.\n */\nconst PHONE_RUN = /[\\d][\\d+\\-().  ]*[\\d]|[\\d]/g;\n\n/**\n * EC-7: the phone-like runs in a message, each normalized to digits.\n *\n * The filter used to normalize the WHOLE message and ask whether the result\n * contained the bot's number. That accepts the four documented formats, but it\n * also concatenates digits from unrelated words: with a bot at 5511999999999,\n * `\"pedido 55 chegou 11, ref 99999-9999 ok\"` normalized to a string containing\n * exactly that number, and the bot answered a message about an order. Every\n * group message carrying scattered digits woke it.\n *\n * Scanning runs instead keeps the separators irrelevant WITHIN a number — which\n * is what EC-7 asks for, and what `\"+55 (11) 99999-9999\"` needs — while letting\n * a letter or a comma do what it visually does: end the number.\n */\nexport function phoneRuns(s: string): string[] {\n return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);\n}\n\n/**\n * Adapter facade. Implements `BasePlatformAdapter` (D172).\n *\n * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`\n * once the backend factories land (or pass `backend` directly in constructor).\n */\nexport class WhatsAppAdapter extends BasePlatformAdapter {\n readonly platform = \"whatsapp\" as const;\n private readonly backendImpl: WhatsAppBackend;\n private readonly requireMention: boolean;\n private readonly botPhoneId: string;\n /** Mirrors the sibling adapters: guards connect() against opening a second session. */\n private connected = false;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.\n private inboundUnsubscribe?: () => void;\n private statusUnsubscribe?: () => void;\n\n /** Construct from a pre-built backend (used by the static factories + tests). */\n constructor(\n backendImpl: WhatsAppBackend,\n opts: { requireMention?: boolean; botPhoneId?: string } = {},\n ) {\n super();\n this.backendImpl = backendImpl;\n this.requireMention = opts.requireMention ?? true;\n this.botPhoneId = digitsOnly(opts.botPhoneId ?? \"\");\n }\n\n /** Escape hatch (D180-style) for advanced features. */\n getBackend(): WhatsAppBackend {\n return this.backendImpl;\n }\n\n async connect(): Promise<boolean> {\n // Guard added 2026-08-17: this was the only adapter without one, so a second\n // connect() opened a second live WhatsApp session. Teams, SMS and Slack all\n // short-circuit here. Note it latches on SUCCESS only — a refused connect\n // must stay retryable, or one network blip becomes permanent.\n if (this.connected) return true;\n const ok = await this.backendImpl.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.handler = undefined;\n this.statusHandler = undefined;\n await this.backendImpl.disconnect();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n // EC-8: split filters empty parts internally.\n const parts = splitForWhatsApp(out.text);\n if (parts.length === 0) {\n return {\n ok: false,\n error: { code: \"empty_text\", message: \"Text reduced to zero parts after splitting.\" },\n };\n }\n let lastWamid: string | undefined;\n const isGroup = out.channel.type === \"group\";\n for (const part of parts) {\n const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });\n if (!r.ok) {\n return {\n ok: false,\n error: { code: r.error?.code ?? \"unknown\", message: r.error?.message ?? \"Send failed.\" },\n };\n }\n lastWamid = r.wamid;\n }\n return lastWamid !== undefined ? { ok: true, messageId: lastWamid } : { ok: true };\n }\n\n /** D309 + EC-7: group filter with digit-only normalization. */\n private shouldDropGroupMessage(inbound: WhatsAppInboundEvent): boolean {\n if (inbound.conversationType !== \"group\" || !this.requireMention) return false;\n if (this.botPhoneId.length === 0) return true; // misconfigured — drop silently\n return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));\n }\n\n private toMessageEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent {\n return {\n id: inbound.wamid,\n platform: \"whatsapp\",\n sender: { id: inbound.fromPhone, displayName: inbound.contactName },\n channel: { id: inbound.channelId, type: inbound.conversationType },\n text: inbound.text,\n receivedAt: inbound.receivedAt,\n whatsapp: {\n wamid: inbound.wamid,\n phoneNumberId: inbound.phoneNumberId,\n contactName: inbound.contactName,\n backend: inbound.backend,\n raw: inbound.raw,\n },\n };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.inboundUnsubscribe?.();\n this.handler = handler;\n\n this.inboundUnsubscribe = this.backendImpl.onInbound(async (inbound) => {\n if (!this.handler) return;\n if (this.shouldDropGroupMessage(inbound)) return;\n await this.handler(this.toMessageEvent(inbound));\n });\n\n return () => {\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.handler = undefined;\n };\n }\n\n /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusUnsubscribe?.();\n this.statusHandler = handler;\n this.statusUnsubscribe = this.backendImpl.onStatusReceipt(async (r) => {\n await this.statusHandler?.(r);\n });\n return () => {\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.statusHandler = undefined;\n };\n }\n}\n","/**\n * Per-backend HTTP/IPC error → canonical `WhatsAppSendResult.error` shape.\n *\n * Cloud follows Meta error codes (https://developers.facebook.com/docs/graph-api/guides/error-handling).\n * Web follows whatsapp-web.js error strings.\n *\n * @internal\n */\n\nimport type { WhatsAppSendResult } from \"./backend-types.js\";\n\ntype ErrorPayload = Required<WhatsAppSendResult>[\"error\"];\n\ninterface MetaErrorBody {\n error?: {\n code?: number;\n message?: string;\n error_subcode?: number;\n };\n}\n\n/** Custom error: `connect()` timed out waiting for \"ready\" (EC-6). */\nexport class WhatsAppConnectTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);\n this.name = \"WhatsAppConnectTimeoutError\";\n }\n}\n\nfunction cloudErrorCode(\n status: number,\n errCode: number,\n): \"auth_failed\" | \"rate_limit\" | \"invalid_request\" | \"server_error\" | \"unknown\" {\n if (errCode === 190 || status === 401) return \"auth_failed\";\n if (errCode === 130 || errCode === 131 || status === 429) return \"rate_limit\";\n if (status === 400 || errCode === 100) return \"invalid_request\";\n if (status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\nexport function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload {\n const parsed = (body !== null && typeof body === \"object\" ? body : {}) as MetaErrorBody;\n const errCode = parsed.error?.code ?? 0;\n const errMsg = parsed.error?.message ?? `HTTP ${status}`;\n const code = cloudErrorCode(status, errCode);\n if (code === \"auth_failed\") return { code, message: `Bearer token rejected: ${errMsg}` };\n if (code === \"rate_limit\") return { code, message: `Throttled: ${errMsg}` };\n return { code, message: errMsg };\n}\n\nexport function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload {\n const msg = ipcError ?? \"unknown bridge error\";\n if (msg.includes(\"AUTHENTICATION\") || msg.includes(\"UNAUTHORIZED\")) {\n return { code: \"auth_failed\", message: msg };\n }\n if (msg.includes(\"RATE\") || msg.includes(\"THROTTLE\")) {\n return { code: \"rate_limit\", message: msg };\n }\n if (msg.includes(\"PROTOCOL\") || msg.includes(\"DISCONNECT\")) {\n return { code: \"server_error\", message: msg };\n }\n if (msg.includes(\"TIMEOUT\")) {\n return { code: \"timeout\", message: msg };\n }\n return { code: \"unknown\", message: msg };\n}\n","/**\n * `WhatsAppCloudClient` — typed `fetch` wrapper for Meta WhatsApp Business\n * Cloud API (ADR D304). No Meta SDK; we own the wire.\n *\n * @internal\n */\n\nimport type { WhatsAppSendResult } from \"../../backend-types.js\";\nimport { mapWhatsAppCloudError } from \"../../errors.js\";\nimport type {\n MetaErrorEnvelope,\n MetaMarkReadRequest,\n MetaSendResponse,\n MetaSendTextRequest,\n} from \"./types.js\";\n\ninterface WhatsAppCloudClientOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudClient {\n private readonly fetchImpl: typeof fetch;\n private readonly baseUrl: string;\n\n constructor(private readonly opts: WhatsAppCloudClientOptions) {\n this.fetchImpl = opts.fetch ?? fetch;\n const apiVersion = opts.apiVersion ?? \"v18.0\";\n this.baseUrl = `https://graph.facebook.com/${apiVersion}/${opts.phoneNumberId}`;\n }\n\n /** Send a text message. v1 scope — no media (D286 deferred). */\n async sendText(to: string, body: string, isGroup: boolean): Promise<WhatsAppSendResult> {\n const req: MetaSendTextRequest = isGroup\n ? {\n messaging_product: \"whatsapp\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n }\n : {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n };\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(req),\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as MetaErrorEnvelope | unknown;\n return { ok: false, error: mapWhatsAppCloudError(response.status, errBody) };\n }\n\n const data = (await response.json()) as MetaSendResponse;\n const wamid = data.messages?.[0]?.id;\n if (wamid === undefined) {\n return { ok: false, error: { code: \"unknown\", message: \"Meta returned no wamid.\" } };\n }\n return { ok: true, wamid };\n }\n\n /** Mark an inbound message as read (status receipt back to user). */\n async markAsRead(wamid: string): Promise<boolean> {\n const body: MetaMarkReadRequest = {\n messaging_product: \"whatsapp\",\n status: \"read\",\n message_id: wamid,\n };\n try {\n const response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","/**\n * Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).\n *\n * Two boundaries:\n * 1. GET handshake — `verifyWebhookSubscription` (EC-1).\n * 2. POST callbacks — `verifyWebhookSignature` (EC-3 length guard) +\n * `normalizeInboundMessages` (EC-4 text-only filter) +\n * `normalizeStatusReceipts`.\n *\n * The user owns the HTTP route; we expose pure helpers they call from inside it.\n *\n * @public\n */\n\nimport * as crypto from \"node:crypto\";\n\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"../../backend-types.js\";\nimport type { MetaIncomingMessage, MetaStatusUpdate, MetaWebhookEnvelope } from \"./types.js\";\n\nconst warnedNonTextTypes = new Set<string>();\n\n/**\n * Verify Meta's GET `/webhook?hub.mode=subscribe&hub.challenge=...&hub.verify_token=...`\n * handshake (EC-1 absorbed).\n *\n * @returns `query[\"hub.challenge\"]` when valid, `null` otherwise. The caller\n * echoes the challenge as `text/plain` on success.\n */\nexport function verifyWebhookSubscription(\n query: Record<string, string | undefined>,\n expectedVerifyToken: string,\n): string | null {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (mode !== \"subscribe\") return null;\n if (token === undefined || token !== expectedVerifyToken) return null;\n if (challenge === undefined || challenge.length === 0) return null;\n return challenge;\n}\n\n/**\n * Verify the `X-Hub-Signature-256` HMAC-SHA256 against the app secret (D312).\n *\n * EC-3 absorbed: length-guard BEFORE `timingSafeEqual` so a malformed header\n * (e.g. `sha256=ab`) returns `false` instead of throwing `RangeError` (DoS).\n *\n * @returns `true` iff the signature matches.\n */\nexport function verifyWebhookSignature(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n appSecret: string,\n): boolean {\n if (signatureHeader === undefined) return false;\n if (!signatureHeader.startsWith(\"sha256=\")) return false;\n const receivedHex = signatureHeader.slice(7);\n if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;\n const received = Buffer.from(receivedHex, \"hex\");\n const body = typeof rawBody === \"string\" ? Buffer.from(rawBody, \"utf8\") : rawBody;\n const expected = crypto.createHmac(\"sha256\", appSecret).update(body).digest();\n // EC-3: length guard before timingSafeEqual.\n if (received.length !== expected.length) return false;\n return crypto.timingSafeEqual(received, expected);\n}\n\n/** Parse the raw JSON payload into a typed envelope. Returns `null` if shape is unrecognized. */\nexport function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null {\n if (json === null || typeof json !== \"object\") return null;\n const env = json as MetaWebhookEnvelope;\n if (env.object === undefined || !Array.isArray(env.entry)) return null;\n return env;\n}\n\n/**\n * Normalize inbound messages → `WhatsAppInboundEvent[]`.\n *\n * EC-4 absorbed: filters `message.type !== \"text\"` (v1 text-only). Non-text\n * types emit a one-shot stderr warn per type.\n */\nfunction buildContactMap(\n value: NonNullable<MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number][\"value\"]>,\n): Map<string, string | undefined> {\n const map = new Map<string, string | undefined>();\n for (const c of value.contacts ?? []) map.set(c.wa_id, c.profile?.name);\n return map;\n}\n\nfunction processChange(\n change: MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number],\n out: WhatsAppInboundEvent[],\n): void {\n const value = change.value;\n if (value === undefined || value === null) return;\n const phoneNumberId = value.metadata?.phone_number_id;\n const contactByWaId = buildContactMap(value);\n for (const msg of value.messages ?? []) {\n const normalized = normalizeOneMessage(msg, phoneNumberId, contactByWaId);\n if (normalized !== null) out.push(normalized);\n }\n}\n\nexport function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[] {\n const out: WhatsAppInboundEvent[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) processChange(change, out);\n }\n return out;\n}\n\nfunction normalizeOneMessage(\n msg: MetaIncomingMessage,\n phoneNumberId: string | undefined,\n contactByWaId: Map<string, string | undefined>,\n): WhatsAppInboundEvent | null {\n // EC-4: text-only in v1.\n if (msg.type !== \"text\") {\n if (!warnedNonTextTypes.has(msg.type)) {\n warnedNonTextTypes.add(msg.type);\n process.stderr.write(\n `[whatsapp] ignoring ${msg.type} message — v1 text-only (will be supported in v0.2+).\\n`,\n );\n }\n return null;\n }\n const body = msg.text?.body ?? \"\";\n // Cloud API doesn't distinguish DM vs group at the message level — `from`\n // is the sender. We don't have a reliable group-detection signal in cloud\n // (groups need a different webhook subscription). v1 treats all inbound\n // as DM. If the user enables group webhooks, the `conversationType` heuristic\n // here is a future-extension point.\n return {\n wamid: msg.id,\n fromPhone: msg.from,\n phoneNumberId,\n contactName: contactByWaId.get(msg.from),\n conversationType: \"dm\",\n channelId: msg.from,\n text: body,\n receivedAt: Number(msg.timestamp) * 1000 || Date.now(),\n backend: \"cloud\",\n raw: msg,\n };\n}\n\n/** Normalize status updates → `WhatsAppStatusReceipt[]`. */\nexport function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[] {\n const out: WhatsAppStatusReceipt[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) {\n const statuses = change.value?.statuses ?? [];\n for (const s of statuses) {\n out.push(metaStatusToReceipt(s));\n }\n }\n }\n return out;\n}\n\nfunction metaStatusToReceipt(s: MetaStatusUpdate): WhatsAppStatusReceipt {\n return {\n wamid: s.id,\n status: s.status,\n recipient: s.recipient_id,\n timestamp: Number(s.timestamp) * 1000 || Date.now(),\n };\n}\n\n/** @internal — test seam to reset the one-shot warn de-dup. */\nexport function __resetNonTextWarnings(): void {\n warnedNonTextTypes.clear();\n}\n","/**\n * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).\n *\n * `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only\n * inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound\n * dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`\n * from inside their HTTP route.\n *\n * @public\n */\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { WhatsAppCloudClient } from \"./client.js\";\nimport {\n normalizeInboundMessages,\n normalizeStatusReceipts,\n parseWebhookPayload,\n verifyWebhookSignature,\n} from \"./webhook.js\";\n\nexport interface WhatsAppCloudBackendOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly appSecret: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudBackend implements WhatsAppBackend {\n readonly kind = \"cloud\" as const;\n private readonly client: WhatsAppCloudClient;\n private readonly appSecret: string;\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n constructor(opts: WhatsAppCloudBackendOptions) {\n this.client = new WhatsAppCloudClient({\n accessToken: opts.accessToken,\n phoneNumberId: opts.phoneNumberId,\n apiVersion: opts.apiVersion,\n ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),\n });\n this.appSecret = opts.appSecret;\n }\n\n // Cloud has no persistent connection — webhook is push, send is HTTP.\n async connect(): Promise<boolean> {\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n return this.client.sendText(message.to, message.text, message.isGroup);\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n this.statusHandler = undefined;\n };\n }\n\n /**\n * Webhook entrypoint. The user calls this from inside their POST /webhook\n * route after `verifyWebhookSubscription` on GET.\n *\n * @returns `true` if signature valid + dispatched (or empty payload).\n * `false` if signature invalid (route should return 401).\n */\n async handleWebhookPayload(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n ): Promise<boolean> {\n if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {\n return false;\n }\n const json = JSON.parse(\n typeof rawBody === \"string\" ? rawBody : rawBody.toString(\"utf8\"),\n ) as unknown;\n const envelope = parseWebhookPayload(json);\n if (envelope === null) return true; // valid signature, unrecognized shape — nothing to dispatch\n const inbounds = normalizeInboundMessages(envelope);\n for (const event of inbounds) {\n if (this.inboundHandler !== undefined) {\n await this.inboundHandler(event);\n }\n }\n const statuses = normalizeStatusReceipts(envelope);\n for (const receipt of statuses) {\n if (this.statusHandler !== undefined) {\n await this.statusHandler(receipt);\n }\n }\n return true;\n }\n}\n","/**\n * IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.\n *\n * Wire: stdin/stdout JSON-lines (each message terminated by `\\n`).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — see `backend-types.ts` for rationale.\n *\n * @knipignore\n */\nexport const __ipcMarker: unique symbol = Symbol(\"ipc\");\n\n/** Commands the adapter sends to the bridge. */\nexport type IpcCommand =\n | { readonly cmd: \"send\"; readonly msgId: string; readonly to: string; readonly text: string }\n | { readonly cmd: \"shutdown\" };\n\n/** Events the bridge emits to the adapter. */\nexport type IpcEvent =\n | { readonly event: \"ready\"; readonly botPhone: string }\n | {\n readonly event: \"message\";\n readonly msgId: string;\n readonly from: string;\n readonly body: string;\n readonly isGroup: boolean;\n readonly chatId: string;\n readonly contactName?: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"send_ack\";\n readonly msgId: string;\n readonly success: boolean;\n readonly wamid?: string;\n readonly error?: string;\n }\n | {\n readonly event: \"status\";\n readonly msgId: string;\n readonly status: \"sent\" | \"delivered\" | \"read\" | \"failed\";\n readonly recipient: string;\n readonly timestamp: number;\n }\n | { readonly event: \"error\"; readonly message: string };\n\n/** Parse one JSON-line. Returns null on malformed. */\nexport function parseEvent(line: string): IpcEvent | null {\n if (line.length === 0) return null;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return null;\n if (typeof (parsed as { event?: unknown }).event !== \"string\") return null;\n return parsed as IpcEvent;\n } catch {\n return null;\n }\n}\n\n/** Format an outbound command as JSON + newline. */\nexport function formatCommand(cmd: IpcCommand): string {\n return `${JSON.stringify(cmd)}\\n`;\n}\n\n/**\n * Line buffer — accumulates stdout chunks until `\\n` boundaries, yields\n * complete lines. Addresses EC-11 (chunked stdout across multiple reads).\n */\nexport class LineBuffer {\n private buffer = \"\";\n\n push(chunk: string): string[] {\n this.buffer += chunk;\n const out: string[] = [];\n let idx = this.buffer.indexOf(\"\\n\");\n while (idx !== -1) {\n out.push(this.buffer.slice(0, idx));\n this.buffer = this.buffer.slice(idx + 1);\n idx = this.buffer.indexOf(\"\\n\");\n }\n return out;\n }\n\n /** Test seam — current pending bytes. */\n get pending(): string {\n return this.buffer;\n }\n}\n","/**\n * Bridge subprocess lifecycle (ADR D305, D313). PID file lock + stale-process\n * cleanup. EC-5 absorbed: verifies cmdline before killing (otherwise we may\n * kill an unrelated process the OS recycled the PID for).\n *\n * @internal\n */\n\nimport { type ChildProcess, execSync, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** Marker substring our bridge process MUST carry in its argv (EC-5). */\nexport const BRIDGE_PROCESS_TAG = \"whatsapp-web-bridge\";\n\ninterface SpawnBridgeOptions {\n readonly sessionId: string;\n readonly bridgeScriptPath: string;\n readonly theokitHome?: string;\n}\n\nexport interface BridgeHandle {\n readonly child: ChildProcess;\n readonly pidFilePath: string;\n}\n\nfunction pidFilePath(theokitHome: string, sessionId: string): string {\n return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);\n}\n\nfunction defaultTheokitHome(): string {\n return process.env.THEOKIT_HOME ?? path.join(process.env.HOME ?? \"/tmp\", \".theokit\");\n}\n\n/**\n * Verify whether `pid` belongs to a process whose argv contains our tag (EC-5).\n *\n * Without this guard, OS may have recycled the PID to e.g. `vim` and our\n * cleanup would terminate the user's editor.\n *\n * @internal\n */\nexport function pidBelongsToOurBridge(pid: number): boolean {\n try {\n // Linux: /proc/<pid>/cmdline (NUL-separated argv).\n const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, \"utf8\");\n return cmdline.includes(BRIDGE_PROCESS_TAG);\n } catch {\n // macOS / BSD fallback: ps -p <pid> -o args=\n try {\n const out = execSync(`ps -p ${pid} -o args=`, {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).toString();\n return out.includes(BRIDGE_PROCESS_TAG);\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Acquire the PID lock for a session — kill any stale bridge (cmdline-verified),\n * then return the lock-file path (caller writes its own PID after spawn).\n */\n/** EC-5: kill `stalePid` ONLY if cmdline confirms ownership. */\nfunction killIfOurBridge(stalePid: number): void {\n if (!Number.isFinite(stalePid) || stalePid <= 0) return;\n if (!pidBelongsToOurBridge(stalePid)) return;\n try {\n process.kill(stalePid, \"SIGTERM\");\n } catch {\n // Process already gone — fine.\n }\n}\n\nfunction cleanupStaleLock(lockFile: string): void {\n const raw = fs.readFileSync(lockFile, \"utf8\").trim();\n killIfOurBridge(Number.parseInt(raw, 10));\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nexport function acquirePidLock(sessionId: string, theokitHome?: string): string {\n const home = theokitHome ?? defaultTheokitHome();\n fs.mkdirSync(home, { recursive: true });\n const lockFile = pidFilePath(home, sessionId);\n if (fs.existsSync(lockFile)) cleanupStaleLock(lockFile);\n return lockFile;\n}\n\n/** Spawn the bridge subprocess, write PID file. */\nexport function spawnBridge(opts: SpawnBridgeOptions): BridgeHandle {\n const home = opts.theokitHome ?? defaultTheokitHome();\n const lockFile = acquirePidLock(opts.sessionId, home);\n\n const child = spawn(\n \"node\",\n [opts.bridgeScriptPath, \"--tag\", BRIDGE_PROCESS_TAG, \"--session\", opts.sessionId],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: false,\n },\n );\n\n if (child.pid !== undefined) {\n fs.writeFileSync(lockFile, String(child.pid), { mode: 0o600 });\n }\n\n // EC-12: pipe stderr so the buffer never fills.\n if (child.stderr !== null) {\n child.stderr.pipe(process.stderr);\n }\n\n return { child, pidFilePath: lockFile };\n}\n\n/** Terminate the bridge: SIGTERM → wait 3s → SIGKILL. Removes PID file. */\nexport async function terminateBridge(handle: BridgeHandle): Promise<void> {\n const { child, pidFilePath: lockFile } = handle;\n if (child.pid !== undefined && !child.killed) {\n try {\n child.kill(\"SIGTERM\");\n } catch {\n /* ignore */\n }\n const exited = await waitForExit(child, 3000);\n if (!exited) {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* ignore */\n }\n await waitForExit(child, 1000);\n }\n }\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) {\n resolve(true);\n return;\n }\n let resolved = false;\n const onExit = () => {\n if (resolved) return;\n resolved = true;\n resolve(true);\n };\n child.once(\"exit\", onExit);\n setTimeout(() => {\n if (resolved) return;\n resolved = true;\n child.removeListener(\"exit\", onExit);\n resolve(false);\n }, timeoutMs).unref();\n });\n}\n","/**\n * `WhatsAppWebBackend` — `whatsapp-web.js` subprocess bridge backend (ADR D305).\n *\n * Lifecycle (T3.1) + IPC (T3.2) wired behind the `WhatsAppBackend` interface.\n * EC-6 absorbed: `connect()` races against a 120s timeout so unattended QR\n * pairings fail fast instead of hanging the app.\n *\n * @public\n */\n\nimport * as path from \"node:path\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { mapWhatsAppWebError, WhatsAppConnectTimeoutError } from \"../../errors.js\";\nimport { formatCommand, type IpcEvent, LineBuffer, parseEvent } from \"./ipc.js\";\nimport { type BridgeHandle, spawnBridge, terminateBridge } from \"./lifecycle.js\";\n\nexport interface WhatsAppWebBackendOptions {\n readonly sessionId: string;\n /** Override the default bridge script path. Defaults to bundled script. */\n readonly bridgeScriptPath?: string;\n /** EC-6 connect timeout in ms. Default 120000. */\n readonly connectTimeoutMs?: number;\n /** Per-send timeout in ms. Default 30000. */\n readonly sendTimeoutMs?: number;\n /** Test seam: override the spawned child via a factory. */\n readonly spawnFactory?: () => BridgeHandle;\n /** Test seam: theokit home for PID locks. */\n readonly theokitHome?: string;\n}\n\ninterface PendingSend {\n readonly resolve: (r: WhatsAppSendResult) => void;\n readonly timer: NodeJS.Timeout;\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 120_000;\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\nexport class WhatsAppWebBackend implements WhatsAppBackend {\n readonly kind = \"web\" as const;\n private handle?: BridgeHandle;\n private readonly buffer = new LineBuffer();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n private readonly pending = new Map<string, PendingSend>();\n private msgIdCounter = 0;\n private botPhone?: string;\n private connected = false;\n // EC-6: emitter resolvers for `event: \"ready\"`.\n private readyResolvers: Array<(phone: string) => void> = [];\n\n constructor(private readonly opts: WhatsAppWebBackendOptions) {}\n\n private spawnBridgeHandle(): NonNullable<typeof this.handle> {\n return this.opts.spawnFactory\n ? this.opts.spawnFactory()\n : spawnBridge({\n sessionId: this.opts.sessionId,\n bridgeScriptPath: this.opts.bridgeScriptPath ?? defaultBridgeScriptPath(),\n ...(this.opts.theokitHome !== undefined ? { theokitHome: this.opts.theokitHome } : {}),\n });\n }\n\n private wireStdout(): void {\n if (this.handle?.child.stdout === null || this.handle === undefined) return;\n this.handle.child.stdout.setEncoding(\"utf8\");\n this.handle.child.stdout.on(\"data\", (chunk: string) => {\n for (const line of this.buffer.push(chunk)) {\n const event = parseEvent(line);\n if (event !== null) this.dispatch(event);\n }\n });\n }\n\n private async cleanupHandle(): Promise<void> {\n if (this.handle === undefined) return;\n await terminateBridge(this.handle).catch(() => {});\n this.handle = undefined;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.handle = this.spawnBridgeHandle();\n this.wireStdout();\n\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const ready = new Promise<string>((resolve) => this.readyResolvers.push(resolve));\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n const phone = await Promise.race([ready, timeout]);\n if (timer !== undefined) clearTimeout(timer);\n this.botPhone = phone;\n this.connected = true;\n return true;\n } catch (err) {\n if (timer !== undefined) clearTimeout(timer);\n await this.cleanupHandle();\n throw err;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected || this.handle === undefined) return;\n try {\n if (this.handle.child.stdin !== null && !this.handle.child.stdin.destroyed) {\n this.handle.child.stdin.write(formatCommand({ cmd: \"shutdown\" }));\n }\n } catch {\n /* ignore */\n }\n await terminateBridge(this.handle);\n this.handle = undefined;\n this.connected = false;\n // Reject any pending sends.\n for (const [_, p] of this.pending) {\n clearTimeout(p.timer);\n p.resolve({ ok: false, error: { code: \"server_error\", message: \"Bridge disconnected.\" } });\n }\n this.pending.clear();\n this.readyResolvers = [];\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n if (!this.connected || this.handle === undefined || this.handle.child.stdin === null) {\n return { ok: false, error: { code: \"server_error\", message: \"Bridge not connected.\" } };\n }\n const msgId = `out-${++this.msgIdCounter}`;\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n return new Promise<WhatsAppSendResult>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: { code: \"timeout\", message: `Bridge send timed out after ${timeoutMs}ms.` },\n });\n }, timeoutMs);\n this.pending.set(msgId, { resolve, timer });\n try {\n this.handle!.child.stdin!.write(\n formatCommand({ cmd: \"send\", msgId, to: message.to, text: message.text }),\n );\n } catch (err) {\n clearTimeout(timer);\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: mapWhatsAppWebError(err instanceof Error ? err.message : String(err)),\n });\n }\n });\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n this.statusHandler = undefined;\n };\n }\n\n private handleReady(event: Extract<IpcEvent, { event: \"ready\" }>): void {\n for (const r of this.readyResolvers) r(event.botPhone);\n this.readyResolvers = [];\n }\n\n private handleMessage(event: Extract<IpcEvent, { event: \"message\" }>): void {\n if (this.inboundHandler === undefined) return;\n const normalized: WhatsAppInboundEvent = {\n wamid: event.msgId,\n fromPhone: event.from,\n contactName: event.contactName,\n conversationType: event.isGroup ? \"group\" : \"dm\",\n channelId: event.chatId,\n text: event.body,\n receivedAt: event.timestamp || Date.now(),\n backend: \"web\",\n raw: event,\n };\n void this.inboundHandler(normalized);\n }\n\n private handleSendAck(event: Extract<IpcEvent, { event: \"send_ack\" }>): void {\n const pending = this.pending.get(event.msgId);\n if (pending === undefined) return;\n this.pending.delete(event.msgId);\n clearTimeout(pending.timer);\n if (event.success) {\n pending.resolve(event.wamid !== undefined ? { ok: true, wamid: event.wamid } : { ok: true });\n } else {\n pending.resolve({ ok: false, error: mapWhatsAppWebError(event.error) });\n }\n }\n\n private handleStatus(event: Extract<IpcEvent, { event: \"status\" }>): void {\n if (this.statusHandler === undefined) return;\n void this.statusHandler({\n wamid: event.msgId,\n status: event.status,\n recipient: event.recipient,\n timestamp: event.timestamp || Date.now(),\n });\n }\n\n private dispatch(event: IpcEvent): void {\n switch (event.event) {\n case \"ready\":\n this.handleReady(event);\n return;\n case \"message\":\n this.handleMessage(event);\n return;\n case \"send_ack\":\n this.handleSendAck(event);\n return;\n case \"status\":\n this.handleStatus(event);\n return;\n case \"error\":\n process.stderr.write(`[whatsapp-web bridge] ${event.message}\\n`);\n return;\n }\n }\n}\n\nfunction defaultBridgeScriptPath(): string {\n // Points to the bundled script at `dist/bridge/whatsapp-web-bridge.mjs` once\n // the build copies it. Until then, callers can pass `bridgeScriptPath` directly.\n return path.resolve(\n path.dirname(new URL(import.meta.url).pathname),\n \"../../bridge/whatsapp-web-bridge.mjs\",\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/allowlist.ts","../src/backend/baileys/normalize.ts","../src/errors.ts","../src/backend/baileys/socket.ts","../src/backend/baileys/index.ts","../src/backend/cloud/client.ts","../src/backend/cloud/webhook.ts","../src/backend/cloud/index.ts","../src/backend/web/ipc.ts","../src/backend/web/lifecycle.ts","../src/backend/web/index.ts","../src/split.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","resolve","crypto","path","fs","execSync","spawn","DEFAULT_CONNECT_TIMEOUT_MS","DEFAULT_SEND_TIMEOUT_MS","path2","fileURLToPath","existsSync","chunkText","BasePlatformAdapter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAM,QAAA,GAAW,GAAA;AAcV,SAAS,oBAAoB,KAAA,EAAuB;AACzD,EAAA,MAAM,aAAA,GAAgB,KAAA,CAAM,OAAA,CAAQ,aAAA,EAAe,EAAE,CAAA;AACrD,EAAA,MAAM,aAAA,GAAgB,aAAA,CAAc,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AACtD,EAAA,OAAO,aAAA,CAAc,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACxC;AASO,SAAS,oBAAoB,GAAA,EAA8C;AAChF,EAAA,MAAM,OAAA,GAAA,CAAW,GAAA,IAAO,EAAA,EACrB,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAI,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,EAAM,CAAA,CAC3B,GAAA,CAAI,CAAC,KAAA,KAAW,KAAA,KAAU,QAAA,GAAW,QAAA,GAAW,mBAAA,CAAo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AA,CAAK,WAAA,CAAY,SAAA,CAAU,OAAO,OAAA,KAAY;AACxD,MAAA,IAAI,CAAC,KAAK,OAAA,EAAS;AACnB,MAAA,IAAI,IAAA,CAAK,0BAAA,CAA2B,OAAO,CAAA,EAAG;AAC9C,MAAA,IAAI,IAAA,CAAK,sBAAA,CAAuB,OAAO,CAAA,EAAG;AAC1C,MAAA,MAAM,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,cAAA,CAAe,OAAO,CAAC,CAAA;AAAA,IACjD,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,kBAAA,GAAqB,GAAA;AAE1B,IAAA,OAAO,MAAM;AAOX,MAAA,IAAI,IAAA,CAAK,YAAY,OAAA,EAAS;AAC5B,QAAA,IAAA,CAAK,OAAA,GAAU,MAAA;AACf,QAAA,GAAA,EAAI;AACJ,QAAA,IAAA,CAAK,kBAAA,GAAqB,MAAA;AAAA,MAC5B;AAAA,IACF,CAAA;AAAA,EACF;AAAA;AAAA,EAGA,gBAAgB,OAAA,EAAwE;AACtF,IAAA,IAAA,CAAK,iBAAA,IAAoB;AACzB,IAAA,IAAA,CAAK,aAAA,GAAgB,OAAA;AACrB,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,WAAA,CAAY,eAAA,CAAgB,OAAO,CAAA,KAAM;AACxD,MAAA,MAAM,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAAA,IAC9B,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,iBAAA,GAAoB,GAAA;AACzB,IAAA,OAAO,MAAM;AAEX,MAAA,IAAI,IAAA,CAAK,kBAAkB,OAAA,EAAS;AAClC,QAAA,IAAA,CAAK,aAAA,GAAgB,MAAA;AACrB,QAAA,GAAA,EAAI;AACJ,QAAA,IAAA,CAAK,iBAAA,GAAoB,MAAA;AAAA,MAC3B;AAAA,IACF,CAAA;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Who is allowed to reach the handler — a fail-closed sender allowlist.\n *\n * Until this existed the package had no sender filter. `shouldDropGroupMessage` fires only for\n * *groups* with `requireMention`, so any stranger who sent a direct message reached the agent.\n *\n * That is two problems wearing one coat. A number that answers strangers accumulates blocks and\n * reports, which is what WhatsApp's enforcement runs on — so an open gateway is a slow route to a\n * banned number. And an agent wired to tools acts on what arrives, so an unfiltered inbound is an\n * instruction channel for anyone who knows the number. Baileys' own `GHSA-qvv5-jq5g-4cgg` — a\n * crafted `protocolMessage` that forges a `messages.upsert` — is the same hazard reached through\n * the library rather than through the phone, and an allowlist narrows both.\n *\n * Pure by construction: no socket, no I/O, no clock. The decision is the part worth testing, and\n * it can be tested exhaustively without a phone number, which the transport around it cannot.\n *\n * @public\n */\n\n/** Allows every identified sender. Must be set deliberately; it is never the default. */\nconst WILDCARD = \"*\";\n\n/**\n * Reduce a WhatsApp identifier to the digits that identify the account.\n *\n * WhatsApp addresses carry two things that are not part of the number: a device suffix\n * (`:12`) and a domain (`@s.whatsapp.net`, `@g.us`, `@lid`). Stripping non-digits without\n * removing the suffix first merges the device id into the number —\n * `5511999999999:12@s.whatsapp.net` becomes `551199999999912`, which matches no allowlist entry,\n * so the filter silently stops recognising that sender the moment they use a second device.\n *\n * Returns `\"\"` when the input carries no identifier at all. Callers must treat that as\n * unidentified, never as a match.\n */\nexport function normalizeWhatsAppId(value: string): string {\n const withoutDevice = value.replace(/:[^@]*(?=@)/, \"\");\n const withoutDomain = withoutDevice.replace(/@.*$/, \"\");\n return withoutDomain.replace(/\\D/g, \"\");\n}\n\n/**\n * Parse a comma-separated allowlist into normalised entries.\n *\n * Blank entries are dropped rather than kept: an empty string is what an unreadable identifier\n * normalises to, so admitting `\"\"` to the set would admit precisely the senders whose id could\n * not be read. The wildcard is preserved verbatim, since normalising it would erase it.\n */\nexport function parseAllowedSenders(raw: string | undefined): ReadonlySet<string> {\n const entries = (raw ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim())\n .map((entry) => (entry === WILDCARD ? WILDCARD : normalizeWhatsAppId(entry)))\n .filter((entry) => entry.length > 0);\n return new Set(entries);\n}\n\n/**\n * May `senderId` reach the handler?\n *\n * **Fail-closed.** An empty allowlist admits nobody. An operator who has not configured one has\n * not decided who may drive the agent, and the safe reading of \"has not decided\" is \"not yet\" —\n * not \"everyone\". The inverse default is a mistake worth naming: it makes the safest-looking\n * configuration, the empty one, the most open.\n *\n * An unidentifiable sender is refused even under the wildcard. `*` means \"any sender\", and\n * something whose sender cannot be named is not a sender; letting it through would make the\n * wildcard the single path that skips identification altogether.\n */\nexport function isSenderAllowed(senderId: string, allowed: ReadonlySet<string>): boolean {\n const normalized = normalizeWhatsAppId(senderId);\n if (normalized.length === 0) return false;\n if (allowed.size === 0) return false;\n if (allowed.has(WILDCARD)) return true;\n return allowed.has(normalized);\n}\n","/**\n * Baileys envelope → `WhatsAppInboundEvent`. Pure: no socket, no clock, no I/O.\n *\n * Purity is the point rather than a preference. Nothing in this repository can exercise the\n * WhatsApp protocol — pairing needs a human with a phone — so the only part of this backend\n * that can be tested exhaustively is the part that does not touch the network. Every decision\n * that can live here does.\n *\n * It returns `undefined` rather than throwing for anything it will not accept. The input\n * arrives straight off a socket from a library that has shipped a message-spoofing advisory\n * (`GHSA-qvv5-jq5g-4cgg`), so a malformed or hostile envelope is an expected case, not an\n * exceptional one — and a throw here would take down whatever is dispatching.\n *\n * @internal\n */\n\nimport { normalizeWhatsAppId } from \"../../allowlist.js\";\nimport type { WhatsAppInboundEvent } from \"../../backend-types.js\";\n\n/** WhatsApp's status feed. Never a conversation, always noise for a bot. */\nconst STATUS_BROADCAST_JID = \"status@broadcast\";\n\n/** Envelopes that carry the real message one level down. */\nconst WRAPPER_KEYS = [\n \"ephemeralMessage\",\n \"viewOnceMessage\",\n \"viewOnceMessageV2\",\n \"documentWithCaptionMessage\",\n] as const;\n\n/** How deep to follow nested wrappers before giving up. Hostile input must not recurse forever. */\nconst MAX_WRAPPER_DEPTH = 3;\n\n/** The subset of a Baileys `WAMessage` this normaliser reads. */\ninterface RawEnvelope {\n key?: {\n remoteJid?: unknown;\n participant?: unknown;\n fromMe?: unknown;\n id?: unknown;\n };\n message?: Record<string, unknown>;\n messageTimestamp?: unknown;\n pushName?: unknown;\n}\n\n/** Narrow an unknown to an object without asserting anything about its members. */\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** A non-empty string, or undefined. */\nfunction asText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The plain text of a message, from either shape Baileys uses.\n *\n * `conversation` carries a bare message; `extendedTextMessage` carries one with context — a\n * reply, a link preview, a mention. v1 is text-only, like the two sibling backends, so any\n * other content type yields undefined and the message is dropped.\n */\nfunction extractText(message: Record<string, unknown> | undefined, depth = 0): string | undefined {\n if (message === undefined || depth > MAX_WRAPPER_DEPTH) return undefined;\n\n const direct = asText(message.conversation);\n if (direct !== undefined) return direct;\n\n const extended = asObject(message.extendedTextMessage);\n const fromExtended = extended === undefined ? undefined : asText(extended.text);\n if (fromExtended !== undefined) return fromExtended;\n\n // Baileys nests the real message inside a wrapper for disappearing messages and view-once.\n // Without unwrapping, every text sent in a chat with disappearing messages turned on was\n // dropped in silence — indistinguishable from an image, which the \"v1 is text-only\"\n // rationale was covering for.\n for (const wrapper of WRAPPER_KEYS) {\n const inner = asObject(message[wrapper]);\n const nested = inner === undefined ? undefined : asObject(inner.message);\n const text = extractText(nested, depth + 1);\n if (text !== undefined) return text;\n }\n return undefined;\n}\n\n/**\n * The message's timestamp in seconds, or `undefined` when it cannot be read.\n *\n * Baileys reports seconds; every other backend here reports milliseconds, which is why the\n * caller multiplies.\n *\n * Returning `undefined` — which makes the caller drop the envelope — is this module's uniform\n * contract, not a special rule: it refuses anything it cannot fully read, exactly as it refuses\n * an unidentifiable sender or a non-text body. An earlier version of this comment justified the\n * drop by a \"freshness window\" that would reject stale messages. **No such window exists** —\n * `receivedAt` is declared in `@theokit/gateway` and read by nothing. A review caught the claim.\n * The replay defence in this backend is the `type !== \"notify\"` filter on `messages.upsert`.\n *\n * Worth knowing when comparing backends: `backend/cloud/webhook.ts` takes the opposite branch,\n * substituting the current time for an unreadable stamp. Neither is wrong given that nobody\n * reads the field; they are inconsistent, and that is recorded rather than quietly aligned.\n */\nfunction toSeconds(timestamp: unknown): number | undefined {\n if (typeof timestamp === \"number\") return timestamp;\n if (typeof timestamp === \"string\") {\n const parsed = Number(timestamp);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n // Baileys' generated protobuf types permit a `Long`. Read as unparseable, a perfectly good\n // message from a real user would be dropped for a field nobody reads — so the shape is\n // handled rather than refused.\n const asLong = asObject(timestamp);\n if (asLong !== undefined && typeof asLong.toNumber === \"function\") {\n const parsed = (asLong.toNumber as () => unknown)();\n return typeof parsed === \"number\" && Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n}\n\n/**\n * Who sent this, and where does it belong?\n *\n * In a group the channel is the group and the sender is the participant; in a DM both are\n * `remoteJid`. Reading `remoteJid` as the sender in a group would attribute every group\n * message to the group itself, which breaks the allowlist and any per-sender session key at\n * once. Returns `undefined` when either cannot be identified — and \"we do not know who sent\n * this\" must never resolve to \"let it through\".\n */\nfunction resolveParties(\n key: Record<string, unknown>,\n remoteJid: string,\n): { fromPhone: string; channelId: string; isGroup: boolean } | undefined {\n const isGroup = remoteJid.endsWith(\"@g.us\");\n const senderJid = isGroup ? asText(key.participant) : remoteJid;\n if (senderJid === undefined) return undefined;\n\n const fromPhone = normalizeWhatsAppId(senderJid);\n const channelId = normalizeWhatsAppId(remoteJid);\n if (fromPhone.length === 0 || channelId.length === 0) return undefined;\n return { fromPhone, channelId, isGroup };\n}\n\n/**\n * Should this envelope reach a handler at all?\n *\n * Refused: anything we sent (or the bot answers its own replies, forever — a lesson every\n * backend in this package learned separately), and the status feed, which is never a\n * conversation.\n */\nfunction isDispatchable(key: Record<string, unknown>, remoteJid: string): boolean {\n if (key.fromMe === true) return false;\n return remoteJid !== STATUS_BROADCAST_JID;\n}\n\n/**\n * Normalise one inbound envelope, or refuse it.\n *\n * Refused: anything we sent (`fromMe`), the status feed, any content that is not text, and\n * anything whose sender cannot be identified. That last one matters most — an event with an\n * unidentifiable sender would reach an allowlist with nothing to match against, and the safe\n * reading of \"we do not know who sent this\" is not \"let it through\".\n */\nexport function normalizeBaileysMessage(raw: unknown): WhatsAppInboundEvent | undefined {\n const envelope = asObject(raw) as RawEnvelope | undefined;\n const key = envelope === undefined ? undefined : asObject(envelope.key);\n if (key === undefined) return undefined;\n\n const remoteJid = asText(key.remoteJid);\n const wamid = asText(key.id);\n if (remoteJid === undefined || wamid === undefined) return undefined;\n if (!isDispatchable(key, remoteJid)) return undefined;\n\n const text = extractText(envelope?.message);\n if (text === undefined) return undefined;\n\n const parties = resolveParties(key, remoteJid);\n if (parties === undefined) return undefined;\n\n const seconds = toSeconds(envelope?.messageTimestamp);\n if (seconds === undefined) return undefined;\n\n const contactName = asText(envelope?.pushName);\n\n return {\n wamid,\n fromPhone: parties.fromPhone,\n conversationType: parties.isGroup ? \"group\" : \"dm\",\n channelId: parties.channelId,\n text,\n receivedAt: seconds * 1_000,\n backend: \"baileys\",\n raw,\n ...(contactName !== undefined ? { contactName } : {}),\n };\n}\n","/**\n * Per-backend HTTP/IPC error → canonical `WhatsAppSendResult.error` shape.\n *\n * Cloud follows Meta error codes (https://developers.facebook.com/docs/graph-api/guides/error-handling).\n * Web follows whatsapp-web.js error strings.\n *\n * @internal\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\nimport type { WhatsAppError, WhatsAppSendResult } from \"./backend-types.js\";\n\ntype ErrorPayload = Required<WhatsAppSendResult>[\"error\"];\n\ninterface MetaErrorBody {\n error?: {\n code?: number;\n message?: string;\n error_subcode?: number;\n };\n}\n\n/**\n * Public input shape for the {@link ConfigurationError} constructor.\n *\n * Aliased from the core rather than redeclared. The base type exists precisely so every\n * adapter stops writing its own copy of the same three fields, and a redeclaration means a\n * field added to the core silently never reaches this package. Four siblings alias it the\n * same way.\n */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * A required option is missing or empty.\n *\n * Raised where a consumer hands us configuration — the factories — rather than later, when\n * the value is finally used against the network. A factory that returns an adapter which\n * cannot authenticate has moved the error away from its cause: the stack then names a send,\n * and the mistake was in construction.\n *\n * Matches the shape every sibling adapter uses (`gateway-line`, `gateway-email`, …), which\n * is what makes one `catch (e) { if (e instanceof GatewayConfigurationError) }` work across\n * all of them.\n *\n * @public\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-whatsapp\", opts);\n }\n}\n\n/**\n * The bridge reported, on its own protocol, that it cannot start.\n *\n * Distinct from {@link WhatsAppConnectTimeoutError}, which says only that nothing arrived in\n * time. This one carries what the bridge said — and, when it could classify itself, a\n * machine-readable `code` such as `peer_missing`, `peer_incompatible` or `peer_load_failed`.\n * The difference matters to a caller: a timeout may be worth retrying, and a peer dependency\n * that does not export what we need never will be.\n *\n * @public\n */\nexport class WhatsAppBridgeError extends Error {\n override readonly name = \"WhatsAppBridgeError\";\n /** Cause as named by the bridge, when it could name one. */\n readonly code: string | undefined;\n\n constructor(message: string, code?: string) {\n super(`WhatsApp web bridge could not start: ${message}`);\n this.code = code;\n }\n}\n\n/** Custom error: `connect()` timed out waiting for \"ready\" (EC-6). */\nexport class WhatsAppConnectTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);\n this.name = \"WhatsAppConnectTimeoutError\";\n }\n}\n\n/**\n * Meta's published error codes, by consequence for the caller.\n *\n * These are six-digit codes, and the mapper used to test `errCode === 130 || errCode === 131`\n * — a condition no Cloud API response can satisfy. The rate-limit branch was dead, every real\n * throttle arrived as `invalid_request`, and a consumer's backoff never fired (#46). The unit\n * test that claimed to cover it passed on the HTTP status while feeding a fabricated code.\n *\n * Numbers verified against Meta's error-code table rather than recalled.\n */\nconst RATE_LIMIT_CODES = new Set([\n 4, // the app reached its API call rate limit\n 80007, // the WhatsApp Business Account reached its rate limit\n 130429, // Cloud API message throughput reached\n]);\nconst UNDELIVERABLE_CODES = new Set([\n 130403, // the business has blocked this user\n 131026, // no WhatsApp account, terms not accepted, or an outdated client\n]);\n/** More than 24h since the recipient last replied. Remedy: resend as a template. */\nconst SESSION_WINDOW_EXPIRED_CODE = 131047;\n/**\n * The recipient was never registered against this number. Remedy: a console step, not a payload.\n *\n * Its own code for the same reason 131047 has one — the remedy is specific and different from\n * every other error here. And it is the error most Cloud API integrations meet first: every app\n * starts on a free test number whose recipients must be registered one by one, so a developer\n * whose payload is correct gets told `invalid_request` and goes to re-read the payload.\n */\nconst RECIPIENT_NOT_ALLOWLISTED_CODE = 131030;\n\n/**\n * Which canonical code this failure is, derived from Meta's status and error number.\n *\n * The return type is `WhatsAppError[\"code\"]` rather than a hand-listed union. It WAS hand-listed,\n * and a review caught that: the commit extracting `WhatsAppError` claimed to have removed the\n * second declaration that would \"drift the moment somebody adds a code to one of them\", and left\n * this one — already drifted, missing `timeout`. One vocabulary, one declaration.\n */\nfunction cloudErrorCode(status: number, errCode: number): WhatsAppError[\"code\"] {\n if (errCode === 190 || status === 401) return \"auth_failed\";\n if (RATE_LIMIT_CODES.has(errCode) || status === 429) return \"rate_limit\";\n // Ordered before the generic 400 branch: all three arrive as HTTP 400, and the\n // specific code is the only thing separating \"fix your payload\" from \"send a\n // template\" and from \"this recipient will never receive it\".\n if (errCode === SESSION_WINDOW_EXPIRED_CODE) return \"session_window_expired\";\n if (errCode === RECIPIENT_NOT_ALLOWLISTED_CODE) return \"recipient_not_allowlisted\";\n if (UNDELIVERABLE_CODES.has(errCode)) return \"undeliverable\";\n if (status === 400 || errCode === 100) return \"invalid_request\";\n if (status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\n/**\n * Map a Cloud API HTTP failure into the canonical `{ code, message }` payload.\n *\n * Takes the status alongside the body because Meta returns the same envelope shape for very\n * different faults, and the status is what separates a rejected payload from an expired token.\n */\nexport function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload {\n const parsed = (body !== null && typeof body === \"object\" ? body : {}) as MetaErrorBody;\n const errCode = parsed.error?.code ?? 0;\n const errMsg = parsed.error?.message ?? `HTTP ${status}`;\n const code = cloudErrorCode(status, errCode);\n if (code === \"auth_failed\") return { code, message: `Bearer token rejected: ${errMsg}` };\n if (code === \"rate_limit\") return { code, message: `Throttled: ${errMsg}` };\n if (code === \"recipient_not_allowlisted\") {\n // The remedy travels with the error, like its sibling above. Naming where the list lives is\n // the difference between a one-minute fix and an afternoon spent on a correct payload.\n return {\n code,\n message:\n `Recipient is not on this number's allowed list — register it under the phone number in ` +\n `the app's WhatsApp API setup before sending: ${errMsg}`,\n };\n }\n if (code === \"session_window_expired\") {\n // The remedy travels with the error. A caller reading only the code knows to\n // switch to a template; a human reading a log should not have to look it up.\n return {\n code,\n message: `Outside the 24-hour service window — send an approved template instead: ${errMsg}`,\n };\n }\n return { code, message: errMsg };\n}\n\n/**\n * Map an error string from the `whatsapp-web.js` bridge into the canonical payload.\n *\n * The bridge speaks over IPC and can only send text, so this is the boundary where a line of stderr\n * becomes a structured error. `undefined` maps to an `unknown` code rather than throwing.\n */\nexport function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload {\n const msg = ipcError ?? \"unknown bridge error\";\n if (msg.includes(\"AUTHENTICATION\") || msg.includes(\"UNAUTHORIZED\")) {\n return { code: \"auth_failed\", message: msg };\n }\n if (msg.includes(\"RATE\") || msg.includes(\"THROTTLE\")) {\n return { code: \"rate_limit\", message: msg };\n }\n if (msg.includes(\"PROTOCOL\") || msg.includes(\"DISCONNECT\")) {\n return { code: \"server_error\", message: msg };\n }\n if (msg.includes(\"TIMEOUT\")) {\n return { code: \"timeout\", message: msg };\n }\n return { code: \"unknown\", message: msg };\n}\n","/**\n * The socket contract this backend depends on, and the real factory behind it (ADR D319).\n *\n * Three members, not Baileys' whole `WASocket`. Two things follow, and both are the reason\n * the contract is ours rather than the library's.\n *\n * It was five, and two rounds of review took two members off it, both declared and called by\n * nothing. `logout()` went first and mattered most: on WhatsApp it UNPAIRS the device, the\n * opposite of what `disconnect()` means here, so the next person needing a teardown would find\n * it, call it, and lose the session the whole `sessionDir` exists to keep. `ev.off()` went for\n * the plain reason — nothing removed a listener, because a socket is discarded whole rather\n * than unsubscribed from. Neither was a capability we had; both read as one.\n *\n * **The backend is testable with `baileys` absent.** It is an optional peer dependency, so\n * CI does not install it — and a backend that could only be exercised with the real library\n * installed would be exercised by nothing, which is how the `web` backend reached production\n * unable to start (B-002).\n *\n * **The library stays an implementation detail of this file.** A breaking change upstream\n * lands in one place instead of wherever its types had spread. Depending on all of `WASocket`\n * to call three of its members is the interface-segregation problem stated plainly\n * (`rules/architecture.md`).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/** A Baileys connection-state update, narrowed to what the lifecycle reads. */\nexport interface BaileysConnectionUpdate {\n readonly connection?: \"close\" | \"connecting\" | \"open\";\n readonly qr?: string;\n readonly lastDisconnect?: { readonly error?: unknown };\n}\n\n/** The events this backend subscribes to. Anything else Baileys emits is ignored. */\nexport interface BaileysEventMap {\n \"connection.update\": BaileysConnectionUpdate;\n \"messages.upsert\": { readonly messages: readonly unknown[]; readonly type?: string };\n \"creds.update\": unknown;\n}\n\n/**\n * What this backend needs a socket to be.\n *\n * Deliberately structural: any object with these members satisfies it, which is what lets a\n * test hand over a fake without importing anything from Baileys.\n */\nexport interface BaileysSocketLike {\n readonly ev: {\n on<K extends keyof BaileysEventMap>(\n event: K,\n listener: (payload: BaileysEventMap[K]) => void,\n ): void;\n };\n sendMessage(\n jid: string,\n content: { text: string },\n ): Promise<{ key?: { id?: string } } | undefined>;\n end?(error?: Error): void;\n}\n\n/** How a socket comes into being. Replaced wholesale in tests. */\nexport type BaileysSocketFactory = (opts: BaileysSocketOptions) => Promise<BaileysSocketLike>;\n\n/** What the real factory needs to build a socket. */\nexport interface BaileysSocketOptions {\n /** Directory holding the multi-file auth state — the pairing, persisted. */\n readonly sessionDir: string;\n /** Overrides the module the factory loads. Tests point it at a stub; production never sets it. */\n readonly specifier?: string;\n /**\n * Called with the pairing QR, as often as WhatsApp reissues it.\n *\n * Without somewhere for this to go, a fresh `sessionDir` can only ever time out: there is\n * no other way to pair, and `printQRInTerminal` is off because a library writing to stdout\n * is a library deciding where a host application's output goes. Defaults to writing the\n * code to **stderr**, which is what the `web` bridge does and what keeps stdout free for a\n * host that is using it for something.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/** Shape of the `baileys` module surface this factory uses. */\ninterface BaileysModule {\n makeWASocket?: (config: Record<string, unknown>) => BaileysSocketLike;\n default?: ((config: Record<string, unknown>) => BaileysSocketLike) | BaileysModule;\n useMultiFileAuthState?: (\n dir: string,\n ) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>;\n fetchLatestBaileysVersion?: () => Promise<{ version: unknown }>;\n}\n\n/** Read a member off the default export first, then the namespace. */\nfunction member<T>(mod: BaileysModule, name: keyof BaileysModule): T | undefined {\n const asDefault = mod.default as BaileysModule | undefined;\n const fromDefault =\n asDefault !== undefined && typeof asDefault === \"object\" ? asDefault[name] : undefined;\n return (fromDefault ?? mod[name]) as T | undefined;\n}\n\n/**\n * Build a real Baileys socket.\n *\n * The import shape follows what B-002 cost this repository to learn: read the API off the\n * default export first, check each member is callable, and report a structured error naming\n * the one that is missing. A `try/catch` around the import guards the package being absent,\n * not a member being undefined — and that gap is what killed the `web` bridge for months\n * behind a friendly \"not installed\" message that was false.\n *\n * The socket settings are ADR D322, each for a stated consequence rather than a precedent:\n * `markOnlineOnConnect: false` so the account does not read as permanently online and\n * suppress push notifications on the owner's real phone; `syncFullHistory: false` so a\n * connect does not pull the entire history; an honest `browser` triple; and the protocol\n * version fetched at connect, because a stale one is refused by the server.\n */\nexport async function createBaileysSocket(opts: BaileysSocketOptions): Promise<BaileysSocketLike> {\n const specifier = opts.specifier ?? \"baileys\";\n\n let mod: BaileysModule;\n try {\n mod = (await import(/* @vite-ignore */ specifier)) as BaileysModule;\n } catch (err) {\n throw new ConfigurationError({\n code: \"peer_missing\",\n message:\n `gateway-whatsapp: ${specifier} is not installed. ` +\n \"Run `pnpm add baileys` to use the baileys backend. \" +\n `(${err instanceof Error ? err.message : String(err)})`,\n });\n }\n\n const makeSocket = member<(config: Record<string, unknown>) => BaileysSocketLike>(\n mod,\n \"makeWASocket\",\n );\n const useAuthState = member<\n (dir: string) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>\n >(mod, \"useMultiFileAuthState\");\n const fetchVersion = member<() => Promise<{ version: unknown }>>(\n mod,\n \"fetchLatestBaileysVersion\",\n );\n\n for (const [name, value] of [\n [\"makeWASocket\", makeSocket],\n [\"useMultiFileAuthState\", useAuthState],\n ] as const) {\n if (typeof value !== \"function\") {\n throw new ConfigurationError({\n code: \"peer_incompatible\",\n message:\n `gateway-whatsapp: ${specifier} is installed but does not export ${name} as a function. ` +\n `Expected a function, got ${typeof value}. The baileys backend expects the peer range ` +\n \"declared in @theokit/gateway-whatsapp.\",\n });\n }\n }\n\n // Non-null after the loop above, which exits the process path on anything else.\n const { state, saveCreds } = await (\n useAuthState as (dir: string) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>\n )(opts.sessionDir);\n\n // A stale protocol version is refused by the server. Absent this export we still connect;\n // Baileys then uses its bundled default, which is a worse guess but not a failure.\n const version = typeof fetchVersion === \"function\" ? (await fetchVersion()).version : undefined;\n\n const socket = (makeSocket as (config: Record<string, unknown>) => BaileysSocketLike)({\n auth: state,\n printQRInTerminal: false,\n markOnlineOnConnect: false,\n syncFullHistory: false,\n browser: [\"theokit-gateway\", \"chrome\", \"1.0.0\"],\n ...(version !== undefined ? { version } : {}),\n });\n\n // The pairing surface (F4). `printQRInTerminal` stays false — a library writing to stdout\n // decides where a host's output goes — so the code is handed to the caller, defaulting to\n // stderr. Without this a fresh session directory has no path to a pairing at all.\n const onQr =\n opts.onQr ??\n ((qr: string) => {\n process.stderr.write(\n `\\n[whatsapp-baileys] Scan this QR with WhatsApp — Settings, Linked devices, Link a device:\\n${qr}\\n\\n`,\n );\n });\n socket.ev.on(\"connection.update\", (update) => {\n if (typeof update.qr === \"string\" && update.qr.length > 0) onQr(update.qr);\n });\n\n socket.ev.on(\"creds.update\", () => {\n // Persisting credentials is what makes a pairing survive a restart. The callback is\n // sync, so the promise is deliberately floated — with a catch, because an unhandled\n // rejection here would end the process (the defect fixed across the adapters in #41).\n void saveCreds().catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-baileys] could not persist credentials: ${message}\\n`);\n });\n });\n\n return socket;\n}\n","/**\n * `WhatsAppBaileysBackend` — the third implementation of `WhatsAppBackend` (B-001).\n *\n * Baileys speaks the WhatsApp Web multi-device protocol over a WebSocket, with no browser.\n * That is the whole difference from the `web` backend, which drives a headless Chromium.\n *\n * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number created\n * for this, never a personal one. Prefer {@link WhatsAppCloudBackend} unless the number has\n * no Cloud API access.\n *\n * **Added rather than replacing**, for three reasons that a substitution would not give:\n * nobody loses a paired session (a Puppeteer profile and a multi-file auth state are not\n * interchangeable), the comparison against the incumbent becomes measurable rather than\n * asserted, and retreat stays cheap because nobody is forced onto it.\n *\n * @public\n */\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { normalizeBaileysMessage } from \"./normalize.js\";\nimport {\n type BaileysSocketFactory,\n type BaileysSocketLike,\n createBaileysSocket,\n} from \"./socket.js\";\n\n/**\n * Close a socket without caring whether it was already gone.\n *\n * Tearing down something that has already closed is not a failure worth reporting: the\n * caller asked for it closed, and it is closed.\n */\nfunction endQuietly(socket: BaileysSocketLike): void {\n try {\n socket.end?.();\n } catch {\n // Deliberately empty — see the docblock.\n }\n}\n\n/** How long to wait for the socket to report `open` before giving up. */\nconst DEFAULT_CONNECT_TIMEOUT_MS = 60_000;\n/** How long to wait for one send to be acknowledged. */\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\n/** Construction options. @public */\nexport interface WhatsAppBaileysBackendOptions {\n /**\n * Directory holding the multi-file auth state — the pairing, persisted.\n *\n * Treat it like a credential: it is the session, and anyone holding it is the account.\n */\n readonly sessionDir: string;\n /** Give up on `connect()` after this long. Default 60s. */\n readonly connectTimeoutMs?: number;\n /** Give up on one send after this long. Default 30s. */\n readonly sendTimeoutMs?: number;\n /** Test seam: build the socket some other way. Production leaves it unset. */\n readonly socketFactory?: BaileysSocketFactory;\n /**\n * Where the pairing QR goes, as often as WhatsApp reissues it.\n *\n * Defaults to stderr. It is exposed here because a host that is not a terminal — a service, a\n * container, a web app — has no way to read stderr back to the person holding the phone, and\n * without a route out the QR the session can never be paired.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/**\n * A WhatsApp backend that speaks the multi-device protocol directly.\n *\n * No browser: where {@link WhatsAppWebBackend} drives a headless Chromium through\n * `whatsapp-web.js`, this holds a WebSocket. That is the whole difference in kind.\n *\n * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number created\n * for this and nothing else — never a personal one. Prefer the Cloud API backend unless the\n * number has no Cloud API access.\n *\n * `baileys` is an optional peer dependency, loaded lazily at connect, so a consumer who never\n * constructs this never needs it installed.\n *\n * @public\n */\nexport class WhatsAppBaileysBackend implements WhatsAppBackend {\n readonly kind = \"baileys\" as const;\n\n private socket?: BaileysSocketLike;\n private connected = false;\n /** Guards a concurrent second `connect()` from opening a second live session. */\n private connecting?: Promise<boolean>;\n /**\n * Which connection attempt is current.\n *\n * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt\n * checks it before touching any state, which is what stops an abandoned socket delivering\n * inbound or flipping `connected` under a live one.\n */\n private generation = 0;\n /**\n * How to end a connection attempt that is still awaiting `open`.\n *\n * Retirement by generation makes an attempt's listeners silent, which is not the same as\n * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so\n * the attempt settles now instead of at its timeout.\n */\n private readonly pendingAttempts = new Set<() => void>();\n /**\n * Why the socket last closed, as Baileys reported it.\n *\n * Kept because `connect()` returning `false` cannot distinguish a network blip from a\n * session the operator unlinked from their phone — and only one of those is worth retrying.\n * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.\n */\n private lastCloseError?: unknown;\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n /**\n * Serialises outbound sends (ADR D320).\n *\n * Both peer gateways studied do this, and one records that concurrent sends on a single\n * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we\n * have never run a Baileys socket — so this is precaution rather than a reproduction of our\n * own bug, and saying so is the point. It is kept because the cost is one promise chain and\n * the failure it guards against is a message delivered to the wrong person.\n */\n private sendQueue: Promise<unknown> = Promise.resolve();\n\n constructor(private readonly opts: WhatsAppBaileysBackendOptions) {}\n\n /**\n * Open the socket and wait for it to report `open`.\n *\n * Idempotent, and safe against a concurrent second call: the in-flight promise is shared\n * rather than a second socket being built. WhatsApp's own adapter shipped without that\n * guard once and opened two live sessions.\n */\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n\n const attempt = this.openSocket();\n this.connecting = attempt;\n try {\n return await attempt;\n } finally {\n // Only clear what is still ours. `disconnect()` clears it too, and a later `connect()`\n // may already have installed its own — a bare assignment here would erase that one and\n // let a third caller open a parallel socket.\n if (this.connecting === attempt) this.connecting = undefined;\n }\n }\n\n /** @internal */\n private async openSocket(): Promise<boolean> {\n // Every attempt carries a generation. A socket from an abandoned attempt must not be able\n // to speak for the backend afterwards — not to deliver inbound, not to flip `connected`,\n // and not to be left running.\n const generation = ++this.generation;\n const socket = await this.buildSocket();\n const isCurrent = (): boolean => this.generation === generation;\n\n // A `disconnect()` that landed while the factory was still resolving cannot see this\n // attempt: it is not yet in `pendingAttempts` and `this.socket` is still undefined, so the\n // teardown ends nothing. The window is not theoretical — the real factory awaits a dynamic\n // import, the auth state off disk and a network round-trip for the protocol version before\n // a socket exists. Without this check, stop-then-start in that window left a live session\n // running until the connect timeout fired.\n if (!isCurrent()) {\n endQuietly(socket);\n return false;\n }\n\n this.subscribeInbound(socket, isCurrent);\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const openedOk = await this.raceOpen(socket, isCurrent, timeoutMs);\n\n // A `disconnect()` that arrived while this was opening wins. Adopting the socket now would\n // leave `connected` true over a backend whose socket was already cleared, and every later\n // `connect()` would short-circuit on it while every `send` was refused — the\n // teardown-during-connect wedge fixed in the Slack adapter.\n if (!isCurrent()) {\n endQuietly(socket);\n return false;\n }\n\n if (!openedOk) {\n this.reportConnectFailure(timeoutMs);\n // A failed attempt must not leave a live socket behind. It would keep feeding inbound\n // into the handler, and the retry would open a SECOND live session — which on an\n // unofficial automation is ban surface, not only a leak.\n //\n // Bumping the generation is what actually silences it: `end()` asks the socket to close,\n // and a socket mid-teardown can still emit. Retiring the generation makes every listener\n // from this attempt a no-op regardless.\n this.generation += 1;\n endQuietly(socket);\n this.socket = undefined;\n this.connected = false;\n return false;\n }\n\n // Nothing should still be here, but a socket that closed and was replaced without going\n // through the close branch would be stranded by this assignment — and a stranded Baileys\n // socket is a live session, not an unreferenced object.\n if (this.socket !== undefined && this.socket !== socket) endQuietly(this.socket);\n this.socket = socket;\n this.connected = true;\n return true;\n }\n\n /** Build a socket through the injected factory, or the real one. @internal */\n private async buildSocket(): Promise<BaileysSocketLike> {\n const factory = this.opts.socketFactory ?? createBaileysSocket;\n return factory({\n sessionDir: this.opts.sessionDir,\n ...(this.opts.onQr !== undefined ? { onQr: this.opts.onQr } : {}),\n });\n }\n\n /** Route this socket's inbound batches into the handler, while it is still current. @internal */\n private subscribeInbound(socket: BaileysSocketLike, isCurrent: () => boolean): void {\n socket.ev.on(\"messages.upsert\", (payload) => {\n // A batch typed anything other than `notify` is history being replayed, not live\n // traffic. Answering replayed history is the defect #11 records in the email backend.\n if (payload.type !== undefined && payload.type !== \"notify\") return;\n if (!isCurrent()) return;\n for (const raw of payload.messages ?? []) this.dispatchInbound(raw);\n });\n }\n\n /**\n * Wait for this socket to report `open`, or for something to end the attempt.\n *\n * Three things can settle it: the socket opens, the socket closes, or the timeout fires — and\n * a fourth, `disconnect()`, reaches it through `pendingAttempts`. That last one is why the\n * resolver is registered rather than merely closed over: retiring an attempt by generation\n * makes its listeners no-ops, INCLUDING the one that would settle this, so without a way in\n * from outside the only thing left able to finish it was the timeout.\n *\n * @internal\n */\n private async raceOpen(\n socket: BaileysSocketLike,\n isCurrent: () => boolean,\n timeoutMs: number,\n ): Promise<boolean> {\n // The executor runs synchronously, so `settle` is assigned before the next statement.\n let settle: (ok: boolean) => void = () => undefined;\n const opened = new Promise<boolean>((resolve) => {\n settle = resolve;\n });\n\n const abandon = (): void => settle(false);\n this.pendingAttempts.add(abandon);\n\n socket.ev.on(\"connection.update\", (update) => {\n if (!isCurrent()) return;\n if (update.connection === \"open\") {\n settle(true);\n return;\n }\n if (update.connection !== \"close\") return;\n this.lastCloseError = update.lastDisconnect?.error;\n this.connected = false;\n // A closed socket is finished, and Baileys carries its own reconnect machinery: left\n // alone it keeps dialling under a backend that believes it is disconnected. Clearing the\n // reference too is what stops the next `connect()` overwriting it and stranding this one\n // beyond the reach of any later `disconnect()`.\n if (this.socket === socket) this.socket = undefined;\n endQuietly(socket);\n settle(false);\n });\n\n // Never hanging matters more than succeeding: a caller has nothing to time out against if\n // this promise simply never settles.\n const timer = setTimeout(() => settle(false), timeoutMs);\n try {\n return await opened;\n } finally {\n // The loser of the race stays scheduled otherwise, and a scheduled timer keeps Node's\n // event loop alive — the defect fixed in the core runner (#37).\n clearTimeout(timer);\n this.pendingAttempts.delete(abandon);\n }\n }\n\n /**\n * Say why the connection did not open.\n *\n * A bare `false` tells an operator nothing, and the two causes want opposite responses: a\n * blip is worth retrying, an unlinked device can only be fixed by re-pairing, and a\n * supervisor that cannot tell them apart retries forever against a dead session.\n *\n * @internal\n */\n private reportConnectFailure(timeoutMs: number): void {\n const error = this.lastCloseError;\n const cause =\n error === undefined\n ? `no 'open' within ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n process.stderr.write(`[whatsapp-baileys] connect failed: ${cause}\\n`);\n }\n\n /** Close the socket. Idempotent, and safe when never connected. */\n async disconnect(): Promise<void> {\n // Bumping first is what makes an in-flight `connect()` lose: whatever it opens will see a\n // stale generation and tear itself down rather than adopting itself into a backend the\n // caller has already closed.\n this.generation += 1;\n this.connected = false;\n // Without this the guard in `connect()` hands the next caller the promise of the attempt\n // this call just doomed: it opens nothing, waits out that attempt's timeout, and returns\n // false. A supervisor doing stop-then-start reads that as an unexplained failure.\n this.connecting = undefined;\n for (const abandon of this.pendingAttempts) abandon();\n this.pendingAttempts.clear();\n const socket = this.socket;\n this.socket = undefined;\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n if (socket !== undefined) endQuietly(socket);\n }\n\n /**\n * Send one text message.\n *\n * Queued behind any send already in flight (D320), and raced against a timeout whose\n * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says\n * the acknowledgement did not arrive, not that the message did not — so this never\n * retries, because a retry after a slow ack duplicates the message.\n */\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n // The queue advances on the UNDERLYING send, not on what the caller is told.\n //\n // Chaining on the raced result looked right and broke the invariant it exists to keep: a\n // timeout returns to the caller while `socket.sendMessage` is still in flight — nothing\n // cancels it — so the next send started on a socket that already had one running. That is\n // precisely the concurrent-send hazard D320 exists to prevent, reached through D321.\n let settled: Promise<unknown> = Promise.resolve();\n const run = this.sendQueue.then(\n () => {\n const attempt = this.sendNow(message);\n settled = attempt.inFlight;\n return attempt.result;\n },\n () => {\n const attempt = this.sendNow(message);\n settled = attempt.inFlight;\n return attempt.result;\n },\n );\n this.sendQueue = run.then(\n () => settled.catch(() => undefined),\n () => settled.catch(() => undefined),\n );\n return run;\n }\n\n /**\n * Race one send against the send timeout.\n *\n * Separated so `sendNow` reads as the three outcomes it has — delivered, undetermined,\n * refused — rather than as promise plumbing.\n *\n * @internal\n */\n private async raceSend(\n inFlight: Promise<{ key?: { id?: string } } | undefined>,\n timeoutMs: number,\n ): Promise<{ key?: { id?: string } } | undefined | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n return await Promise.race([inFlight, timeout]);\n } finally {\n // The loser of the race stays scheduled otherwise, and a scheduled timer keeps Node's\n // event loop alive — the defect fixed in the core runner (#37).\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n /**\n * One send attempt.\n *\n * Returns two promises deliberately. `result` is what the caller is told — it settles on\n * the timeout. `inFlight` settles when the socket is actually free again, which is what the\n * queue must wait for: a timeout does not cancel `sendMessage`, so releasing the queue on\n * the timeout would put two sends on one socket.\n *\n * @internal\n */\n private sendNow(message: WhatsAppOutboundMessage): {\n result: Promise<WhatsAppSendResult>;\n inFlight: Promise<unknown>;\n } {\n const socket = this.socket;\n if (!this.connected || socket === undefined) {\n return {\n result: Promise.resolve({\n ok: false,\n error: { code: \"not_connected\", message: \"Baileys backend is not connected.\" },\n }),\n inFlight: Promise.resolve(),\n };\n }\n\n const jid = `${message.to}@${message.isGroup ? \"g.us\" : \"s.whatsapp.net\"}`;\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n const inFlight = socket.sendMessage(jid, { text: message.text });\n\n const result = this.raceSend(inFlight, timeoutMs)\n .then((outcome) => {\n if (outcome === \"timeout\") {\n return {\n ok: false,\n error: {\n code: \"timeout\" as const,\n message:\n `No acknowledgement after ${timeoutMs}ms — delivery is undetermined. ` +\n \"Not retried: the message may already have been delivered.\",\n },\n };\n }\n const wamid = outcome?.key?.id;\n return wamid !== undefined ? { ok: true, wamid } : { ok: true };\n })\n .catch((err: unknown) => ({\n ok: false,\n error: {\n code: \"server_error\" as const,\n message: err instanceof Error ? err.message : String(err),\n },\n }));\n\n return { result, inFlight };\n }\n\n /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.\n *\n * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does\n * not consume. Registering a handler is accepted and it is never called — stated here\n * rather than left for a consumer to discover from silence.\n */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n /**\n * Normalise one envelope and hand it to the handler.\n *\n * The promise is floated because the Baileys listener is synchronous — but with a `catch`,\n * because a bare `void` on a rejecting promise ends the process under Node's default, which\n * is what killed two adapters in this package (#41). A handler is user code; its failure is\n * named as the handler's and delivery continues.\n *\n * @internal\n */\n private dispatchInbound(raw: unknown): void {\n const handler = this.inboundHandler;\n if (handler === undefined) return;\n const event = normalizeBaileysMessage(raw);\n if (event === undefined) return;\n void handler(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-baileys] handler threw: ${message}\\n`);\n });\n }\n}\n","/**\n * `WhatsAppCloudClient` — typed `fetch` wrapper for Meta WhatsApp Business\n * Cloud API (ADR D304). No Meta SDK; we own the wire.\n *\n * @internal\n */\n\nimport type { WhatsAppCredentialCheck, WhatsAppSendResult } from \"../../backend-types.js\";\nimport { mapWhatsAppCloudError } from \"../../errors.js\";\nimport type {\n MetaErrorEnvelope,\n MetaMarkReadRequest,\n MetaSendResponse,\n MetaSendTemplateRequest,\n MetaSendTextRequest,\n MetaTemplateComponent,\n} from \"./types.js\";\n\ninterface WhatsAppCloudClientOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudClient {\n private readonly fetchImpl: typeof fetch;\n private readonly baseUrl: string;\n\n constructor(private readonly opts: WhatsAppCloudClientOptions) {\n this.fetchImpl = opts.fetch ?? fetch;\n const apiVersion = opts.apiVersion ?? \"v18.0\";\n this.baseUrl = `https://graph.facebook.com/${apiVersion}/${opts.phoneNumberId}`;\n }\n\n /** Send a text message. v1 scope — no media (D286 deferred). */\n async sendText(to: string, body: string, isGroup: boolean): Promise<WhatsAppSendResult> {\n const req: MetaSendTextRequest = isGroup\n ? {\n messaging_product: \"whatsapp\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n }\n : {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n };\n\n return this.postMessage(req);\n }\n\n /**\n * Send an approved template.\n *\n * The only message type Meta accepts outside the 24-hour service window, and so the only way to\n * reach someone who has not written first — every notification, and every unattended check of\n * whether this integration still works. Free-form text to a cold recipient is refused with\n * `131047`, which the error mapper now surfaces as `session_window_expired`.\n *\n * `components` is omitted from the payload when absent rather than sent empty: Meta rejects\n * `components: []` on a template that declares no variables, so the two are not equivalent.\n *\n * Deliberately NOT on the `WhatsAppBackend` interface. The web backend drives WhatsApp Web,\n * which has no concept of templates, and widening the shared contract would hand it a method it\n * can only throw from.\n */\n async sendTemplate(\n to: string,\n templateName: string,\n languageCode: string,\n components?: ReadonlyArray<MetaTemplateComponent>,\n ): Promise<WhatsAppSendResult> {\n const req: MetaSendTemplateRequest = {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"template\",\n template: {\n name: templateName,\n language: { code: languageCode },\n ...(components !== undefined && components.length > 0 ? { components } : {}),\n },\n };\n return this.postMessage(req);\n }\n\n /**\n * Ask Meta whether this credential can actually act as this phone number.\n *\n * `connect()` used to answer that question with `return true`, so a wrong, expired or revoked\n * token reported success at startup and surfaced as messages that silently never arrived —\n * the worst failure mode a gateway has, because there is nothing in a log to see. The first\n * live run of the WhatsApp suite caught it (#58); 209 unit tests could not, because a fake\n * backend always accepts.\n *\n * It reads the phone number itself rather than `/me`, and that choice is the point: a token\n * can be perfectly valid and still have no access to THIS phone number id, which is the\n * likelier misconfiguration of the two. Checking only the token would wave it through.\n *\n * Returns a result rather than a boolean, and never throws — `connect()` is specified to\n * return false rather than throw, and the reason has to survive the trip: `auth_failed` and\n * `rate_limit` ask a supervisor for opposite responses.\n */\n async verifyCredentials(): Promise<WhatsAppCredentialCheck> {\n let response: Response;\n try {\n response = await this.fetchImpl(this.baseUrl, {\n method: \"GET\",\n headers: { authorization: `Bearer ${this.opts.accessToken}` },\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n const body = (await response.json().catch(() => undefined)) as\n | (MetaErrorEnvelope & { id?: unknown })\n | undefined;\n\n if (!response.ok) {\n return { ok: false, error: mapWhatsAppCloudError(response.status, body ?? {}) };\n }\n // A 200 is not a yes. Meta answers some failures with an error envelope under a 200, and a\n // captive portal or proxy answers everything with one — so the status line is the weakest\n // evidence in the response.\n // `null`, an array, a string and a number are all valid JSON and none of them is a node\n // description. `response.json()` resolves `null` for the literal, which is neither\n // `undefined` nor an object — the undefined-only guard let it through and the next line\n // dereferenced it, so a proxy answering `null` made `connect()` THROW. That is precisely the\n // clause this method is written to uphold.\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n return {\n ok: false,\n error: {\n code: \"unknown\",\n message: `Meta answered ${response.status} with a body this client could not read.`,\n },\n };\n }\n if (body.error !== undefined) {\n return { ok: false, error: mapWhatsAppCloudError(response.status, body) };\n }\n // IDENTITY, not access — the distinction this method exists for, and the one its first\n // version claimed while checking only the other. `GET /{waba_id}` with a management-scoped\n // token also answers 200, so pasting the WABA id where the phone number id belongs sails\n // through an access check and fails on every send afterwards. It is the likeliest\n // misconfiguration in Cloud API setup, and the response names the node it actually reached.\n // Compared as strings: Graph returns ids as strings, but a numeric one under strict `!==`\n // produced \"resolves to node 12345, not the configured phoneNumberId 12345\" — a refusal that\n // contradicts itself and sends someone hunting a mixup its own text rules out.\n if (String(body.id) !== this.opts.phoneNumberId) {\n return {\n ok: false,\n error: {\n code: \"invalid_request\",\n message:\n `Credential is valid but resolves to node ${String(body.id)}, not the configured ` +\n `phoneNumberId ${this.opts.phoneNumberId}. A WhatsApp Business Account id in place ` +\n `of a phone number id looks exactly like this.`,\n },\n };\n }\n return { ok: true };\n }\n\n /**\n * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.\n *\n * Shared by every send: how to reach the endpoint, how to authenticate, and how to read the\n * reply is one piece of knowledge, and it was about to have a second copy.\n */\n private async postMessage(\n req: MetaSendTextRequest | MetaSendTemplateRequest,\n ): Promise<WhatsAppSendResult> {\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(req),\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as MetaErrorEnvelope | unknown;\n return { ok: false, error: mapWhatsAppCloudError(response.status, errBody) };\n }\n\n const data = (await response.json()) as MetaSendResponse;\n const wamid = data.messages?.[0]?.id;\n if (wamid === undefined) {\n return { ok: false, error: { code: \"unknown\", message: \"Meta returned no wamid.\" } };\n }\n return { ok: true, wamid };\n }\n\n /** Mark an inbound message as read (status receipt back to user). */\n async markAsRead(wamid: string): Promise<boolean> {\n const body: MetaMarkReadRequest = {\n messaging_product: \"whatsapp\",\n status: \"read\",\n message_id: wamid,\n };\n try {\n const response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","/**\n * Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).\n *\n * Two boundaries:\n * 1. GET handshake — `verifyWebhookSubscription` (EC-1).\n * 2. POST callbacks — `verifyWebhookSignature` (EC-3 length guard) +\n * `normalizeInboundMessages` (EC-4 text-only filter) +\n * `normalizeStatusReceipts`.\n *\n * The user owns the HTTP route; we expose pure helpers they call from inside it.\n *\n * @public\n */\n\nimport * as crypto from \"node:crypto\";\n\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"../../backend-types.js\";\nimport type { MetaIncomingMessage, MetaStatusUpdate, MetaWebhookEnvelope } from \"./types.js\";\n\nconst warnedNonTextTypes = new Set<string>();\n\n/**\n * Verify Meta's GET `/webhook?hub.mode=subscribe&hub.challenge=...&hub.verify_token=...`\n * handshake (EC-1 absorbed).\n *\n * @returns `query[\"hub.challenge\"]` when valid, `null` otherwise. The caller\n * echoes the challenge as `text/plain` on success.\n */\nexport function verifyWebhookSubscription(\n query: Record<string, string | undefined>,\n expectedVerifyToken: string,\n): string | null {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (mode !== \"subscribe\") return null;\n if (token === undefined || token !== expectedVerifyToken) return null;\n if (challenge === undefined || challenge.length === 0) return null;\n return challenge;\n}\n\n/**\n * Verify the `X-Hub-Signature-256` HMAC-SHA256 against the app secret (D312).\n *\n * EC-3 absorbed: length-guard BEFORE `timingSafeEqual` so a malformed header\n * (e.g. `sha256=ab`) returns `false` instead of throwing `RangeError` (DoS).\n *\n * @returns `true` iff the signature matches.\n */\nexport function verifyWebhookSignature(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n appSecret: string,\n): boolean {\n if (signatureHeader === undefined) return false;\n if (!signatureHeader.startsWith(\"sha256=\")) return false;\n const receivedHex = signatureHeader.slice(7);\n if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;\n const received = Buffer.from(receivedHex, \"hex\");\n const body = typeof rawBody === \"string\" ? Buffer.from(rawBody, \"utf8\") : rawBody;\n const expected = crypto.createHmac(\"sha256\", appSecret).update(body).digest();\n // EC-3: length guard before timingSafeEqual.\n if (received.length !== expected.length) return false;\n return crypto.timingSafeEqual(received, expected);\n}\n\n/** Parse the raw JSON payload into a typed envelope. Returns `null` if shape is unrecognized. */\nexport function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null {\n if (json === null || typeof json !== \"object\") return null;\n const env = json as MetaWebhookEnvelope;\n if (env.object === undefined || !Array.isArray(env.entry)) return null;\n return env;\n}\n\n/**\n * Normalize inbound messages → `WhatsAppInboundEvent[]`.\n *\n * EC-4 absorbed: filters `message.type !== \"text\"` (v1 text-only). Non-text\n * types emit a one-shot stderr warn per type.\n */\nfunction buildContactMap(\n value: NonNullable<MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number][\"value\"]>,\n): Map<string, string | undefined> {\n const map = new Map<string, string | undefined>();\n for (const c of value.contacts ?? []) map.set(c.wa_id, c.profile?.name);\n return map;\n}\n\nfunction processChange(\n change: MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number],\n out: WhatsAppInboundEvent[],\n): void {\n const value = change.value;\n if (value === undefined || value === null) return;\n const phoneNumberId = value.metadata?.phone_number_id;\n const contactByWaId = buildContactMap(value);\n for (const msg of value.messages ?? []) {\n const normalized = normalizeOneMessage(msg, phoneNumberId, contactByWaId);\n if (normalized !== null) out.push(normalized);\n }\n}\n\n/**\n * Extract the inbound messages from one Meta webhook envelope.\n *\n * A single delivery batches entries, changes and messages, and may carry none at all — a\n * status-only delivery is normal. Returns an array, empty when there is nothing to hand on.\n */\nexport function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[] {\n const out: WhatsAppInboundEvent[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) processChange(change, out);\n }\n return out;\n}\n\nfunction normalizeOneMessage(\n msg: MetaIncomingMessage,\n phoneNumberId: string | undefined,\n contactByWaId: Map<string, string | undefined>,\n): WhatsAppInboundEvent | null {\n // EC-4: text-only in v1.\n if (msg.type !== \"text\") {\n if (!warnedNonTextTypes.has(msg.type)) {\n warnedNonTextTypes.add(msg.type);\n process.stderr.write(\n `[whatsapp] ignoring ${msg.type} message — v1 text-only (will be supported in v0.2+).\\n`,\n );\n }\n return null;\n }\n const body = msg.text?.body ?? \"\";\n // Cloud API doesn't distinguish DM vs group at the message level — `from`\n // is the sender. We don't have a reliable group-detection signal in cloud\n // (groups need a different webhook subscription). v1 treats all inbound\n // as DM. If the user enables group webhooks, the `conversationType` heuristic\n // here is a future-extension point.\n return {\n wamid: msg.id,\n fromPhone: msg.from,\n phoneNumberId,\n contactName: contactByWaId.get(msg.from),\n conversationType: \"dm\",\n channelId: msg.from,\n text: body,\n receivedAt: Number(msg.timestamp) * 1000 || Date.now(),\n backend: \"cloud\",\n raw: msg,\n };\n}\n\n/** Normalize status updates → `WhatsAppStatusReceipt[]`. */\nexport function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[] {\n const out: WhatsAppStatusReceipt[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) {\n const statuses = change.value?.statuses ?? [];\n for (const s of statuses) {\n out.push(metaStatusToReceipt(s));\n }\n }\n }\n return out;\n}\n\nfunction metaStatusToReceipt(s: MetaStatusUpdate): WhatsAppStatusReceipt {\n return {\n wamid: s.id,\n status: s.status,\n recipient: s.recipient_id,\n timestamp: Number(s.timestamp) * 1000 || Date.now(),\n };\n}\n\n/** @internal — test seam to reset the one-shot warn de-dup. */\nexport function __resetNonTextWarnings(): void {\n warnedNonTextTypes.clear();\n}\n","/**\n * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).\n *\n * `connect()` verifies the credential against Meta and caches the result; `disconnect()` clears\n * it. This header used to say both were no-ops, which is what the code did and what the first\n * live run of the WhatsApp suite refuted (#58): a wrong or revoked token reported success at\n * startup and surfaced as messages that silently never arrived.\n *\n * There is still no session to open — HTTP push via webhook is the only inbound channel, and\n * outbound is a stateless POST. What `connect()` buys is the startup answer to \"can this\n * credential act as this number?\", which is the question every sibling adapter answers and this\n * one did not. Outbound delegates to `WhatsAppCloudClient`. Inbound dispatch is driven by the\n * user calling `handleWebhookPayload(rawBody, sig)` from inside their HTTP route.\n *\n * @public\n */\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { WhatsAppCloudClient } from \"./client.js\";\nimport type { MetaTemplateComponent } from \"./types.js\";\nimport {\n normalizeInboundMessages,\n normalizeStatusReceipts,\n parseWebhookPayload,\n verifyWebhookSignature,\n} from \"./webhook.js\";\n\nexport interface WhatsAppCloudBackendOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly appSecret: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\n/**\n * WhatsApp backend over Meta's official Cloud API.\n *\n * The supported path: Meta dials in with webhook deliveries, so inbound needs a publicly reachable\n * HTTPS endpoint registered in the Meta console. Outbound is a plain HTTPS call and works anywhere.\n * Business-initiated messages outside the 24-hour customer service window must use an approved\n * template — a plain text send to a cold contact is rejected by the platform, not by this code.\n */\nexport class WhatsAppCloudBackend implements WhatsAppBackend {\n readonly kind = \"cloud\" as const;\n private readonly client: WhatsAppCloudClient;\n /** Verified once by `connect()`; cleared by `disconnect()`. */\n private connected = false;\n /**\n * The verification currently in flight, shared by every caller that arrives during it.\n *\n * A flag alone only guards callers that arrive AFTER one finished — two simultaneous\n * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a\n * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it\n * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay\n * distinguishable from a revoked token.\n */\n private connecting?: Promise<boolean>;\n /**\n * Which connection attempt is current.\n *\n * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in\n * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every\n * later `connect()` would short-circuit on a flag no live check stands behind — the field's own\n * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend\n * carries, for the same reason.\n */\n private generation = 0;\n private readonly appSecret: string;\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n constructor(opts: WhatsAppCloudBackendOptions) {\n this.client = new WhatsAppCloudClient({\n accessToken: opts.accessToken,\n phoneNumberId: opts.phoneNumberId,\n apiVersion: opts.apiVersion,\n ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),\n });\n this.appSecret = opts.appSecret;\n }\n\n // Cloud has no persistent connection — webhook is push, send is HTTP.\n /**\n * Confirm with Meta that this credential can act as this phone number.\n *\n * This used to be `return true`. A consumer with a wrong, expired or revoked token got success\n * at startup and found out from messages that silently never arrived — no error, no log,\n * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the\n * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.\n *\n * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would\n * turn a supervisor's health check into a rate-limit source against Meta.\n *\n * Returns false rather than throwing — the contract each sibling adapter is tested against,\n * because a throw at startup takes the whole runner down with it. The reason goes to stderr\n * first: told only \"false\", a supervisor cannot tell a revoked token, which needs a human,\n * from a rate limit, which needs a wait.\n */\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n\n const attempt = this.verifyOnce(++this.generation);\n this.connecting = attempt;\n try {\n return await attempt;\n } finally {\n // Only clear what is still ours: `disconnect()` clears it too, and a later `connect()` may\n // already have installed its own.\n if (this.connecting === attempt) this.connecting = undefined;\n }\n }\n\n /** One credential check, mapped to the boolean `connect()` is contracted to return. @internal */\n private async verifyOnce(generation: number): Promise<boolean> {\n const check = await this.client.verifyCredentials();\n if (!check.ok) {\n process.stderr.write(\n `[whatsapp-cloud] connect failed: ${check.error?.code ?? \"unknown\"} — ` +\n `${check.error?.message ?? \"no reason given\"}\\n`,\n );\n return false;\n }\n // A `disconnect()` that arrived while this was in flight wins: adopting now would leave a\n // flag standing over a backend the caller has already closed.\n if (this.generation !== generation) return false;\n this.connected = true;\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n // Cloud is stateless HTTP, so there is no session to be outside of — and that was the reason\n // this posted regardless while web and Baileys refused. It was the wrong reason. Since\n // `connect()` started verifying the credential, `connected === false` means the credential\n // was rejected or never checked, and sending anyway spends a request that cannot succeed\n // while making this backend behave differently from its siblings under one interface.\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"Cloud backend is not connected — call connect().\",\n },\n };\n }\n return this.client.sendText(message.to, message.text, message.isGroup);\n }\n\n /**\n * Send an approved template to `to`.\n *\n * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no\n * concept of templates, so putting this on the shared contract would hand the web backend a\n * method it could only throw from. A consumer reaches it by holding the backend directly.\n *\n * This is the only way to message someone outside the 24-hour service window — every\n * notification, and every unattended check that this integration still works. Free-form text to\n * a cold recipient comes back as `session_window_expired`.\n *\n * @param templateName Name of a template already approved on the WhatsApp Business account.\n * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.\n * @param components Values for the template's variables; omit for a template that takes none.\n */\n async sendTemplate(\n to: string,\n templateName: string,\n languageCode: string,\n components?: ReadonlyArray<MetaTemplateComponent>,\n ): Promise<WhatsAppSendResult> {\n // Same rule as `send()`, and it needs saying separately because this method is off the\n // `WhatsAppBackend` interface — WhatsApp Web has no templates — so the conformance suite that\n // enforces it there structurally cannot see it here. Being outside the shared contract is\n // why it needs its own guard, not a reason to be exempt from the rule.\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"Cloud backend is not connected — call connect().\",\n },\n };\n }\n return this.client.sendTemplate(to, templateName, languageCode, components);\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n // Identity-guarded: a stale unsubscribe must be a no-op. Without it,\n // `onInbound(A)` → `onInbound(B)` → `A.off()` clears B's handler and the backend goes\n // silent with no error — nothing to see in a log, nothing to alert on. This is a public\n // export implementing an exported interface, so a consumer holding the backend directly\n // reaches it without going through `WhatsAppAdapter`.\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n /**\n * Webhook entrypoint. The user calls this from inside their POST /webhook\n * route after `verifyWebhookSubscription` on GET.\n *\n * @returns `true` if signature valid + dispatched (or empty payload).\n * `false` if signature invalid (route should return 401).\n */\n async handleWebhookPayload(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n ): Promise<boolean> {\n if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {\n return false;\n }\n const json = this.parseBody(rawBody);\n if (json === undefined) return false;\n const envelope = parseWebhookPayload(json);\n if (envelope === null) return true; // valid signature, unrecognized shape — nothing to dispatch\n for (const event of normalizeInboundMessages(envelope)) {\n if (this.inboundHandler === undefined) continue;\n await this.dispatchContained(() => this.inboundHandler?.(event), \"handler\");\n }\n for (const receipt of normalizeStatusReceipts(envelope)) {\n if (this.statusHandler === undefined) continue;\n await this.dispatchContained(() => this.statusHandler?.(receipt), \"status handler\");\n }\n return true;\n }\n\n /**\n * Parse a signed webhook body, or report `undefined` when it is not JSON.\n *\n * The method's contract is true/false; the route calling it has no reason to expect a throw.\n */\n private parseBody(rawBody: Buffer | string): unknown | undefined {\n try {\n return JSON.parse(typeof rawBody === \"string\" ? rawBody : rawBody.toString(\"utf8\"));\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-cloud] webhook body is not JSON: ${m}\\n`);\n return undefined;\n }\n }\n\n /**\n * Run one user callback and contain its failure.\n *\n * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a\n * handler with nothing around it made one throw skip every remaining message in the payload —\n * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the\n * whole batch, replaying the messages that HAD succeeded (#41).\n */\n private async dispatchContained(\n run: () => Promise<void> | undefined,\n what: string,\n ): Promise<void> {\n try {\n await run();\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-cloud] ${what} threw: ${m}\\n`);\n }\n }\n}\n","/**\n * IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.\n *\n * Wire: stdin/stdout JSON-lines (each message terminated by `\\n`).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — see `backend-types.ts` for rationale.\n *\n * @knipignore\n */\nexport const __ipcMarker: unique symbol = Symbol(\"ipc\");\n\n/** Commands the adapter sends to the bridge. */\nexport type IpcCommand =\n | { readonly cmd: \"send\"; readonly msgId: string; readonly to: string; readonly text: string }\n | { readonly cmd: \"shutdown\" };\n\n/** Events the bridge emits to the adapter. */\nexport type IpcEvent =\n | { readonly event: \"ready\"; readonly botPhone: string }\n | {\n readonly event: \"message\";\n readonly msgId: string;\n readonly from: string;\n readonly body: string;\n readonly isGroup: boolean;\n readonly chatId: string;\n readonly contactName?: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"send_ack\";\n readonly msgId: string;\n readonly success: boolean;\n readonly wamid?: string;\n readonly error?: string;\n }\n | {\n readonly event: \"status\";\n readonly msgId: string;\n readonly status: \"sent\" | \"delivered\" | \"read\" | \"failed\";\n readonly recipient: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"error\";\n readonly message: string;\n /**\n * Machine-readable cause, when the bridge could name one. Absent on older bridges and\n * on failures it cannot classify, which is why every consumer must tolerate it being\n * undefined rather than switching exhaustively.\n */\n readonly code?: string;\n };\n\n/** Parse one JSON-line. Returns null on malformed. */\nexport function parseEvent(line: string): IpcEvent | null {\n if (line.length === 0) return null;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return null;\n if (typeof (parsed as { event?: unknown }).event !== \"string\") return null;\n return parsed as IpcEvent;\n } catch {\n return null;\n }\n}\n\n/** Format an outbound command as JSON + newline. */\nexport function formatCommand(cmd: IpcCommand): string {\n return `${JSON.stringify(cmd)}\\n`;\n}\n\n/**\n * Line buffer — accumulates stdout chunks until `\\n` boundaries, yields\n * complete lines. Addresses EC-11 (chunked stdout across multiple reads).\n */\nexport class LineBuffer {\n private buffer = \"\";\n\n push(chunk: string): string[] {\n this.buffer += chunk;\n const out: string[] = [];\n let idx = this.buffer.indexOf(\"\\n\");\n while (idx !== -1) {\n out.push(this.buffer.slice(0, idx));\n this.buffer = this.buffer.slice(idx + 1);\n idx = this.buffer.indexOf(\"\\n\");\n }\n return out;\n }\n\n /** Test seam — current pending bytes. */\n get pending(): string {\n return this.buffer;\n }\n}\n","/**\n * Bridge subprocess lifecycle (ADR D305, D313). PID file lock + stale-process\n * cleanup. EC-5 absorbed: verifies cmdline before killing (otherwise we may\n * kill an unrelated process the OS recycled the PID for).\n *\n * @internal\n */\n\nimport { type ChildProcess, execSync, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** Marker substring our bridge process MUST carry in its argv (EC-5). */\nexport const BRIDGE_PROCESS_TAG = \"whatsapp-web-bridge\";\n\ninterface SpawnBridgeOptions {\n readonly sessionId: string;\n readonly bridgeScriptPath: string;\n readonly theokitHome?: string;\n}\n\nexport interface BridgeHandle {\n readonly child: ChildProcess;\n readonly pidFilePath: string;\n}\n\nfunction pidFilePath(theokitHome: string, sessionId: string): string {\n return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);\n}\n\nfunction defaultTheokitHome(): string {\n return process.env.THEOKIT_HOME ?? path.join(process.env.HOME ?? \"/tmp\", \".theokit\");\n}\n\n/**\n * Verify whether `pid` belongs to a process whose argv contains our tag (EC-5).\n *\n * Without this guard, OS may have recycled the PID to e.g. `vim` and our\n * cleanup would terminate the user's editor.\n *\n * @internal\n */\nexport function pidBelongsToOurBridge(pid: number): boolean {\n try {\n // Linux: /proc/<pid>/cmdline (NUL-separated argv).\n const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, \"utf8\");\n return cmdline.includes(BRIDGE_PROCESS_TAG);\n } catch {\n // macOS / BSD fallback: ps -p <pid> -o args=\n try {\n const out = execSync(`ps -p ${pid} -o args=`, {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).toString();\n return out.includes(BRIDGE_PROCESS_TAG);\n } catch {\n return false;\n }\n }\n}\n\n/** EC-5: kill `stalePid` ONLY if cmdline confirms ownership. */\nfunction killIfOurBridge(stalePid: number): void {\n if (!Number.isFinite(stalePid) || stalePid <= 0) return;\n if (!pidBelongsToOurBridge(stalePid)) return;\n try {\n process.kill(stalePid, \"SIGTERM\");\n } catch {\n // Process already gone — fine.\n }\n}\n\nfunction cleanupStaleLock(lockFile: string): void {\n const raw = fs.readFileSync(lockFile, \"utf8\").trim();\n killIfOurBridge(Number.parseInt(raw, 10));\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\n/**\n * Acquire the PID lock for a session — kill any stale bridge (cmdline-verified),\n * then return the lock-file path (caller writes its own PID after spawn).\n */\nexport function acquirePidLock(sessionId: string, theokitHome?: string): string {\n const home = theokitHome ?? defaultTheokitHome();\n fs.mkdirSync(home, { recursive: true });\n const lockFile = pidFilePath(home, sessionId);\n if (fs.existsSync(lockFile)) cleanupStaleLock(lockFile);\n return lockFile;\n}\n\n/** Spawn the bridge subprocess, write PID file. */\nexport function spawnBridge(opts: SpawnBridgeOptions): BridgeHandle {\n const home = opts.theokitHome ?? defaultTheokitHome();\n const lockFile = acquirePidLock(opts.sessionId, home);\n\n const child = spawn(\n \"node\",\n [opts.bridgeScriptPath, \"--tag\", BRIDGE_PROCESS_TAG, \"--session\", opts.sessionId],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: false,\n },\n );\n\n if (child.pid !== undefined) {\n fs.writeFileSync(lockFile, String(child.pid), { mode: 0o600 });\n }\n\n // EC-12: pipe stderr so the buffer never fills.\n if (child.stderr !== null) {\n child.stderr.pipe(process.stderr);\n }\n\n return { child, pidFilePath: lockFile };\n}\n\n/** Terminate the bridge: SIGTERM → wait 3s → SIGKILL. Removes PID file. */\nexport async function terminateBridge(handle: BridgeHandle): Promise<void> {\n const { child, pidFilePath: lockFile } = handle;\n if (child.pid !== undefined && !child.killed) {\n try {\n child.kill(\"SIGTERM\");\n } catch {\n /* ignore */\n }\n const exited = await waitForExit(child, 3000);\n if (!exited) {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* ignore */\n }\n await waitForExit(child, 1000);\n }\n }\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) {\n resolve(true);\n return;\n }\n let resolved = false;\n const onExit = () => {\n if (resolved) return;\n resolved = true;\n resolve(true);\n };\n child.once(\"exit\", onExit);\n setTimeout(() => {\n if (resolved) return;\n resolved = true;\n child.removeListener(\"exit\", onExit);\n resolve(false);\n }, timeoutMs).unref();\n });\n}\n","/**\n * `WhatsAppWebBackend` — `whatsapp-web.js` subprocess bridge backend (ADR D305).\n *\n * Lifecycle (T3.1) + IPC (T3.2) wired behind the `WhatsAppBackend` interface.\n * EC-6 absorbed: `connect()` races against a 120s timeout so unattended QR\n * pairings fail fast instead of hanging the app.\n *\n * @public\n */\n\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport {\n mapWhatsAppWebError,\n WhatsAppBridgeError,\n WhatsAppConnectTimeoutError,\n} from \"../../errors.js\";\nimport { formatCommand, type IpcEvent, LineBuffer, parseEvent } from \"./ipc.js\";\nimport { type BridgeHandle, spawnBridge, terminateBridge } from \"./lifecycle.js\";\n\nexport interface WhatsAppWebBackendOptions {\n readonly sessionId: string;\n /** Override the default bridge script path. Defaults to bundled script. */\n readonly bridgeScriptPath?: string;\n /** EC-6 connect timeout in ms. Default 120000. */\n readonly connectTimeoutMs?: number;\n /** Per-send timeout in ms. Default 30000. */\n readonly sendTimeoutMs?: number;\n /** Test seam: override the spawned child via a factory. */\n readonly spawnFactory?: () => BridgeHandle;\n /** Test seam: theokit home for PID locks. */\n readonly theokitHome?: string;\n}\n\ninterface PendingSend {\n readonly resolve: (r: WhatsAppSendResult) => void;\n readonly timer: NodeJS.Timeout;\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 120_000;\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\n/**\n * WhatsApp backend driving `whatsapp-web.js` in a child process.\n *\n * Unofficial: it automates a WhatsApp Web session, which Meta's terms do not sanction and which can\n * get a number banned. It exists for a personal number that has no Cloud API access. The browser\n * runs out-of-process behind a PID lock so a crashed or orphaned bridge cannot be left holding the\n * session.\n */\nexport class WhatsAppWebBackend implements WhatsAppBackend {\n readonly kind = \"web\" as const;\n private handle?: BridgeHandle;\n private readonly buffer = new LineBuffer();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n private readonly pending = new Map<string, PendingSend>();\n /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */\n private connectRejectors: Array<(reason: Error) => void> = [];\n private msgIdCounter = 0;\n private botPhone?: string;\n private connected = false;\n // EC-6: emitter resolvers for `event: \"ready\"`.\n private readyResolvers: Array<(phone: string) => void> = [];\n\n constructor(private readonly opts: WhatsAppWebBackendOptions) {}\n\n private spawnBridgeHandle(): NonNullable<typeof this.handle> {\n return this.opts.spawnFactory\n ? this.opts.spawnFactory()\n : spawnBridge({\n sessionId: this.opts.sessionId,\n bridgeScriptPath: this.opts.bridgeScriptPath ?? defaultBridgeScriptPath(),\n ...(this.opts.theokitHome !== undefined ? { theokitHome: this.opts.theokitHome } : {}),\n });\n }\n\n private wireStdout(): void {\n if (this.handle?.child.stdout === null || this.handle === undefined) return;\n this.handle.child.stdout.setEncoding(\"utf8\");\n this.handle.child.stdout.on(\"data\", (chunk: string) => {\n for (const line of this.buffer.push(chunk)) {\n const event = parseEvent(line);\n if (event !== null) this.dispatch(event);\n }\n });\n }\n\n private async cleanupHandle(): Promise<void> {\n if (this.handle === undefined) return;\n await terminateBridge(this.handle).catch(() => {});\n this.handle = undefined;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.handle = this.spawnBridgeHandle();\n this.wireStdout();\n\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const ready = new Promise<string>((resolve, reject) => {\n this.readyResolvers.push(resolve);\n // The bridge reporting a startup failure resolves the race immediately, so the caller\n // learns the cause instead of waiting out the timeout.\n this.connectRejectors.push(reject);\n });\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n const phone = await Promise.race([ready, timeout]);\n this.botPhone = phone;\n this.connected = true;\n return true;\n } catch (err) {\n await this.cleanupHandle();\n throw err;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n // Both arrays hold settled callbacks once the race is decided, and neither was cleared\n // on the path that fails by timeout — `handleBridgeError` never ran, and `disconnect()`\n // returns early while `connected` is false. A reconnect loop therefore grew them by one\n // per attempt forever. `readyResolvers` had the same leak before this method learned to\n // reject; clearing them together is the whole fix.\n this.readyResolvers = [];\n this.connectRejectors = [];\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected || this.handle === undefined) return;\n try {\n if (this.handle.child.stdin !== null && !this.handle.child.stdin.destroyed) {\n this.handle.child.stdin.write(formatCommand({ cmd: \"shutdown\" }));\n }\n } catch {\n /* ignore */\n }\n await terminateBridge(this.handle);\n this.handle = undefined;\n this.connected = false;\n // Reject any pending sends.\n for (const [_, p] of this.pending) {\n clearTimeout(p.timer);\n p.resolve({ ok: false, error: { code: \"server_error\", message: \"Bridge disconnected.\" } });\n }\n this.pending.clear();\n this.readyResolvers = [];\n this.connectRejectors = [];\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n if (!this.connected || this.handle === undefined || this.handle.child.stdin === null) {\n return { ok: false, error: { code: \"not_connected\", message: \"Bridge not connected.\" } };\n }\n const msgId = `out-${++this.msgIdCounter}`;\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n return new Promise<WhatsAppSendResult>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: { code: \"timeout\", message: `Bridge send timed out after ${timeoutMs}ms.` },\n });\n }, timeoutMs);\n this.pending.set(msgId, { resolve, timer });\n try {\n this.handle!.child.stdin!.write(\n formatCommand({ cmd: \"send\", msgId, to: message.to, text: message.text }),\n );\n } catch (err) {\n clearTimeout(timer);\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: mapWhatsAppWebError(err instanceof Error ? err.message : String(err)),\n });\n }\n });\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n // Identity-guarded: a stale unsubscribe must be a no-op. Without it,\n // `onInbound(A)` → `onInbound(B)` → `A.off()` clears B's handler and the backend goes\n // silent with no error — nothing to see in a log, nothing to alert on. This is a public\n // export implementing an exported interface, so a consumer holding the backend directly\n // reaches it without going through `WhatsAppAdapter`.\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n private handleReady(event: Extract<IpcEvent, { event: \"ready\" }>): void {\n for (const r of this.readyResolvers) r(event.botPhone);\n this.readyResolvers = [];\n }\n\n private handleMessage(event: Extract<IpcEvent, { event: \"message\" }>): void {\n if (this.inboundHandler === undefined) return;\n const normalized: WhatsAppInboundEvent = {\n wamid: event.msgId,\n fromPhone: event.from,\n contactName: event.contactName,\n conversationType: event.isGroup ? \"group\" : \"dm\",\n channelId: event.chatId,\n text: event.body,\n receivedAt: event.timestamp || Date.now(),\n backend: \"web\",\n raw: event,\n };\n // The bridge's stdout listener is synchronous and does not await this, so the promise has to be\n // terminated here. `void` alone left the rejection unhandled, and under Node 22's default that\n // ends the process — one message with a throwing handler killed the bot (#41). A handler is\n // user code; its failure is contained and named, and the bridge keeps delivering.\n void this.inboundHandler(normalized).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-web] handler threw: ${m}\\n`);\n });\n }\n\n /**\n * A bridge that reported a failure has failed — say so now, not in two minutes.\n *\n * This used to write the message to stderr and return. `connect()` races only the `ready`\n * promise against the timeout, so a bridge that told us exactly what was wrong and exited\n * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one\n * error that carries no information. The diagnosis was printed where nothing could act on\n * it, which is the swallowing `rules/error-handling.md` § 5 names.\n */\n private handleBridgeError(event: Extract<IpcEvent, { event: \"error\" }>): void {\n process.stderr.write(`[whatsapp-web bridge] ${event.message}\\n`);\n const failure = new WhatsAppBridgeError(event.message, event.code);\n // Unblocks an in-flight connect(). Harmless once connected: nobody is waiting.\n for (const reject of this.connectRejectors) reject(failure);\n this.connectRejectors = [];\n }\n\n private handleSendAck(event: Extract<IpcEvent, { event: \"send_ack\" }>): void {\n const pending = this.pending.get(event.msgId);\n if (pending === undefined) return;\n this.pending.delete(event.msgId);\n clearTimeout(pending.timer);\n if (event.success) {\n pending.resolve(event.wamid !== undefined ? { ok: true, wamid: event.wamid } : { ok: true });\n } else {\n pending.resolve({ ok: false, error: mapWhatsAppWebError(event.error) });\n }\n }\n\n private handleStatus(event: Extract<IpcEvent, { event: \"status\" }>): void {\n if (this.statusHandler === undefined) return;\n // Same boundary as handleMessage: nothing awaits this, so an unhandled rejection here is fatal.\n void this.statusHandler({\n wamid: event.msgId,\n status: event.status,\n recipient: event.recipient,\n timestamp: event.timestamp || Date.now(),\n }).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-web] status handler threw: ${m}\\n`);\n });\n }\n\n private dispatch(event: IpcEvent): void {\n switch (event.event) {\n case \"ready\":\n this.handleReady(event);\n return;\n case \"message\":\n this.handleMessage(event);\n return;\n case \"send_ack\":\n this.handleSendAck(event);\n return;\n case \"status\":\n this.handleStatus(event);\n return;\n case \"error\":\n this.handleBridgeError(event);\n return;\n }\n }\n}\n\n/**\n * Where the bridge script lives, for the layout this module is running from.\n *\n * The single hard-coded `../../bridge/...` this replaced was written against the SOURCE\n * tree — `src/backend/web/` up two is `src/`, which is right. The bundle is one flat file\n * at `dist/index.js`, so the same relative path resolved to `packages/bridge/...`, one\n * directory above the package. Nothing caught it: every test injects `spawnFactory`, so the\n * real spawn had never run, and when it did the child died with `MODULE_NOT_FOUND` and\n * `connect()` reported a 120-second timeout — the one error carrying no information about\n * what actually happened.\n *\n * Both layouts are checked, and neither existing is an error rather than a guess: a path\n * that does not exist can only fail later, further from the cause.\n */\nexport function defaultBridgeScriptPath(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidates = [\n // Bundled: dist/index.js beside dist/bridge/\n path.resolve(here, \"bridge/whatsapp-web-bridge.mjs\"),\n // Source: src/backend/web/index.ts up two to src/\n path.resolve(here, \"../../bridge/whatsapp-web-bridge.mjs\"),\n ];\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw new WhatsAppBridgeError(\n `bridge script not found. Looked in: ${candidates.join(\", \")}. ` +\n \"Pass `bridgeScriptPath` explicitly if the package layout differs.\",\n \"bridge_script_missing\",\n );\n }\n return found;\n}\n","/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096\n * window, `\\n\\n` → `\\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,\n * leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered\n * so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst WHATSAPP_MAX_TEXT = 4096;\n\nexport function splitForWhatsApp(text: string): string[] {\n return chunkText(text, {\n limit: WHATSAPP_MAX_TEXT,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n surrogateGuard: true,\n stripLeading: /^\\s+/,\n trimParts: true,\n });\n}\n","/**\n * `WhatsAppAdapter` — WhatsApp platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #2; ADRs D303-D314).\n *\n * Multi-backend (Cloud + Web) — backend chosen via `WhatsAppAdapterOptions.backend`.\n * Backend-agnostic adapter delegates lifecycle + send + subscribe through the\n * `WhatsAppBackend` seam (D303).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n type WhatsAppMessageEvent,\n} from \"@theokit/gateway\";\n\nimport { isSenderAllowed, parseAllowedSenders } from \"./allowlist.js\";\nimport { WhatsAppBaileysBackend } from \"./backend/baileys/index.js\";\nimport { WhatsAppCloudBackend } from \"./backend/cloud/index.js\";\nimport { WhatsAppWebBackend } from \"./backend/web/index.js\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppStatusReceipt,\n} from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { splitForWhatsApp } from \"./split.js\";\n\n/** Cloud (Meta WhatsApp Business Cloud API) backend config (ADR D304). */\nexport interface WhatsAppCloudConfig {\n /** Meta system-user / phone-number access token. */\n readonly accessToken: string;\n /** Meta-issued phone-number-id (NOT the user-facing phone). */\n readonly phoneNumberId: string;\n /** App secret used to verify `X-Hub-Signature-256` on inbound webhooks. */\n readonly appSecret: string;\n /** Graph API version. Defaults to `v18.0`. */\n readonly apiVersion?: string;\n}\n\n/**\n * Baileys backend config (ADR D319-D322).\n *\n * Unofficial, like the `web` backend: it automates a WhatsApp Web session, which Meta's terms\n * do not sanction and which can get a number banned. Unlike `web` it needs no browser.\n *\n * @public\n */\nexport interface WhatsAppBaileysConfig {\n /**\n * Directory holding the multi-file auth state — the pairing, persisted.\n *\n * Treat it like a credential: it IS the session, and anyone holding it is the account.\n */\n readonly sessionDir: string;\n /** Give up on `connect()` after this long. Default 60s. */\n readonly connectTimeoutMs?: number;\n /** Give up on one send after this long. Default 30s. */\n readonly sendTimeoutMs?: number;\n /**\n * Where the pairing QR goes, as often as WhatsApp reissues it. Defaults to stderr.\n *\n * The backend has always accepted this; it was reachable only by constructing the backend by\n * hand, which is the path this class exists to replace. A host that is not a terminal — a\n * service, a container, a web app — cannot read stderr back to the person holding the phone,\n * and without a route out the QR a fresh `sessionDir` can only ever time out.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */\nexport interface WhatsAppWebConfig {\n /** Stable session id used to lock the bridge per-workspace. */\n readonly sessionId: string;\n /** Optional override of the bridge script path (defaults to packaged bridge). */\n readonly bridgeScriptPath?: string;\n}\n\n/**\n * Which backend to build, and its configuration.\n *\n * The union carries only what DIFFERS between backends. Options that mean the same thing on\n * either one — `requireMention`, `botPhoneId`, `allowedSenders` — live in\n * {@link WhatsAppAdapterCommonOptions} instead, so there is one copy rather than one per arm\n * for the two copies to drift apart (ADR D318).\n *\n * @public\n */\nexport type WhatsAppAdapterOptions =\n | { readonly backend: \"cloud\"; readonly cloud: WhatsAppCloudConfig }\n | { readonly backend: \"web\"; readonly web: WhatsAppWebConfig }\n | { readonly backend: \"baileys\"; readonly baileys: WhatsAppBaileysConfig };\n\n/**\n * Options that apply whichever backend is in use.\n *\n * @public\n */\nexport interface WhatsAppAdapterCommonOptions {\n /** D309: require an @mention in groups. Default `true`. */\n readonly requireMention?: boolean;\n /**\n * Phone id to detect mentions of (digits only).\n *\n * `fromCloud` defaults it to the phone number id. **The web backend has nothing to default\n * from**, so leaving it unset there while `requireMention` is on (its default) drops every\n * group message — the adapter cannot tell whether it was mentioned. That drop is now\n * logged rather than silent.\n */\n readonly botPhoneId?: string;\n /**\n * Comma-separated senders allowed to reach the handler. Absent leaves delivery unchanged;\n * an empty string admits nobody. See `allowlist.ts` for why those differ.\n */\n readonly allowedSenders?: string;\n}\n\n/**\n * Fail at the boundary when a required option is missing or blank.\n *\n * A factory that returns an adapter with an empty token has moved the error away from its\n * cause: the stack then names a send, and the mistake was in construction\n * (`rules/error-handling.md` § 2).\n */\nfunction requireNonEmpty(entries: ReadonlyArray<readonly [string, string | undefined]>): void {\n for (const [name, value] of entries) {\n if (value === undefined || value.trim().length === 0) {\n throw new ConfigurationError({\n code: \"missing_option\",\n message: `gateway-whatsapp: ${name} is required and must not be empty.`,\n });\n }\n }\n}\n\n/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */\nexport function digitsOnly(s: string): string {\n return s.replace(/[^\\d]/g, \"\");\n}\n\n/**\n * Characters that may appear INSIDE a written phone number: digits and the\n * separators people type around them. Anything else — a letter, a comma, a\n * newline — ends the run.\n */\nconst PHONE_RUN = /[\\d][\\d+\\-().  ]*[\\d]|[\\d]/g;\n\n/**\n * EC-7: the phone-like runs in a message, each normalized to digits.\n *\n * The filter used to normalize the WHOLE message and ask whether the result\n * contained the bot's number. That accepts the four documented formats, but it\n * also concatenates digits from unrelated words: with a bot at 5511999999999,\n * `\"pedido 55 chegou 11, ref 99999-9999 ok\"` normalized to a string containing\n * exactly that number, and the bot answered a message about an order. Every\n * group message carrying scattered digits woke it.\n *\n * Scanning runs instead keeps the separators irrelevant WITHIN a number — which\n * is what EC-7 asks for, and what `\"+55 (11) 99999-9999\"` needs — while letting\n * a letter or a comma do what it visually does: end the number.\n */\nexport function phoneRuns(s: string): string[] {\n return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);\n}\n\n/**\n * Adapter facade. Implements `BasePlatformAdapter` (D172).\n *\n * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`. The\n * constructor stays available for tests and for a backend of your own.\n */\nexport class WhatsAppAdapter extends BasePlatformAdapter {\n readonly platform = \"whatsapp\" as const;\n private readonly backendImpl: WhatsAppBackend;\n private readonly requireMention: boolean;\n private readonly botPhoneId: string;\n /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */\n private readonly allowedSenders: ReadonlySet<string> | undefined;\n /** Mirrors the sibling adapters: guards connect() against opening a second session. */\n private connected = false;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.\n private inboundUnsubscribe?: () => void;\n private statusUnsubscribe?: () => void;\n\n /**\n * Build an adapter from a discriminated configuration.\n *\n * The entry point for configuration that arrives as **data** — read from a file, an\n * environment, or a tenant record — where the backend is a string rather than a decision\n * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already\n * known at the call site.\n *\n * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union\n * was exported, documented and inert, which is the defect #47 was filed about, and the\n * first attempt at closing that issue left it inert — the factories took the config halves\n * directly and never the union.\n *\n * @throws {ConfigurationError} when a required option is missing or empty.\n * @public\n */\n static from(\n options: WhatsAppAdapterOptions,\n common: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n switch (options.backend) {\n case \"cloud\":\n return WhatsAppAdapter.fromCloud(options.cloud, common);\n case \"web\":\n return WhatsAppAdapter.fromWeb(options.web, common);\n case \"baileys\":\n return WhatsAppAdapter.fromBaileys(options.baileys, common);\n }\n }\n\n /**\n * Build a Baileys adapter.\n *\n * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number\n * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless\n * the number has no Cloud API access.\n *\n * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device\n * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily\n * at connect, so a consumer who never calls this never needs it installed.\n *\n * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`\n * is on (its default) drops every group message. The adapter logs when it does.\n *\n * @throws {ConfigurationError} when `sessionDir` is missing or empty.\n * @public\n */\n static fromBaileys(\n baileys: WhatsAppBaileysConfig,\n opts: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n requireNonEmpty([[\"sessionDir\", baileys.sessionDir]]);\n return new WhatsAppAdapter(\n new WhatsAppBaileysBackend({\n sessionDir: baileys.sessionDir,\n ...(baileys.connectTimeoutMs !== undefined\n ? { connectTimeoutMs: baileys.connectTimeoutMs }\n : {}),\n ...(baileys.sendTimeoutMs !== undefined ? { sendTimeoutMs: baileys.sendTimeoutMs } : {}),\n ...(baileys.onQr !== undefined ? { onQr: baileys.onQr } : {}),\n }),\n opts,\n );\n }\n\n /**\n * Build a Cloud-API adapter.\n *\n * The construction path this package's docblock has named since it was written, and which\n * did not exist until #47 — a consumer following the only guidance the package gave wrote\n * code that would not compile.\n *\n * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail\n * of this package rather than something every consumer imports and assembles.\n *\n * @throws {ConfigurationError} when a required credential is missing or empty.\n * @public\n */\n static fromCloud(\n cloud: WhatsAppCloudConfig,\n opts: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n // `appSecret` is deliberately NOT required: it verifies inbound webhook signatures\n // (`backend/cloud/index.ts`) and outbound never reads it. This repository's own\n // integration suite passes `\"\"` for exactly that reason, so requiring it would have\n // locked an outbound-only consumer out of the path this factory exists to offer.\n requireNonEmpty([\n [\"accessToken\", cloud.accessToken],\n [\"phoneNumberId\", cloud.phoneNumberId],\n ]);\n // INFO-10: an empty apiVersion yields `https://graph.facebook.com//<id>`, because the\n // client's `?? \"v18.0\"` does not catch `\"\"`. Absent is fine; blank is a mistake.\n if (cloud.apiVersion !== undefined) {\n requireNonEmpty([[\"apiVersion\", cloud.apiVersion]]);\n }\n return new WhatsAppAdapter(\n new WhatsAppCloudBackend({\n accessToken: cloud.accessToken,\n phoneNumberId: cloud.phoneNumberId,\n appSecret: cloud.appSecret,\n ...(cloud.apiVersion !== undefined ? { apiVersion: cloud.apiVersion } : {}),\n }),\n { ...opts, botPhoneId: opts.botPhoneId ?? cloud.phoneNumberId },\n );\n }\n\n /**\n * Build a WhatsApp-Web adapter.\n *\n * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms\n * do not sanction and which can get a number banned. It also needs a browser this package\n * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no\n * Cloud API access.\n *\n * @throws {ConfigurationError} when `sessionId` is missing or empty.\n * @public\n */\n static fromWeb(web: WhatsAppWebConfig, opts: WhatsAppAdapterCommonOptions = {}): WhatsAppAdapter {\n requireNonEmpty([[\"sessionId\", web.sessionId]]);\n return new WhatsAppAdapter(\n new WhatsAppWebBackend({\n sessionId: web.sessionId,\n ...(web.bridgeScriptPath !== undefined ? { bridgeScriptPath: web.bridgeScriptPath } : {}),\n }),\n opts,\n );\n }\n\n /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */\n constructor(backendImpl: WhatsAppBackend, opts: WhatsAppAdapterCommonOptions = {}) {\n super();\n this.backendImpl = backendImpl;\n this.requireMention = opts.requireMention ?? true;\n this.botPhoneId = digitsOnly(opts.botPhoneId ?? \"\");\n // Absent and empty are different answers. Absent means the operator has not adopted the\n // filter, and delivery is unchanged. Empty means they configured one and named nobody, which\n // is a decision — `parseAllowedSenders` is fail-closed and honours it.\n this.allowedSenders =\n opts.allowedSenders === undefined ? undefined : parseAllowedSenders(opts.allowedSenders);\n }\n\n /** Escape hatch (D180-style) for advanced features. */\n getBackend(): WhatsAppBackend {\n return this.backendImpl;\n }\n\n async connect(): Promise<boolean> {\n // Guard added 2026-08-17: this was the only adapter without one, so a second\n // connect() opened a second live WhatsApp session. Teams, SMS and Slack all\n // short-circuit here. Note it latches on SUCCESS only — a refused connect\n // must stay retryable, or one network blip becomes permanent.\n if (this.connected) return true;\n const ok = await this.backendImpl.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.handler = undefined;\n this.statusHandler = undefined;\n await this.backendImpl.disconnect();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n // EC-8: split filters empty parts internally.\n const parts = splitForWhatsApp(out.text);\n if (parts.length === 0) {\n return {\n ok: false,\n error: { code: \"empty_text\", message: \"Text reduced to zero parts after splitting.\" },\n };\n }\n let lastWamid: string | undefined;\n const isGroup = out.channel.type === \"group\";\n for (const part of parts) {\n const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });\n if (!r.ok) {\n return {\n ok: false,\n error: { code: r.error?.code ?? \"unknown\", message: r.error?.message ?? \"Send failed.\" },\n };\n }\n lastWamid = r.wamid;\n }\n return lastWamid !== undefined ? { ok: true, messageId: lastWamid } : { ok: true };\n }\n\n /**\n * Is this sender refused by a configured allowlist?\n *\n * Runs before the group/mention filter because it answers a different question: that one asks\n * whether a message was meant for us, this one asks whether the sender may reach us at all.\n *\n * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the\n * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.\n */\n private isRefusedBySenderAllowlist(inbound: WhatsAppInboundEvent): boolean {\n if (this.allowedSenders === undefined) return false;\n if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;\n process.stderr.write(\n `[whatsapp] dropped inbound from \"${inbound.fromPhone}\" — not in the configured allowlist\\n`,\n );\n return true;\n }\n\n /** D309 + EC-7: group filter with digit-only normalization. */\n private shouldDropGroupMessage(inbound: WhatsAppInboundEvent): boolean {\n if (inbound.conversationType !== \"group\" || !this.requireMention) return false;\n if (this.botPhoneId.length === 0) {\n // Misconfigured: with no id to look for, every group message looks unaddressed. Saying\n // so matters more here than anywhere — the sibling allowlist check makes the same point\n // fifteen lines below, and a gateway that answers no group message and explains nothing\n // is indistinguishable from a broken one. Common with `fromWeb`, which has no phone\n // number id to default from.\n process.stderr.write(\n \"[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\\n\",\n );\n return true;\n }\n return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));\n }\n\n private toMessageEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent {\n return {\n id: inbound.wamid,\n platform: \"whatsapp\",\n sender: { id: inbound.fromPhone, displayName: inbound.contactName },\n channel: { id: inbound.channelId, type: inbound.conversationType },\n text: inbound.text,\n receivedAt: inbound.receivedAt,\n whatsapp: {\n wamid: inbound.wamid,\n phoneNumberId: inbound.phoneNumberId,\n contactName: inbound.contactName,\n backend: inbound.backend,\n raw: inbound.raw,\n },\n };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.inboundUnsubscribe?.();\n this.handler = handler;\n\n const off = this.backendImpl.onInbound(async (inbound) => {\n if (!this.handler) return;\n if (this.isRefusedBySenderAllowlist(inbound)) return;\n if (this.shouldDropGroupMessage(inbound)) return;\n await this.handler(this.toMessageEvent(inbound));\n });\n this.inboundUnsubscribe = off;\n\n return () => {\n // Identity-guarded, like every sibling adapter. Without the guard this closure tore down\n // whatever subscription was CURRENT: `onInbound(A)` → `onInbound(B)` → A's stale `off()`\n // killed B's and nulled the handler, and the gateway went silent with no error. That is\n // the defect the cross-adapter contract exists to catch, and this adapter was exempted\n // from it by a comment claiming its mechanism gave \"the same guarantee\" — it had no\n // guard at all.\n if (this.handler === handler) {\n this.handler = undefined;\n off();\n this.inboundUnsubscribe = undefined;\n }\n };\n }\n\n /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusUnsubscribe?.();\n this.statusHandler = handler;\n const off = this.backendImpl.onStatusReceipt(async (r) => {\n await this.statusHandler?.(r);\n });\n this.statusUnsubscribe = off;\n return () => {\n // Same identity guard, same reason. A stale unsubscribe must be a no-op.\n if (this.statusHandler === handler) {\n this.statusHandler = undefined;\n off();\n this.statusUnsubscribe = undefined;\n }\n };\n }\n}\n"]}