@12-apps/messaging 1.4.0 → 1.6.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.
- package/README.md +42 -0
- package/dist/{channel-CZjNEBLC.d.ts → channel-BWhnnuip.d.ts} +22 -2
- package/dist/chunk-RXJNLPY4.js +560 -0
- package/dist/chunk-RXJNLPY4.js.map +1 -0
- package/dist/{engine-BJse1HAX.d.ts → engine-BybESJ7p.d.ts} +27 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +65 -8
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/whatsapp/index.d.ts +1 -1
- package/dist/whatsapp/index.js +22 -536
- package/dist/whatsapp/index.js.map +1 -1
- package/dist/whatsapp-web/index.d.ts +504 -0
- package/dist/whatsapp-web/index.js +956 -0
- package/dist/whatsapp-web/index.js.map +1 -0
- package/package.json +5 -1
- package/src/core/inbound.ts +6 -1
- package/src/core/ports.ts +16 -0
- package/src/core/sent-elsewhere.ts +87 -0
- package/src/core/types.ts +22 -1
- package/src/index.ts +1 -0
- package/src/whatsapp-web/adapter.ts +62 -0
- package/src/whatsapp-web/auth-state.ts +92 -0
- package/src/whatsapp-web/baileys-port.ts +168 -0
- package/src/whatsapp-web/choices.ts +126 -0
- package/src/whatsapp-web/envelope.ts +97 -0
- package/src/whatsapp-web/history.ts +171 -0
- package/src/whatsapp-web/index.ts +50 -0
- package/src/whatsapp-web/media.ts +78 -0
- package/src/whatsapp-web/normalize.ts +223 -0
- package/src/whatsapp-web/own-sends.ts +124 -0
- package/src/whatsapp-web/session.ts +391 -0
- package/src/whatsapp-web/timers.ts +19 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/whatsapp-web/envelope.ts","../../src/whatsapp-web/adapter.ts","../../src/whatsapp-web/auth-state.ts","../../src/whatsapp-web/baileys-port.ts","../../src/whatsapp-web/choices.ts","../../src/whatsapp-web/normalize.ts","../../src/whatsapp-web/timers.ts","../../src/whatsapp-web/history.ts","../../src/whatsapp-web/own-sends.ts","../../src/whatsapp-web/media.ts","../../src/whatsapp-web/session.ts"],"sourcesContent":["import type { InboundContent, NormalizedEvent, ReceiptStatus } from \"../core/types\";\n\n/**\n * The raw body a session hands the engine's inbox.\n *\n * The inbox stores every delivery raw before processing it, and re-parses it\n * on a retry. A socket has no HTTP body, so the session writes one: its\n * already-normalized events, as JSON. Never Baileys' own message objects —\n * they carry media keys and the full protobuf, and the inbox keeps what it\n * is given.\n *\n * `{ \"format\": \"whatsapp-web/1\", \"events\": [...] }`, dates as ISO strings.\n */\nexport const ENVELOPE_FORMAT = \"whatsapp-web/1\";\n\nexport function encodeEnvelope(events: readonly NormalizedEvent[]): string {\n return JSON.stringify({ format: ENVELOPE_FORMAT, events });\n}\n\ntype Json = Record<string, unknown>;\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst str = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\nconst strOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\nconst date = (value: unknown): Date | null => {\n const parsed = typeof value === \"string\" ? new Date(value) : null;\n return parsed && Number.isFinite(parsed.getTime()) ? parsed : null;\n};\n\nconst RECEIPTS: readonly ReceiptStatus[] = [\"SENT\", \"DELIVERED\", \"READ\", \"FAILED\"];\n\nconst CONTENT: Readonly<Record<string, (value: Json) => InboundContent | null>> = {\n TEXT: (value) => (typeof value.text === \"string\" ? { kind: \"TEXT\", text: value.text } : null),\n INTERACTIVE: (value) => (str(value.replyId) ? { kind: \"INTERACTIVE\", replyId: value.replyId as string, title: strOrNull(value.title) ?? \"\" } : null),\n AUDIO: (value) => (str(value.mediaId) ? { kind: \"AUDIO\", mediaId: value.mediaId as string, mimeType: strOrNull(value.mimeType) } : null),\n OTHER: (value) => (str(value.channelType) ? { kind: \"OTHER\", channelType: value.channelType as string } : null),\n};\n\nfunction content(value: unknown): InboundContent | null {\n if (!isObject(value) || typeof value.kind !== \"string\") return null;\n return CONTENT[value.kind]?.(value) ?? null;\n}\n\nfunction messageEvent(value: Json, accountId: string): NormalizedEvent | null {\n const contactId = str(value.contactId);\n const externalId = str(value.externalId);\n const sentAt = date(value.sentAt);\n const body = content(value.content);\n if (!contactId || !externalId || !sentAt || !body) return null;\n return { type: \"message\", accountId, contactId, contactName: strOrNull(value.contactName), externalId, sentAt, content: body, optOut: value.optOut === true };\n}\n\nfunction statusEvent(value: Json, accountId: string): NormalizedEvent | null {\n const externalId = str(value.externalId);\n const at = date(value.at);\n const status = RECEIPTS.find((receipt) => receipt === value.status);\n if (!externalId || !at || !status) return null;\n const optional = { contactId: strOrNull(value.contactId), error: strOrNull(value.error), callbackData: strOrNull(value.callbackData) };\n return { type: \"status\", accountId, externalId, status, at, ...optional };\n}\n\nfunction optOutEvent(value: Json, accountId: string): NormalizedEvent | null {\n const contactId = str(value.contactId);\n const at = date(value.at);\n return contactId && at ? { type: \"opt_out\", accountId, contactId, at } : null;\n}\n\nfunction sentElsewhereEvent(value: Json, accountId: string): NormalizedEvent | null {\n const contactId = str(value.contactId);\n const externalId = str(value.externalId);\n const sentAt = date(value.sentAt);\n const body = content(value.content);\n if (!contactId || !externalId || !sentAt || !body) return null;\n return { type: \"sent_elsewhere\", accountId, contactId, externalId, sentAt, content: body };\n}\n\nconst EVENTS: Readonly<Record<string, (value: Json, accountId: string) => NormalizedEvent | null>> = {\n message: messageEvent,\n status: statusEvent,\n opt_out: optOutEvent,\n sent_elsewhere: sentElsewhereEvent,\n};\n\nfunction event(value: unknown): NormalizedEvent | null {\n if (!isObject(value) || typeof value.type !== \"string\") return null;\n const accountId = str(value.accountId);\n return accountId ? (EVENTS[value.type]?.(value, accountId) ?? null) : null;\n}\n\n/**\n * An envelope's events, in order. Another format, or an event of an unknown\n * shape, yields nothing for it; only bytes that are not JSON throw.\n */\nexport function parseEnvelope(rawBody: string): NormalizedEvent[] {\n const payload = JSON.parse(rawBody) as unknown;\n if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];\n return payload.events.map(event).filter((parsed): parsed is NormalizedEvent => parsed !== null);\n}\n","import { ChannelMediaFailure, ChannelSendFailure, OPEN_SEND_POLICY, type ChannelAdapter, type SendPolicy } from \"../core/channel\";\nimport { WHATSAPP_CHANNEL } from \"../whatsapp\";\nimport { parseEnvelope } from \"./envelope\";\nimport type { WhatsAppWebSession } from \"./session\";\n\nexport interface WhatsAppWebAdapterConfig {\n /**\n * The session that serves an account: one session, or a lookup by the\n * connection's account id (the linked number's digits). A session serves\n * only the account it is linked to.\n */\n sessions: WhatsAppWebSession | ((accountId: string) => WhatsAppWebSession | undefined);\n /**\n * The channel key. Default `whatsapp`, the Cloud adapter's: a host switches a\n * number between the two transports by mounting one adapter or the other,\n * and its connections and conversations stay where they are. Give another\n * key (`whatsapp-web`) to run both side by side.\n */\n kind?: string;\n /**\n * When free-form sends are allowed. Default: always. A personal account has\n * no service window; that window is a rule of the Business API.\n */\n policy?: SendPolicy;\n}\n\n/**\n * The WhatsApp Web adapter: the same `ChannelAdapter` as the Cloud one, over\n * a Baileys session instead of the Graph API.\n *\n * - `handshake` and `verify`: there is no webhook. The verify FAILS CLOSED,\n * so the webhook route refuses any POST to this channel: inbound arrives\n * only from the session's own socket, through `engine.receive`.\n * - `parse` reads the session's envelope (normalized events, never Baileys'\n * raw objects).\n * - `send` and `fetchMedia` go through the session. The connection's\n * credential is not used: the linked device's keys live in the session's\n * auth store.\n */\nexport function createWhatsAppWebAdapter(config: WhatsAppWebAdapterConfig): ChannelAdapter {\n const sessionFor = (accountId: string): WhatsAppWebSession | undefined => {\n if (typeof config.sessions === \"function\") return config.sessions(accountId);\n return config.sessions.accountId() === accountId ? config.sessions : undefined;\n };\n return {\n kind: config.kind ?? WHATSAPP_CHANNEL,\n handshake: () => null,\n verify: () => false,\n parse: parseEnvelope,\n send: async ({ accountId, to, content }) => {\n const session = sessionFor(accountId);\n if (!session) throw new ChannelSendFailure(\"NOT_CONNECTED\", \"no open WhatsApp Web session for this account\");\n return session.send(to, content);\n },\n fetchMedia: async ({ accountId, mediaId, maxBytes, timeoutMs }) => {\n const session = sessionFor(accountId);\n if (!session) throw new ChannelMediaFailure(\"NOT_CONNECTED\", \"no open WhatsApp Web session for this account\");\n return session.downloadMedia(mediaId, { maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) });\n },\n policy: config.policy ?? OPEN_SEND_POLICY,\n };\n}\n","import type { BaileysAuthState, BaileysModule } from \"./baileys-port\";\n\n/**\n * WHERE A LINKED SESSION'S KEYS LIVE. The host's, never the package's.\n *\n * A Baileys session is a linked device: its auth state (the account's\n * identity and Signal keys) gives whoever holds it full access to the\n * account, every chat included. The package therefore writes NOTHING itself:\n * the host passes a store, and decides where it lives and how it is sealed\n * (an encrypted column, a secrets manager, a 0600 file on the owner's\n * machine). The package never logs a value, never puts one in an error.\n *\n * Values are opaque JSON text (Baileys' `BufferJSON`); keys are\n * `creds` and `<category>-<id>`.\n */\nexport interface AuthStateStore {\n read(key: string): Promise<string | null>;\n write(key: string, value: string): Promise<void>;\n remove(key: string): Promise<void>;\n /** Remove every key of this session. Optional: without it, a logout removes only `creds`, which already unlinks it. */\n clear?(): Promise<void>;\n}\n\n/** An in-memory store: for tests, and for a session that may be lost at restart (it must pair again). */\nexport function createMemoryAuthStateStore(): AuthStateStore & { keys(): string[]; clear(): Promise<void> } {\n const values = new Map<string, string>();\n return {\n read: async (key) => values.get(key) ?? null,\n write: async (key, value) => {\n values.set(key, value);\n },\n remove: async (key) => {\n values.delete(key);\n },\n keys: () => [...values.keys()],\n clear: async () => {\n values.clear();\n },\n };\n}\n\nconst CREDS_KEY = \"creds\";\nconst APP_STATE_SYNC_KEY = \"app-state-sync-key\";\n\n/**\n * Baileys' auth state over a host store: the same recipe as Baileys' own\n * `useMultiFileAuthState`, with the store in place of the folder. A store with\n * no creds yet starts a NEW device (the session pairs); `saveCreds` must run on\n * every `creds.update`.\n */\nexport async function loadAuthState(\n baileys: Pick<BaileysModule<unknown>, \"initAuthCreds\" | \"BufferJSON\" | \"proto\">,\n store: AuthStateStore,\n): Promise<{ state: BaileysAuthState; saveCreds: () => Promise<void>; isNew: boolean }> {\n const encode = (value: unknown): string => JSON.stringify(value, baileys.BufferJSON.replacer);\n const decode = (text: string | null): unknown => (text === null ? null : (JSON.parse(text, baileys.BufferJSON.reviver) as unknown));\n\n const stored = decode(await store.read(CREDS_KEY));\n const isNew = stored === null || typeof stored !== \"object\";\n const creds = isNew ? baileys.initAuthCreds() : (stored as object);\n const appStateKey = baileys.proto?.Message?.AppStateSyncKeyData;\n\n const state: BaileysAuthState = {\n creds,\n keys: {\n get: async (type, ids) => {\n const found: Record<string, unknown> = {};\n await Promise.all(\n ids.map(async (id) => {\n let value = decode(await store.read(`${type}-${id}`));\n if (type === APP_STATE_SYNC_KEY && value && appStateKey) value = appStateKey.fromObject(value);\n found[id] = value ?? undefined;\n }),\n );\n return found;\n },\n set: async (data) => {\n const writes = Object.entries(data).flatMap(([category, entries]) =>\n Object.entries(entries).map(([id, value]) => (value ? store.write(`${category}-${id}`, encode(value)) : store.remove(`${category}-${id}`))),\n );\n await Promise.all(writes);\n },\n },\n };\n return { state, saveCreds: () => store.write(CREDS_KEY, encode(creds)), isNew };\n}\n\n/** Forget a session's keys, after a logout: the next start pairs a NEW device. */\nexport async function clearAuthState(store: AuthStateStore): Promise<void> {\n if (store.clear) await store.clear();\n else await store.remove(CREDS_KEY);\n}\n","/**\n * The slice of Baileys (`baileys` / `@whiskeysockets/baileys`, v7) this layer\n * uses, typed STRUCTURALLY. The package never imports Baileys: the host passes\n * the module it installed (`import * as baileys from \"baileys\"`), so a host on\n * the official Cloud adapter never installs it, and the suites drive a fake.\n *\n * Every shape here is what Baileys 7.0.0 declares, narrowed to the fields read.\n * Anything wider is left `unknown` and read defensively.\n */\n\n/** A protobuf `Long`, as Baileys hands timestamps: a number, or `{ low, high }`. */\nexport type LongLike = number | string | { low: number; high: number; unsigned?: boolean } | null | undefined;\n\n/** `WAMessageKey`: Baileys' `proto.IMessageKey` plus the v7 LID alternates. */\nexport interface BaileysMessageKey {\n remoteJid?: string | null;\n /** The same chat's other address: the phone-number JID when `remoteJid` is a LID, and back. */\n remoteJidAlt?: string | null;\n fromMe?: boolean | null;\n id?: string | null;\n participant?: string | null;\n}\n\n/** `WAMessage` (`proto.IWebMessageInfo`), the fields read. `message` is the raw `proto.IMessage`. */\nexport interface BaileysMessage {\n key: BaileysMessageKey;\n message?: object | null;\n messageTimestamp?: number | { low: number; high: number } | null;\n pushName?: string | null;\n /** `proto.WebMessageInfo.Status`: 0 ERROR, 1 PENDING, 2 SERVER_ACK, 3 DELIVERY_ACK, 4 READ, 5 PLAYED. */\n status?: number | null;\n}\n\n/** One `messages.update` entry. */\nexport interface BaileysMessageUpdate {\n key: BaileysMessageKey;\n update: { status?: number | null } & Record<string, unknown>;\n}\n\n/** The close reason Baileys reports: a Boom, whose `output.statusCode` is the `DisconnectReason`. */\nexport interface BaileysDisconnect {\n error?: { output?: { statusCode?: number }; message?: string } | Error | null | undefined;\n date?: Date;\n}\n\nexport interface BaileysConnectionUpdate {\n connection?: \"open\" | \"connecting\" | \"close\";\n lastDisconnect?: BaileysDisconnect;\n qr?: string;\n}\n\n/** `messaging-history.set`: a history sync. `syncType` is `proto.HistorySync.HistorySyncType` (6 is ON_DEMAND), a number or its name. */\nexport interface BaileysHistorySet<Msg extends BaileysMessage = BaileysMessage> {\n messages: Msg[];\n syncType?: number | string | null;\n /** The id `fetchMessageHistory` returned, on the answer to that request. */\n peerDataRequestSessionId?: string | null;\n isLatest?: boolean;\n}\n\n/** `WAPresence` values this layer sends. */\nexport type BaileysPresence = \"composing\" | \"paused\";\n\n/** The events this layer listens to, by Baileys' own names. */\nexport interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {\n \"connection.update\": BaileysConnectionUpdate;\n \"creds.update\": Record<string, unknown>;\n \"messages.upsert\": { messages: Msg[]; type: \"notify\" | \"append\" | string };\n \"messages.update\": BaileysMessageUpdate[];\n \"messaging-history.set\": BaileysHistorySet<Msg>;\n}\n\n/** `SignalKeyStore`: keyed by category, then id. A null value deletes. */\nexport interface BaileysKeyStore {\n get(type: string, ids: string[]): Promise<Record<string, unknown>>;\n set(data: Record<string, Record<string, unknown>>): Promise<void>;\n}\n\n/** `AuthenticationState`, as this layer builds it. `creds` and every key are Baileys' own values, opaque here. */\nexport interface BaileysAuthState {\n creds: object;\n keys: BaileysKeyStore;\n}\n\n/** The socket `makeWASocket` returns, the members used. */\n/** `Msg` is Baileys' own `WAMessage`, inferred from the module: messages go back to Baileys as they came. */\nexport interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {\n ev: {\n on<E extends keyof BaileysEventMap>(event: E, listener: (data: BaileysEventMap<Msg>[E]) => void): void;\n };\n /** The linked account, once open: `id` is `5511999999999:12@s.whatsapp.net`. */\n user?: { id?: string | null | undefined } | null | undefined;\n sendMessage(jid: string, content: { text: string }): Promise<Msg | undefined>;\n /** `sendPresenceUpdate(type, toJid?)`: \"digitando…\" (`composing`) or its end (`paused`) in one chat. */\n sendPresenceUpdate(type: BaileysPresence, toJid?: string): Promise<void>;\n /** `readMessages(keys)`: marks those messages read (blue ticks). */\n readMessages(keys: BaileysMessageKey[]): Promise<void>;\n /**\n * `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)`: asks the phone for up to `count` messages\n * before that one. Returns the request id; the answer arrives on `messaging-history.set`.\n */\n fetchMessageHistory(count: number, oldestMsgKey: BaileysMessageKey, oldestMsgTimestamp: number): Promise<string>;\n requestPairingCode(phoneNumber: string): Promise<string>;\n logout(msg?: string): Promise<void>;\n end(error: Error | undefined): Promise<void> | void;\n /** Asks the phone to re-upload expired media; passed to `downloadMediaMessage`. */\n updateMediaMessage?(message: Msg): Promise<Msg>;\n}\n\n/** Baileys' `ILogger`: pino satisfies it. */\nexport interface BaileysLogger {\n level: string;\n child(obj: Record<string, unknown>): BaileysLogger;\n trace(obj: unknown, msg?: string): void;\n debug(obj: unknown, msg?: string): void;\n info(obj: unknown, msg?: string): void;\n warn(obj: unknown, msg?: string): void;\n error(obj: unknown, msg?: string): void;\n}\n\n/** The members of the Baileys MODULE this layer calls. `import * as baileys from \"baileys\"` satisfies it. */\n/**\n * `Auth` is Baileys' own `AuthenticationState` and `Msg` its `WAMessage`, inferred from the module the\n * host passes. The layer builds it from the host's store, where the values are\n * Baileys' own, serialized by its `BufferJSON`.\n */\nexport interface BaileysModule<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {\n makeWASocket(config: {\n auth: Auth;\n logger?: BaileysLogger;\n browser?: [string, string, string];\n markOnlineOnConnect?: boolean;\n syncFullHistory?: boolean;\n }): BaileysSocket<Msg>;\n initAuthCreds(): object;\n BufferJSON: {\n replacer(key: string, value: unknown): unknown;\n reviver(key: string, value: unknown): unknown;\n };\n downloadMediaMessage(\n message: Msg,\n type: \"buffer\",\n options: Record<string, unknown>,\n ctx?: { logger?: BaileysLogger; reuploadRequest?: (message: Msg) => Promise<Msg> },\n ): Promise<Uint8Array>;\n /** Optional: rebuilds an app-state sync key read back from storage (Baileys' own file store does). */\n proto?: { Message?: { AppStateSyncKeyData?: { fromObject(value: unknown): unknown } } };\n}\n\n/** Baileys' `DisconnectReason` values this layer acts on. */\nexport const DISCONNECT = {\n /** The phone unlinked this device, or the session was logged out: never reconnect. */\n loggedOut: 401,\n /** Another client took the session over. Reconnecting would fight it: stop. */\n connectionReplaced: 440,\n /** The account is banned or the session is unusable: stop. */\n forbidden: 403,\n /** Baileys asks for a fresh socket right after pairing: reconnect at once. */\n restartRequired: 515,\n} as const;\n\n/** The close's `DisconnectReason`, or null when Baileys gave none. */\nexport function disconnectCode(disconnect: BaileysDisconnect | undefined): number | null {\n const error = disconnect?.error;\n if (!error || typeof error !== \"object\" || !(\"output\" in error)) return null;\n const code = error.output?.statusCode;\n return typeof code === \"number\" ? code : null;\n}\n","import type { InboundContent, NormalizedEvent, OutboundContent } from \"../core/types\";\n\n/**\n * The choices a personal account offered, remembered so the contact's typed\n * answer reads as the tap it stands for.\n *\n * A personal account cannot send reply buttons or lists: `renderOutboundText`\n * sends them as numbered lines, and the contact answers with text. An agent\n * built for the Cloud adapter expects `INTERACTIVE { replyId, title }`. This\n * module keeps the last choices offered to each contact (in memory, bounded,\n * expiring) and turns an answer that is EXACTLY a listed number or EXACTLY a\n * choice's title into that `INTERACTIVE`. Anything else stays `TEXT`.\n *\n * An offer maps only the first reply after it: any later message to that\n * contact, from this session (plain text included) or from the owner's phone\n * (`sent_elsewhere`), clears it, because the \"1\" that follows answers that.\n */\n\n/** One offered choice: the id the agent gave it and the title the contact sees. */\nexport interface OfferedChoice {\n replyId: string;\n title: string;\n}\n\n/** The choices an outbound message offers, in the order {@link renderOutboundText} numbers them. Empty for plain text. */\nexport function choicesOf(content: OutboundContent): OfferedChoice[] {\n if (content.kind === \"TEXT\") return [];\n if (content.kind === \"BUTTONS\") return content.buttons.map((button) => ({ replyId: button.id, title: button.title }));\n return content.sections.flatMap((section) => section.rows.map((row) => ({ replyId: row.id, title: row.title })));\n}\n\n/** Case, accents and spacing out of the way: `\" Sim, Por Favor \"` and `\"sim, por favor\"` are one title. */\nexport function foldTitle(value: string): string {\n return value.normalize(\"NFD\").replace(/\\p{M}/gu, \"\").toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\n/** `\"1\"`, `\"1.\"`, `\" 2 \"`, `\"3)\"` → the number; anything else (`\"1 pizza\"`, `\"2x\"`) → null. */\nexport function listedNumber(value: string): number | null {\n // Trimmed and bounded first, so the pattern has one whitespace run and stays linear on any input.\n const text = value.trim();\n if (text.length > 8) return null;\n const match = /^(\\d{1,3})(?:\\s*[.)])?$/.exec(text);\n return match ? Number(match[1]) : null;\n}\n\ninterface Offer {\n choices: readonly OfferedChoice[];\n folded: readonly string[];\n at: number;\n}\n\nexport interface ChoiceMemoryOptions {\n /** How many contacts are remembered; the least recently offered goes first. Default 500. */\n maxContacts?: number;\n /** How long an offer stays answerable. Default 2 hours. */\n ttlMs?: number;\n now?(): Date;\n}\n\nexport class ChoiceMemory {\n private readonly offers = new Map<string, Offer>();\n private readonly maxContacts: number;\n private readonly ttlMs: number;\n private readonly now: () => Date;\n\n constructor(options: ChoiceMemoryOptions = {}) {\n this.maxContacts = options.maxContacts ?? 500;\n this.ttlMs = options.ttlMs ?? 2 * 60 * 60 * 1000;\n this.now = options.now ?? (() => new Date());\n }\n\n /** Remember what was just sent to a contact: its choices replace the earlier offer, and plain text clears it. */\n offer(contactId: string, content: OutboundContent): void {\n const choices = choicesOf(content);\n this.offers.delete(contactId);\n if (choices.length === 0) return;\n this.offers.set(contactId, { choices, folded: choices.map((choice) => foldTitle(choice.title)), at: this.now().getTime() });\n for (const oldest of this.offers.keys()) {\n if (this.offers.size <= this.maxContacts) break;\n this.offers.delete(oldest);\n }\n }\n\n /**\n * The choice a typed answer stands for, or null. A listed number wins over a\n * title. A match uses the offer up (the answer was given); a miss, an\n * expired offer or a contact never offered anything clears nothing.\n */\n resolve(contactId: string, answer: string): OfferedChoice | null {\n const offer = this.offers.get(contactId);\n if (!offer) return null;\n if (this.now().getTime() - offer.at > this.ttlMs) {\n this.offers.delete(contactId);\n return null;\n }\n const number = listedNumber(answer);\n const index = number === null ? offer.folded.indexOf(foldTitle(answer)) : number - 1;\n const choice = offer.choices[index];\n if (!choice || index < 0) return null;\n this.offers.delete(contactId);\n return choice;\n }\n\n /** Something else was said to the contact since: the offer no longer maps their reply. */\n forget(contactId: string): void {\n this.offers.delete(contactId);\n }\n\n get size(): number {\n return this.offers.size;\n }\n}\n\n/**\n * The events, in socket order, with each TEXT answer that picks an offered choice read as `INTERACTIVE`. A\n * `sent_elsewhere` clears its contact's offer. Every other event is returned as it came.\n */\nexport function applyChoices(memory: ChoiceMemory, events: readonly NormalizedEvent[]): NormalizedEvent[] {\n return events.map((event) => {\n if (event.type === \"sent_elsewhere\") memory.forget(event.contactId);\n if (event.type !== \"message\" || event.content.kind !== \"TEXT\") return event;\n const choice = memory.resolve(event.contactId, event.content.text);\n const content: InboundContent | null = choice ? { kind: \"INTERACTIVE\", replyId: choice.replyId, title: choice.title } : null;\n return content ? { ...event, content } : event;\n });\n}\n","import type { InboundContent, NormalizedEvent, ReceiptStatus, SentElsewhereEvent, StatusEvent } from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"../whatsapp/opt-out\";\nimport type { BaileysMessage, BaileysMessageKey, BaileysMessageUpdate, LongLike } from \"./baileys-port\";\n\n/**\n * Baileys' socket events → the engine's normalized events: the SAME\n * `NormalizedEvent`s the Cloud webhook's parser produces, so the inbox, the\n * dedupe, the conversations and the retention cannot tell the transports apart.\n *\n * Read defensively: an unknown shape is skipped, never thrown on. What is\n * left out, on purpose:\n * - groups, broadcast lists, Status and channels (`@g.us`, `@broadcast`,\n * `@newsletter`): the engine's conversation is one contact;\n * - messages the account sent itself (`fromMe`) are NOT inbound: `normalizeUpsert`\n * drops them, and `normalizeSentElsewhere` reads them as a separate event (the\n * session drops the echo of its own sends before it hands them on);\n * - history sync (`messages.upsert` of type `append`, `messaging-history.set`):\n * only live messages reach the inbox; on-demand history never leaves the session;\n * - protocol messages (a deletion, an edit, a key distribution).\n */\n\ntype Json = Record<string, unknown>;\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\nconst PN_SUFFIX = \"@s.whatsapp.net\";\nconst LID_SUFFIX = \"@lid\";\n\n/** A JID's user part, without the device (`5511…:12@s.whatsapp.net` → `5511…`). */\nexport function jidUser(jid: string): string {\n const user = jid.slice(0, jid.indexOf(\"@\") >= 0 ? jid.indexOf(\"@\") : jid.length);\n const colon = user.indexOf(\":\");\n return colon >= 0 ? user.slice(0, colon) : user;\n}\n\n/**\n * The contact's address, as the engine stores it. A phone-number JID becomes\n * its digits (`5511987654321`), the same address the Cloud API's `wa_id` is.\n * A contact WhatsApp only names by a LID keeps the whole LID JID\n * (`123456@lid`): the send path routes it back as is. Null for anything that\n * is not one person.\n */\nexport function contactAddress(key: BaileysMessageKey): string | null {\n const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid): jid is string => typeof jid === \"string\");\n const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));\n if (pn) return jidUser(pn) || null;\n const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));\n return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;\n}\n\n/** The JID a send goes to, for an address `contactAddress` produced (or plain digits). */\nexport function addressJid(address: string): string {\n if (address.includes(\"@\")) return address;\n const digits = address.replace(/\\D/g, \"\");\n return `${digits}${PN_SUFFIX}`;\n}\n\n/**\n * The address a contact's reply to a send will carry, keyed as {@link contactAddress} keys an inbound message:\n * `+55 11 98765-4321`, `5511987654321` and `5511987654321:12@s.whatsapp.net` are all `5511987654321`, and a LID\n * the socket reports beside its phone-number JID (`sentKey.remoteJidAlt`) is that number. Null when it is not one person.\n */\nexport function replyAddress(to: string, sentKey?: BaileysMessageKey | null): string | null {\n return contactAddress({ remoteJid: addressJid(to), remoteJidAlt: sentKey?.remoteJidAlt ?? null });\n}\n\n/** A protobuf Long (a timestamp in seconds, a byte length) as a positive number, or null. */\nexport function longNumber(value: LongLike): number | null {\n if (typeof value === \"number\") return Number.isFinite(value) && value > 0 ? value : null;\n if (typeof value === \"string\") return longNumber(Number(value));\n if (isObject(value) && typeof value.low === \"number\" && typeof value.high === \"number\") {\n return longNumber(value.high * 2 ** 32 + (value.low >>> 0));\n }\n return null;\n}\n\n/** Wrappers whose inner `message` is the real content. */\nconst WRAPPERS = [\"ephemeralMessage\", \"viewOnceMessage\", \"viewOnceMessageV2\", \"viewOnceMessageV2Extension\", \"documentWithCaptionMessage\", \"editedMessage\"];\n/** Fields of a message that are never its content. */\nconst NOT_CONTENT = new Set([\"messageContextInfo\", \"senderKeyDistributionMessage\"]);\n/** Content that is not a message a person reads: skipped whole. */\nconst SKIPPED = new Set([\"protocolMessage\", \"reactionMessage\", \"pollUpdateMessage\", \"keepInChatMessage\"]);\n\n/** A message's real content, out of its ephemeral, view-once or edit wrappers. `{}` for anything else. */\nexport function unwrapMessage(message: unknown): Json {\n if (!isObject(message)) return {};\n for (const wrapper of WRAPPERS) {\n const inner = message[wrapper];\n if (isObject(inner) && isObject(inner.message)) return unwrapMessage(inner.message);\n }\n return message;\n}\n\ntype Reader = (body: unknown) => InboundContent | null;\n\nconst interactive = (replyId: unknown, title: unknown): InboundContent | null =>\n text(replyId) ? { kind: \"INTERACTIVE\", replyId: replyId as string, title: text(title) ?? \"\" } : null;\n\n/** How each content type a person reads is read. A type not listed is OTHER. */\nconst READERS: Readonly<Record<string, Reader>> = {\n conversation: (body) => (text(body) ? { kind: \"TEXT\", text: body as string } : null),\n extendedTextMessage: (body) => (isObject(body) && text(body.text) ? { kind: \"TEXT\", text: body.text as string } : null),\n buttonsResponseMessage: (body) => (isObject(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null),\n templateButtonReplyMessage: (body) => (isObject(body) ? interactive(body.selectedId, body.selectedDisplayText) : null),\n listResponseMessage: (body) =>\n isObject(body) && isObject(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null,\n // The media id is filled with the message id by the caller.\n audioMessage: (body) => (isObject(body) ? { kind: \"AUDIO\", mediaId: \"\", mimeType: text(body.mimetype) } : null),\n};\n\n/** The message's content, or null to skip it. */\nexport function contentOf(raw: unknown): InboundContent | null {\n const message = unwrapMessage(raw);\n const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== undefined);\n if (!type || SKIPPED.has(type)) return null;\n const reader = READERS[type];\n return reader ? reader(message[type]) : { kind: \"OTHER\", channelType: type.replace(/Message$/, \"\") || type };\n}\n\nexport interface NormalizeOptions {\n /** The whole-message words that opt a contact out. Default: the Cloud adapter's. */\n optOutKeywords?: readonly string[];\n}\n\n/** One message → its inbound event, or null when it is not one a contact sent to this account. */\nfunction inboundEvent(accountId: string, message: BaileysMessage, keywords: readonly string[]): NormalizedEvent | null {\n if (!isObject(message) || !isObject(message.key) || message.key.fromMe) return null;\n const id = text(message.key.id);\n const contactId = contactAddress(message.key);\n const seconds = longNumber(message.messageTimestamp);\n const content = contentOf(message.message);\n if (!id || !contactId || seconds === null || !content) return null;\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: text(message.pushName),\n externalId: id,\n sentAt: new Date(seconds * 1000),\n // An audio's media id is the message's own id: the session keeps the message to download it.\n content: content.kind === \"AUDIO\" ? { ...content, mediaId: id } : content,\n optOut: content.kind === \"TEXT\" && isOptOutText(content.text, keywords),\n };\n}\n\n/** One live `messages.upsert` → inbound message events. `accountId` is the linked account's digits. */\nexport function normalizeUpsert(\n accountId: string,\n upsert: { messages: readonly BaileysMessage[]; type: string },\n options: NormalizeOptions = {},\n): NormalizedEvent[] {\n if (upsert.type !== \"notify\") return [];\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event): event is NormalizedEvent => event !== null);\n}\n\n/** What a message the account sent from another device carried: its text, or `OTHER` for anything else (never media keys). */\nfunction sentContent(raw: unknown): InboundContent | null {\n const content = contentOf(raw);\n if (!content) return null;\n if (content.kind === \"AUDIO\") return { kind: \"OTHER\", channelType: \"audio\" };\n return content.kind === \"INTERACTIVE\" ? { kind: \"TEXT\", text: content.title } : content;\n}\n\n/** One message → the event for a message the account sent itself, or null when it is not one a person sent to one contact. */\nfunction sentElsewhereEvent(accountId: string, message: BaileysMessage): SentElsewhereEvent | null {\n if (!isObject(message) || !isObject(message.key) || !message.key.fromMe) return null;\n const id = text(message.key.id);\n const contactId = contactAddress(message.key);\n const seconds = longNumber(message.messageTimestamp);\n const content = sentContent(message.message);\n if (!id || !contactId || seconds === null || !content) return null;\n return { type: \"sent_elsewhere\", accountId, contactId, externalId: id, sentAt: new Date(seconds * 1000), content };\n}\n\n/**\n * One live `messages.upsert` → events for the messages the account sent itself\n * (from another device, or the echo of one of this session's own sends: the\n * CALLER tells them apart by id). `accountId` is the linked account's digits.\n */\nexport function normalizeSentElsewhere(accountId: string, upsert: { messages: readonly BaileysMessage[]; type: string }): SentElsewhereEvent[] {\n if (upsert.type !== \"notify\") return [];\n return upsert.messages.map((message) => sentElsewhereEvent(accountId, message)).filter((event): event is SentElsewhereEvent => event !== null);\n}\n\n/** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */\nexport function receiptOf(status: unknown): ReceiptStatus | null {\n switch (status) {\n case 0:\n return \"FAILED\";\n case 2:\n return \"SENT\";\n case 3:\n return \"DELIVERED\";\n case 4:\n case 5:\n return \"READ\";\n default:\n return null;\n }\n}\n\n/** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */\nexport function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[] {\n const events: StatusEvent[] = [];\n for (const entry of updates) {\n if (!isObject(entry) || !isObject(entry.key) || !entry.key.fromMe || !isObject(entry.update)) continue;\n const id = text(entry.key.id);\n const status = receiptOf(entry.update.status);\n if (!id || !status) continue;\n events.push({\n type: \"status\",\n accountId,\n externalId: id,\n status,\n at,\n contactId: contactAddress(entry.key),\n error: status === \"FAILED\" ? \"ERROR\" : null,\n callbackData: null,\n });\n }\n return events;\n}\n","/**\n * The timer pair the session's deadlines run on: a history request's timeout and\n * the longest an echo-suspect event is held. Injectable so a test fires them by\n * hand; every timer set here is cleared once what it guards settles.\n */\nexport interface WhatsAppWebTimers {\n setTimeout(run: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n}\n\nexport const systemTimers: WhatsAppWebTimers = {\n setTimeout: (run, ms) => {\n const handle = setTimeout(run, ms);\n // A pending hold or history deadline never keeps a short-lived host process alive.\n (handle as { unref?: () => void }).unref?.();\n return handle;\n },\n clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n","import type { InboundContent } from \"../core/types\";\nimport type { BaileysHistorySet, BaileysMessage } from \"./baileys-port\";\nimport { addressJid, contactAddress, contentOf, longNumber } from \"./normalize\";\nimport { systemTimers, type WhatsAppWebTimers } from \"./timers\";\n\n/**\n * On-demand history: the messages of ONE chat, read from the phone and handed\n * back to the caller, never to the inbox or the engine.\n *\n * `fetchMessageHistory` asks the phone for messages before an anchor and\n * returns only a request id; the answer arrives later on `messaging-history.set`\n * (which can even come BEFORE the call resolves). This module holds the\n * pending requests, matches an answer to the chat it is for, and reduces each\n * message to what a model may read: text, or a placeholder kind for media.\n * Nothing here keeps a message after its request settles.\n */\n\n/** The message a history read starts before: the inbound message that began the turn. */\nexport interface HistoryAnchor {\n externalId: string;\n sentAt: Date;\n fromMe: boolean;\n}\n\n/**\n * One message of a chat's history. `kind` is `text`, `interactive`, `audio`, or the channel's own type for\n * anything else (`image`, `sticker`, `video`): text is carried only for `text` and `interactive`.\n */\nexport interface WhatsAppWebHistoryMessage {\n externalId: string;\n fromMe: boolean;\n sentAt: Date;\n text: string | null;\n kind: string;\n}\n\n/** `proto.HistorySync.HistorySyncType.ON_DEMAND`. */\nconst ON_DEMAND = 6;\n\nconst isOnDemand = (syncType: unknown): boolean => syncType === ON_DEMAND || syncType === \"ON_DEMAND\";\n\n/** What a content keeps: its text (or none) and the placeholder `kind`. Media keeps neither bytes nor keys. */\nfunction kept(content: InboundContent): { text: string | null; kind: string } {\n switch (content.kind) {\n case \"TEXT\":\n return { text: content.text, kind: \"text\" };\n case \"INTERACTIVE\":\n return { text: content.title || null, kind: \"interactive\" };\n case \"AUDIO\":\n return { text: null, kind: \"audio\" };\n default:\n return { text: null, kind: content.channelType.toLowerCase() };\n }\n}\n\n/** One raw message → its text-only form, or null for a protocol message, a malformed one or one with no id or time. */\nexport function historyMessage(message: BaileysMessage): WhatsAppWebHistoryMessage | null {\n const id = message?.key?.id;\n const seconds = longNumber(message?.messageTimestamp);\n const content = contentOf(message?.message);\n if (typeof id !== \"string\" || id === \"\" || seconds === null || !content) return null;\n return { externalId: id, fromMe: message.key.fromMe === true, sentAt: new Date(seconds * 1000), ...kept(content) };\n}\n\n/** Whether a message key belongs to the contact's chat, by either of the chat's addresses (a LID or its phone number). */\nconst inChat = (contactId: string, key: BaileysMessage[\"key\"]): boolean =>\n contactAddress(key) === contactId || [key.remoteJid, key.remoteJidAlt].includes(addressJid(contactId));\n\n/** The messages of one contact's chat out of a history batch: oldest first, each id once, the newest `count`. */\nexport function chatHistory(contactId: string, messages: readonly BaileysMessage[], count: number): WhatsAppWebHistoryMessage[] {\n const seen = new Set<string>();\n const found: WhatsAppWebHistoryMessage[] = [];\n for (const raw of messages) {\n if (!raw?.key || !inChat(contactId, raw.key)) continue;\n const message = historyMessage(raw);\n if (!message || seen.has(message.externalId)) continue;\n seen.add(message.externalId);\n found.push(message);\n }\n found.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());\n return count > 0 ? found.slice(-count) : [];\n}\n\ninterface Pending {\n contactId: string;\n count: number;\n requestId: string | null;\n settle(messages: WhatsAppWebHistoryMessage[]): void;\n}\n\n/** A request waiting for its answer. */\nexport interface HistoryWait {\n /** The messages, or `[]` on a timeout, an abandoned request or a closed socket. Never rejects. */\n result: Promise<WhatsAppWebHistoryMessage[]>;\n /** The id `fetchMessageHistory` returned: from then on an answer naming another id is not this one's. */\n setRequestId(id: string): void;\n /** Settle with nothing: the call that was to fetch it failed. */\n abandon(): void;\n}\n\nexport class HistoryRequests {\n /** Oldest first: an answer that names no request goes to the oldest one for its chat. */\n private readonly pending = new Set<Pending>();\n\n constructor(private readonly timers: WhatsAppWebTimers = systemTimers) {}\n\n /**\n * Ask, and wait for the answer without waiting on the call: `call` (which returns the request id) may never\n * settle, and the deadline still ends the wait. A rejected call abandons the request and goes to `onError`.\n */\n fetch(contactId: string, count: number, timeoutMs: number, call: () => Promise<string>, onError: (error: unknown) => void): Promise<WhatsAppWebHistoryMessage[]> {\n // Registered BEFORE the call: the phone's answer can beat the call's own return.\n const wait = this.wait(contactId, count, timeoutMs);\n Promise.resolve()\n .then(call)\n .then(wait.setRequestId, (error: unknown) => {\n wait.abandon();\n // A throwing host callback must not become an unhandled rejection of this detached chain.\n try {\n onError(error);\n } catch {\n /* the host's own error */\n }\n });\n return wait.result;\n }\n\n /** Register a request BEFORE the call is made: the answer may beat the call's own return. The deadline is cleared once it settles. */\n wait(contactId: string, count: number, timeoutMs: number): HistoryWait {\n let entry!: Pending;\n let timer: unknown = null;\n const result = new Promise<WhatsAppWebHistoryMessage[]>((resolve) => {\n entry = {\n contactId,\n count,\n requestId: null,\n settle: (messages) => {\n if (!this.pending.delete(entry)) return;\n this.timers.clearTimeout(timer);\n resolve(messages);\n },\n };\n });\n this.pending.add(entry);\n timer = this.timers.setTimeout(() => entry.settle([]), timeoutMs);\n return { result, setRequestId: (id) => void (entry.requestId = id), abandon: () => entry.settle([]) };\n }\n\n /**\n * A `messaging-history.set`. An answer naming a request id settles THAT request; one naming an id nobody holds\n * yet, or none, settles the oldest request for its chat whose id it cannot contradict. A late answer is dropped.\n */\n answer(set: BaileysHistorySet): void {\n if (!isOnDemand(set.syncType) || !Array.isArray(set.messages)) return;\n const named = typeof set.peerDataRequestSessionId === \"string\" ? set.peerDataRequestSessionId : null;\n const entries = [...this.pending];\n const exact = named ? entries.find((entry) => entry.requestId === named) : undefined;\n const candidates = exact ? [exact] : entries.filter((entry) => !named || entry.requestId === null);\n for (const entry of candidates) {\n const messages = chatHistory(entry.contactId, set.messages, entry.count);\n if (messages.length === 0) continue;\n entry.settle(messages);\n return;\n }\n }\n\n /** The socket closed: nothing more will come. */\n flush(): void {\n for (const entry of [...this.pending]) entry.settle([]);\n }\n}\n","import type { SentElsewhereEvent } from \"../core/types\";\nimport { systemTimers, type WhatsAppWebTimers } from \"./timers\";\n\n/**\n * Tells a message the account sent from ANOTHER device from the echo of a\n * send this session made.\n *\n * A linked device sees every message of the account on `messages.upsert`,\n * its own sends included, and the echo can arrive BEFORE `sendMessage`\n * resolves with the id. So: the ids of finished sends are remembered (bounded),\n * and a `fromMe` event that arrives while sends are in flight is HELD, stamped\n * with THOSE sends, and judged against the ids once they settle (a send that\n * starts later never holds it). The engine already recorded its own sends; an\n * echo reaching the host as \"the owner replied from the phone\" would pause the\n * agent on its own reply.\n *\n * Bounded: an event is held at most `maxHoldMs` (a send that never settles\n * cannot pin it), at most `maxHeld` events are held (the oldest is judged and\n * released first), and `reset` (the socket closed) releases everything. A\n * released event is judged against the ids known then. Released events reach\n * the host later than events that arrived after them.\n */\n\nexport interface OwnSendsOptions {\n timers?: WhatsAppWebTimers;\n /** The longest an event waits for its sends. Default 30 s. */\n maxHoldMs?: number;\n /** How many events may be held at once. Default 200. */\n maxHeld?: number;\n /** How many sent ids are remembered. Default 1000. */\n remembered?: number;\n}\n\ninterface Held {\n event: SentElsewhereEvent;\n /** The sends in flight when it arrived that have not settled yet. */\n waitingOn: Set<number>;\n timer: unknown;\n}\n\nexport class OwnSends {\n private readonly ids = new Set<string>();\n private readonly inFlight = new Set<number>();\n private sequence = 0;\n private held: Held[] = [];\n private readonly timers: WhatsAppWebTimers;\n private readonly maxHoldMs: number;\n private readonly maxHeld: number;\n private readonly remembered: number;\n\n /** `release` gets the held events that turned out to be from another device, when they are judged. */\n constructor(\n private readonly release: (events: SentElsewhereEvent[]) => void,\n options: OwnSendsOptions = {},\n ) {\n this.timers = options.timers ?? systemTimers;\n this.maxHoldMs = options.maxHoldMs ?? 30_000;\n this.maxHeld = options.maxHeld ?? 200;\n this.remembered = options.remembered ?? 1000;\n }\n\n /** Run one send. Its id is remembered whether the caller or the echo gets there first. */\n async track<T extends { externalId: string }>(run: () => Promise<T>): Promise<T> {\n this.sequence += 1;\n const send = this.sequence;\n this.inFlight.add(send);\n let id: string | null = null;\n try {\n const result = await run();\n id = result.externalId;\n return result;\n } finally {\n this.inFlight.delete(send);\n if (id) this.remember(id);\n for (const entry of this.held) entry.waitingOn.delete(send);\n this.releaseWhere((entry) => entry.waitingOn.size === 0);\n }\n }\n\n /** The events to hand on NOW: not our own, and none while a send is in flight (those are held). */\n accept(events: readonly SentElsewhereEvent[]): SentElsewhereEvent[] {\n if (this.inFlight.size === 0) return this.judge(events);\n for (const event of events) this.hold(event);\n const excess = new Set(this.held.slice(0, Math.max(0, this.held.length - this.maxHeld)));\n this.releaseWhere((entry) => excess.has(entry));\n return [];\n }\n\n /** The socket closed: release everything held, and hold nothing for the sends that were in flight. */\n reset(): void {\n this.inFlight.clear();\n this.releaseWhere(() => true);\n }\n\n private hold(event: SentElsewhereEvent): void {\n const entry: Held = { event, waitingOn: new Set(this.inFlight), timer: null };\n entry.timer = this.timers.setTimeout(() => this.releaseWhere((held) => held === entry), this.maxHoldMs);\n this.held.push(entry);\n }\n\n /** Release the held entries `done` picks, in the order they arrived, judged against the ids known now. */\n private releaseWhere(done: (entry: Held) => boolean): void {\n const out: Held[] = [];\n const kept: Held[] = [];\n for (const entry of this.held) (done(entry) ? out : kept).push(entry);\n if (out.length === 0) return;\n this.held = kept;\n for (const entry of out) this.timers.clearTimeout(entry.timer);\n const events = this.judge(out.map((entry) => entry.event));\n if (events.length > 0) this.release(events);\n }\n\n private judge(events: readonly SentElsewhereEvent[]): SentElsewhereEvent[] {\n return events.filter((event) => !this.ids.has(event.externalId));\n }\n\n private remember(id: string): void {\n this.ids.add(id);\n for (const oldest of this.ids) {\n if (this.ids.size <= this.remembered) break;\n this.ids.delete(oldest);\n }\n }\n}\n","import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, type ChannelMedia } from \"../core/channel\";\nimport type { BaileysLogger, BaileysMessage, BaileysModule } from \"./baileys-port\";\nimport { longNumber, unwrapMessage } from \"./normalize\";\n\n/**\n * Inbound audio, for `fetchMedia`. A Baileys media message is downloaded from\n * the message itself (its URL and media key), so the session keeps the most\n * recent audio messages IN MEMORY, by message id, and nothing else: the media\n * key never reaches the inbox or the host's database. After a restart an\n * older audio is `NOT_FOUND`.\n */\nexport class AudioCache<Msg extends BaileysMessage> {\n private readonly messages = new Map<string, Msg>();\n\n constructor(private readonly size: number) {}\n\n /** Keep `message` if it is an audio. The oldest is dropped past the size. */\n remember(message: Msg): void {\n const id = message.key?.id;\n if (!id || !audioOf(message)) return;\n this.messages.set(id, message);\n while (this.messages.size > this.size) this.messages.delete(this.messages.keys().next().value as string);\n }\n\n get(id: string): Msg | undefined {\n return this.messages.get(id);\n }\n}\n\n/** The audio content of a message, unwrapped, or null. */\nexport function audioOf(message: BaileysMessage): Record<string, unknown> | null {\n const audio = unwrapMessage(message.message).audioMessage;\n return typeof audio === \"object\" && audio !== null ? (audio as Record<string, unknown>) : null;\n}\n\nasync function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new ChannelMediaFailure(\"TIMEOUT\", `media download passed its ${ms} ms deadline`)), ms);\n });\n try {\n return await Promise.race([work, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction refuseOverCap(size: number | null, maxBytes: number, what: \"declares\" | \"is\"): void {\n if (size !== null && size > maxBytes) throw new ChannelMediaFailure(\"TOO_LARGE\", `the media ${what} ${size} bytes, over ${maxBytes}`);\n}\n\nexport interface DownloadAudioInput<Msg extends BaileysMessage> {\n baileys: Pick<BaileysModule<unknown, Msg>, \"downloadMediaMessage\">;\n message: Msg | undefined;\n maxBytes: number;\n timeoutMs?: number | undefined;\n logger?: BaileysLogger | undefined;\n reupload?: ((message: Msg) => Promise<Msg>) | undefined;\n}\n\n/** Download one cached audio into memory. Throws `ChannelMediaFailure`; never stores anything. */\nexport async function downloadAudio<Msg extends BaileysMessage>(input: DownloadAudioInput<Msg>): Promise<ChannelMedia> {\n const audio = input.message ? audioOf(input.message) : null;\n if (!input.message || !audio) throw new ChannelMediaFailure(\"NOT_FOUND\", \"no recent audio with this id in this session\");\n refuseOverCap(longNumber(audio.fileLength as number | null), input.maxBytes, \"declares\");\n const ctx = {\n ...(input.logger ? { logger: input.logger } : {}),\n ...(input.reupload ? { reuploadRequest: input.reupload } : {}),\n };\n const bytes = await withDeadline(input.baileys.downloadMediaMessage(input.message, \"buffer\", {}, ctx), input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS).catch(\n (error: unknown) => {\n throw error instanceof ChannelMediaFailure ? error : new ChannelMediaFailure(\"DOWNLOAD_FAILED\", \"the media could not be downloaded\");\n },\n );\n refuseOverCap(bytes.length, input.maxBytes, \"is\");\n const mimeType = typeof audio.mimetype === \"string\" && audio.mimetype ? audio.mimetype : \"application/octet-stream\";\n return { bytes: new Uint8Array(bytes), mimeType, size: bytes.length };\n}\n","import { ChannelSendFailure, type ChannelMedia } from \"../core/channel\";\nimport type { NormalizedEvent, OutboundContent } from \"../core/types\";\nimport { clearAuthState, loadAuthState, type AuthStateStore } from \"./auth-state\";\nimport {\n DISCONNECT,\n disconnectCode,\n type BaileysAuthState,\n type BaileysConnectionUpdate,\n type BaileysLogger,\n type BaileysMessage,\n type BaileysMessageKey,\n type BaileysModule,\n type BaileysSocket,\n} from \"./baileys-port\";\nimport { applyChoices, ChoiceMemory } from \"./choices\";\nimport { encodeEnvelope } from \"./envelope\";\nimport { HistoryRequests, type HistoryAnchor, type WhatsAppWebHistoryMessage } from \"./history\";\nimport { OwnSends } from \"./own-sends\";\nimport { AudioCache, downloadAudio } from \"./media\";\nimport { addressJid, jidUser, normalizeSentElsewhere, normalizeUpdates, normalizeUpsert, replyAddress } from \"./normalize\";\nimport type { WhatsAppWebTimers } from \"./timers\";\n\n/**\n * ONE linked WhatsApp account, over Baileys: the socket, its pairing, its\n * reconnects, and the bridge to the engine.\n *\n * Inbound, the session normalizes every live socket event and hands the host\n * a raw body (`deliver`) that the host stores through `engine.receive(channel,\n * rawBody)`, exactly as the webhook edge does for the Cloud API: the inbox,\n * the processing job and the reconciliation sweep are the same. Outbound,\n * the adapter sends through the session's socket.\n */\n\n/** Where the session stands. `qr` and `pairing-code` wait for the person to link the device on their phone. */\nexport type WhatsAppWebStatus =\n | { state: \"idle\" }\n | { state: \"connecting\" }\n /** Show `qr` as a QR code; WhatsApp › Linked devices › Link a device. It rotates: a new status replaces it. */\n | { state: \"qr\"; qr: string }\n /** Type `code` on the phone: WhatsApp › Linked devices › Link with phone number. */\n | { state: \"pairing-code\"; code: string }\n | { state: \"open\"; accountId: string }\n | { state: \"reconnecting\"; attempt: number; code: number | null }\n /** The phone unlinked this device (or WhatsApp logged it out). The keys were cleared: the next start pairs again. */\n | { state: \"logged-out\"; code: number | null }\n /** Stopped for good: another client took the session (440), the account is refused (403), or reconnects ran out. */\n | { state: \"failed\"; code: number | null; reason: \"replaced\" | \"forbidden\" | \"reconnects-exhausted\" | \"start-failed\" }\n | { state: \"stopped\" };\n\nexport interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {\n /** The Baileys module the host installed: `import * as baileys from \"baileys\"`. */\n baileys: BaileysModule<Auth, Msg>;\n /** Where the linked device's keys live. The host's: see {@link AuthStateStore}. */\n authStore: AuthStateStore;\n /**\n * Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.\n * Called one at a time, in socket order, except that a phone-sent message held\n * while a send was in flight comes when it is judged (see the README). A socket\n * does not redeliver, so a throw is reported through `onError` and that body is lost.\n */\n deliver(rawBody: string): Promise<unknown>;\n /** Every status change. Show the QR or the pairing code from here. */\n onStatus?(status: WhatsAppWebStatus): void;\n /** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */\n onError?(error: unknown, where: \"deliver\" | \"save-creds\" | \"pairing-code\" | \"presence\" | \"mark-read\" | \"history\"): void;\n /** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */\n pairingPhoneNumber?: string;\n /** Opt-out words, as the Cloud adapter's `optOutKeywords`. */\n optOutKeywords?: readonly string[];\n /** A pino-compatible logger for Baileys. Default: Baileys' own. */\n logger?: BaileysLogger;\n /** How the linked device is named on the phone: `[client, browser, version]`. */\n browser?: [string, string, string];\n /** Reconnects after an unexpected close. Default 5 attempts, from 2 s, doubling. */\n reconnect?: { maxAttempts?: number; delayMs?: number };\n /** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */\n mediaCacheSize?: number;\n /** How many contacts' last offered choices are kept to read a typed \"1\" as a tap. Default 500. */\n choiceMemorySize?: number;\n /** How long offered choices stay answerable by number or title. Default 2 hours. */\n choiceTtlMs?: number;\n /** For tests. */\n now?(): Date;\n sleep?(ms: number): Promise<void>;\n /** The deadlines (a history request's, an echo-suspect's 30 s hold). Default: the global timers. For tests. */\n timers?: WhatsAppWebTimers;\n}\n\nexport interface WhatsAppWebSession {\n /** Open the socket: resume the stored device, or pair a new one. Idempotent while running. */\n start(): Promise<void>;\n /** Close the socket and keep the keys: `start` resumes without pairing. */\n stop(): Promise<void>;\n /** Unlink this device on WhatsApp and clear its keys. */\n logout(): Promise<void>;\n status(): WhatsAppWebStatus;\n /** The linked account's digits once open (`5511987654321`), else null. */\n accountId(): string | null;\n /** Send one message. Throws `ChannelSendFailure`. */\n send(to: string, content: OutboundContent): Promise<{ externalId: string }>;\n /**\n * Show \"digitando…\" (`composing`) or its end (`paused`) to one contact. Fire and forget: it never\n * rejects. A failure goes to `onError` (`presence`); a session that is not open reports `NOT_CONNECTED` there.\n */\n sendPresence(contactId: string, state: \"composing\" | \"paused\"): Promise<void>;\n /** Mark messages of one contact read, by their ids. Same failure rules as `sendPresence` (`mark-read`). */\n markRead(contactId: string, externalIds: readonly string[]): Promise<void>;\n /**\n * Read up to `count` messages of one chat that came BEFORE `anchor`, from the phone, on demand. Text only, both\n * sides, media as a placeholder `kind`, oldest first. Nothing is stored here or delivered to the engine. Resolves\n * `[]` when the session is not open, the phone does not answer within `timeoutMs`, or the call fails (`history`);\n * a late answer is dropped.\n */\n fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]>;\n /** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */\n downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia>;\n}\n\n/**\n * The text a personal account sends for an outbound message. Reply buttons\n * and lists are a Business API feature: here their choices become numbered\n * lines under the text, and the contact's answer arrives as TEXT.\n */\nexport function renderOutboundText(content: OutboundContent): string {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"BUTTONS\") return [content.text, \"\", ...content.buttons.map((button, i) => `${i + 1}. ${button.title}`)].join(\"\\n\");\n let n = 0;\n const sections = content.sections.map((section) => [\n \"\",\n ...(section.title ? [`*${section.title}*`] : []),\n ...section.rows.map((row) => `${++n}. ${row.title}${row.description ? ` — ${row.description}` : \"\"}`),\n ]);\n return [content.text, ...sections.flat()].join(\"\\n\");\n}\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/** The close codes after which the session stops for good, and how it reports each. */\nconst TERMINAL: Readonly<Record<number, Extract<WhatsAppWebStatus, { state: \"failed\" }>[\"reason\"]>> = {\n [DISCONNECT.connectionReplaced]: \"replaced\",\n [DISCONNECT.forbidden]: \"forbidden\",\n};\n\nclass BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSession {\n private socket: BaileysSocket<Msg> | null = null;\n private current: WhatsAppWebStatus = { state: \"idle\" };\n private account: string | null = null;\n private attempts = 0;\n private stopping = false;\n private pairingRequested = false;\n private deliveries: Promise<void> = Promise.resolve();\n private readonly audio: AudioCache<Msg>;\n private readonly choices: ChoiceMemory;\n private readonly history: HistoryRequests;\n private readonly ownSends: OwnSends;\n\n constructor(private readonly config: WhatsAppWebSessionConfig<Auth, Msg>) {\n this.history = new HistoryRequests(config.timers);\n this.ownSends = new OwnSends((events) => this.deliver(applyChoices(this.choices, events)), config.timers ? { timers: config.timers } : {});\n this.audio = new AudioCache(config.mediaCacheSize ?? 200);\n this.choices = new ChoiceMemory({\n ...(config.choiceMemorySize !== undefined ? { maxContacts: config.choiceMemorySize } : {}),\n ...(config.choiceTtlMs !== undefined ? { ttlMs: config.choiceTtlMs } : {}),\n now: () => (config.now ?? (() => new Date()))(),\n });\n }\n\n status = (): WhatsAppWebStatus => this.current;\n accountId = (): string | null => this.account;\n\n async start(): Promise<void> {\n if (this.socket) return;\n this.stopping = false;\n this.attempts = 0;\n this.pairingRequested = false;\n try {\n await this.open();\n } catch (error) {\n this.socket = null;\n this.setStatus({ state: \"failed\", code: null, reason: \"start-failed\" });\n throw error;\n }\n }\n\n async stop(): Promise<void> {\n const sock = this.detach();\n if (sock) await sock.end(undefined);\n this.setStatus({ state: \"stopped\" });\n }\n\n async logout(): Promise<void> {\n const sock = this.detach();\n if (sock) await sock.logout();\n await clearAuthState(this.config.authStore);\n this.setStatus({ state: \"logged-out\", code: null });\n }\n\n async send(to: string, content: OutboundContent): Promise<{ externalId: string }> {\n const sock = this.socket;\n if (!sock || this.current.state !== \"open\") throw new ChannelSendFailure(\"NOT_CONNECTED\", \"the WhatsApp Web session is not open\");\n const { externalId, key } = await this.ownSends.track(() => this.dispatch(sock, to, content));\n const contact = replyAddress(to, key);\n if (contact) this.choices.offer(contact, content);\n return { externalId };\n }\n\n private async dispatch(sock: BaileysSocket<Msg>, to: string, content: OutboundContent): Promise<{ externalId: string; key: BaileysMessageKey }> {\n const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content) }).catch((error: unknown) => {\n const code = disconnectCode({ error: error as Error });\n throw new ChannelSendFailure(code === null ? \"SEND_FAILED\" : String(code), \"the WhatsApp Web socket refused the send\");\n });\n const externalId = sent?.key?.id;\n if (!externalId) throw new ChannelSendFailure(\"NO_MESSAGE_ID\", \"the WhatsApp Web socket returned no message id\");\n return { externalId, key: sent?.key ?? {} };\n }\n\n sendPresence(contactId: string, state: \"composing\" | \"paused\"): Promise<void> {\n return this.fireAndForget(\"presence\", (sock) => sock.sendPresenceUpdate(state, addressJid(contactId)));\n }\n\n markRead(contactId: string, externalIds: readonly string[]): Promise<void> {\n if (externalIds.length === 0) return Promise.resolve();\n const remoteJid = addressJid(contactId);\n return this.fireAndForget(\"mark-read\", (sock) => sock.readMessages(externalIds.map((id) => ({ remoteJid, id, fromMe: false }))));\n }\n\n /** One call on the open socket whose failure is reported, never thrown. */\n private async fireAndForget(where: \"presence\" | \"mark-read\", call: (sock: BaileysSocket<Msg>) => Promise<void>): Promise<void> {\n const sock = this.socket;\n try {\n if (!sock || this.current.state !== \"open\") throw new ChannelSendFailure(\"NOT_CONNECTED\", \"the WhatsApp Web session is not open\");\n await call(sock);\n } catch (error) {\n this.config.onError?.(error, where);\n }\n }\n\n async fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]> {\n const sock = this.socket;\n if (!sock || this.current.state !== \"open\" || count <= 0) return [];\n const key = { remoteJid: addressJid(contactId), id: anchor.externalId, fromMe: anchor.fromMe };\n const call = () => sock.fetchMessageHistory(count, key, Math.floor(anchor.sentAt.getTime() / 1000));\n return this.history.fetch(contactId, count, timeoutMs, call, (error) => this.config.onError?.(error, \"history\"));\n }\n\n downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia> {\n const sock = this.socket;\n return downloadAudio({\n baileys: this.config.baileys,\n message: this.audio.get(mediaId),\n maxBytes: options.maxBytes,\n timeoutMs: options.timeoutMs,\n logger: this.config.logger,\n reupload: sock?.updateMediaMessage ? (message: Msg) => sock.updateMediaMessage!(message) : undefined,\n });\n }\n\n // ── The socket ──────────────────────────────────────────────────────────\n\n private detach(): BaileysSocket<Msg> | null {\n this.stopping = true;\n const sock = this.socket;\n this.socket = null;\n this.account = null;\n this.history.flush();\n this.ownSends.reset();\n return sock;\n }\n\n private setStatus(status: WhatsAppWebStatus): void {\n this.current = status;\n this.config.onStatus?.(status);\n }\n\n private async open(): Promise<void> {\n this.setStatus({ state: \"connecting\" });\n const { state, saveCreds } = await loadAuthState(this.config.baileys, this.config.authStore);\n const sock = this.config.baileys.makeWASocket({\n // The ONE boundary cast: the store holds Baileys' own values, which its key store types per category.\n auth: state as Auth,\n markOnlineOnConnect: false,\n syncFullHistory: false,\n ...(this.config.logger ? { logger: this.config.logger } : {}),\n ...(this.config.browser ? { browser: this.config.browser } : {}),\n });\n this.socket = sock;\n sock.ev.on(\"creds.update\", () => {\n saveCreds().catch((error: unknown) => this.config.onError?.(error, \"save-creds\"));\n });\n sock.ev.on(\"connection.update\", (update) => {\n if (sock === this.socket) void this.onConnection(sock, update);\n });\n sock.ev.on(\"messages.upsert\", (upsert) => {\n const account = this.linked(sock);\n if (!account) return;\n if (upsert.type === \"notify\") upsert.messages.forEach((message) => this.audio.remember(message));\n const options = this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {};\n // One message at a time: a phone message clears an offer only for the replies that come after it.\n const events = upsert.messages.flatMap((message) => {\n const one = { type: upsert.type, messages: [message] };\n return [...normalizeUpsert(account, one, options), ...this.ownSends.accept(normalizeSentElsewhere(account, one))];\n });\n this.deliver(applyChoices(this.choices, events));\n });\n sock.ev.on(\"messaging-history.set\", (set) => {\n if (sock === this.socket) this.history.answer(set);\n });\n sock.ev.on(\"messages.update\", (updates) => {\n const account = this.linked(sock);\n if (account) this.deliver(normalizeUpdates(account, updates, (this.config.now ?? (() => new Date()))()));\n });\n }\n\n /** The account a CURRENT socket is linked to: from the open event, or its own user while still opening. */\n private linked(sock: BaileysSocket<Msg>): string | null {\n if (sock !== this.socket) return null;\n return this.account ?? (sock.user?.id ? jidUser(sock.user.id) : null);\n }\n\n /** Hand one body to the host, after every earlier one: a socket's order is kept. */\n private deliver(events: NormalizedEvent[]): void {\n if (events.length === 0) return;\n const body = encodeEnvelope(events);\n this.deliveries = this.deliveries.then(() =>\n this.config.deliver(body).then(\n () => undefined,\n (error: unknown) => this.config.onError?.(error, \"deliver\"),\n ),\n );\n }\n\n private async onConnection(sock: BaileysSocket<Msg>, update: BaileysConnectionUpdate): Promise<void> {\n if (update.qr) await this.onQr(sock, update.qr);\n if (update.connection === \"open\") {\n this.attempts = 0;\n this.account = sock.user?.id ? jidUser(sock.user.id) : null;\n this.setStatus(this.account ? { state: \"open\", accountId: this.account } : { state: \"connecting\" });\n } else if (update.connection === \"close\") {\n await this.onClose(disconnectCode(update.lastDisconnect));\n }\n }\n\n private async onQr(sock: BaileysSocket<Msg>, qr: string): Promise<void> {\n const phone = this.config.pairingPhoneNumber;\n if (!phone) return this.setStatus({ state: \"qr\", qr });\n if (this.pairingRequested) return;\n this.pairingRequested = true;\n try {\n this.setStatus({ state: \"pairing-code\", code: await sock.requestPairingCode(phone.replace(/\\D/g, \"\")) });\n } catch (error) {\n this.pairingRequested = false;\n this.config.onError?.(error, \"pairing-code\");\n }\n }\n\n private async onClose(code: number | null): Promise<void> {\n this.socket = null;\n this.account = null;\n this.history.flush();\n this.ownSends.reset();\n if (this.stopping) return this.setStatus({ state: \"stopped\" });\n if (code === DISCONNECT.loggedOut) {\n await clearAuthState(this.config.authStore);\n return this.setStatus({ state: \"logged-out\", code });\n }\n const terminal = code === null ? undefined : TERMINAL[code];\n if (terminal) return this.setStatus({ state: \"failed\", code, reason: terminal });\n if (code !== DISCONNECT.restartRequired && !(await this.backOff(code))) return;\n await this.open();\n }\n\n /** Wait before a reconnect; false when the attempts ran out or the session was stopped meanwhile. */\n private async backOff(code: number | null): Promise<boolean> {\n const maxAttempts = this.config.reconnect?.maxAttempts ?? 5;\n this.attempts += 1;\n if (this.attempts > maxAttempts) {\n this.setStatus({ state: \"failed\", code, reason: \"reconnects-exhausted\" });\n return false;\n }\n this.setStatus({ state: \"reconnecting\", attempt: this.attempts, code });\n await (this.config.sleep ?? defaultSleep)((this.config.reconnect?.delayMs ?? 2_000) * 2 ** (this.attempts - 1));\n if (!this.stopping) return true;\n this.setStatus({ state: \"stopped\" });\n return false;\n }\n}\n\n/** One linked WhatsApp account over Baileys. Nothing connects until `start()`. */\nexport function createWhatsAppWebSession<Auth, Msg extends BaileysMessage>(config: Wh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,aAAa;AAC/B,WAAK,UAAU,EAAE,OAAO,UAAU,MAAM,QAAQ,uBAAuB,CAAC;AACxE,aAAO;AAAA,IACT;AACA,SAAK,UAAU,EAAE,OAAO,gBAAgB,SAAS,KAAK,UAAU,KAAK,CAAC;AACtE,WAAO,KAAK,OAAO,SAAS,eAAe,KAAK,OAAO,WAAW,WAAW,OAAS,MAAM,KAAK,WAAW,EAAE;AAC9G,QAAI,CAAC,KAAK,SAAU,QAAO;AAC3B,SAAK,UAAU,EAAE,OAAO,UAAU,CAAC;AACnC,WAAO;AAAA,EACT;AACF;AAGO,SAAS,yBAA2D,QAAiE;AAC1I,SAAO,IAAI,eAAe,MAAM;AAClC;AAFgB;","names":["content","text","content","text","event","isObject","content","event","sentElsewhereEvent","content","event","kept","content"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/messaging",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "A channel-agnostic conversational messaging connector: channel connections with sealed credentials, a durable inbox of raw webhook deliveries, conversations with an owner state and a structured summary, messages with delivery statuses, an opt-out, a per-channel send policy and a text-retention sweep, behind a channel adapter port. WhatsApp Cloud is the first adapter (./whatsapp), with its signature check, payload parser, Graph sender and Embedded Signup helpers. Framework-neutral webhook routes (./server), dep-free job blueprints and the package-owned Prisma partial + migrations.",
|
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
"types": "./dist/whatsapp/index.d.ts",
|
|
14
14
|
"default": "./dist/whatsapp/index.js"
|
|
15
15
|
},
|
|
16
|
+
"./whatsapp-web": {
|
|
17
|
+
"types": "./dist/whatsapp-web/index.d.ts",
|
|
18
|
+
"default": "./dist/whatsapp-web/index.js"
|
|
19
|
+
},
|
|
16
20
|
"./inbound-guard": {
|
|
17
21
|
"types": "./dist/inbound-guard/index.d.ts",
|
|
18
22
|
"default": "./dist/inbound-guard/index.js"
|
package/src/core/inbound.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { EngineContext } from "./context";
|
|
2
2
|
import { errorText } from "./errors";
|
|
3
|
+
import { handleSentElsewhere } from "./sent-elsewhere";
|
|
3
4
|
import type { StoredConnection } from "./store";
|
|
4
5
|
import type {
|
|
5
6
|
ConversationState,
|
|
@@ -21,10 +22,13 @@ import type {
|
|
|
21
22
|
*/
|
|
22
23
|
|
|
23
24
|
export type EventOutcome =
|
|
24
|
-
|
|
25
|
+
/** `no-conversation`: a message the owner sent from their phone to a contact the store has no conversation with here. */
|
|
26
|
+
| { kind: "dropped"; reason: "unknown-account" | "not-connected" | "no-conversation" }
|
|
25
27
|
| { kind: "duplicate" }
|
|
26
28
|
| { kind: "message"; conversationId: string; messageId: string }
|
|
27
29
|
| { kind: "opted-out"; conversationId: string }
|
|
30
|
+
/** A message the owner sent from another device, stored as the store's own. */
|
|
31
|
+
| { kind: "staff-message"; conversationId: string; messageId: string }
|
|
28
32
|
| { kind: "receipt"; applied: boolean };
|
|
29
33
|
|
|
30
34
|
export async function handleEvent(ctx: EngineContext, channel: string, event: NormalizedEvent): Promise<EventOutcome> {
|
|
@@ -34,6 +38,7 @@ export async function handleEvent(ctx: EngineContext, channel: string, event: No
|
|
|
34
38
|
|
|
35
39
|
if (event.type === "message") return handleMessage(ctx, connection, event);
|
|
36
40
|
if (event.type === "opt_out") return handleOptOut(ctx, connection, event);
|
|
41
|
+
if (event.type === "sent_elsewhere") return handleSentElsewhere(ctx, connection, event);
|
|
37
42
|
const applied = await ctx.config.store.applyReceipt({
|
|
38
43
|
tenantId: connection.tenantId,
|
|
39
44
|
channel,
|
package/src/core/ports.ts
CHANGED
|
@@ -50,6 +50,12 @@ export interface InboundMessageNotice {
|
|
|
50
50
|
message: MessageView;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/** What `onStaffReply` is told: the conversation, and the stored message the owner sent from another device. */
|
|
54
|
+
export interface StaffReplyNotice {
|
|
55
|
+
conversation: ConversationView;
|
|
56
|
+
message: MessageView;
|
|
57
|
+
}
|
|
58
|
+
|
|
53
59
|
/** What a re-opened conversation may become. */
|
|
54
60
|
export type ReopenState = Exclude<ConversationState, "OPTED_OUT">;
|
|
55
61
|
|
|
@@ -63,6 +69,16 @@ export interface MessagingHooks {
|
|
|
63
69
|
* retried, because the message is already stored. Default: nothing.
|
|
64
70
|
*/
|
|
65
71
|
onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;
|
|
72
|
+
/**
|
|
73
|
+
* The account's owner answered a contact from ANOTHER device (their phone),
|
|
74
|
+
* on a channel that shows it (WhatsApp Web's `sent_elsewhere` event). The
|
|
75
|
+
* message is stored first, as an outbound `STAFF` message, and this runs once
|
|
76
|
+
* per stored message, never for a redelivery and never for the echo of a send
|
|
77
|
+
* the engine made. The engine changes no state itself: a host that wants its
|
|
78
|
+
* agent to step aside does it here (`setState(..., "HUMAN")`, a timer).
|
|
79
|
+
* A throw is logged, never retried. Default: nothing.
|
|
80
|
+
*/
|
|
81
|
+
onStaffReply?(notice: StaffReplyNotice): Promise<void> | void;
|
|
66
82
|
/**
|
|
67
83
|
* The state a CLOSED or OPTED_OUT conversation re-opens into when its
|
|
68
84
|
* contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { EngineContext } from "./context";
|
|
2
|
+
import { errorText } from "./errors";
|
|
3
|
+
import type { EventOutcome } from "./inbound";
|
|
4
|
+
import type { StoredConnection } from "./store";
|
|
5
|
+
import type { ConversationView, MessageView, SentElsewhereEvent } from "./types";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A message the account's owner sent from another device (their phone), applied.
|
|
9
|
+
*
|
|
10
|
+
* It is stored as an OUTBOUND message of the contact's conversation authored
|
|
11
|
+
* by `STAFF` (no `staffUserId`: the channel does not say who held the phone),
|
|
12
|
+
* `SENT` at the time the channel gave it, the same row shape `sendMessage`
|
|
13
|
+
* writes. Then `hooks.onStaffReply` tells the host, once per stored message,
|
|
14
|
+
* so it can pause its agent. It changes no conversation state itself.
|
|
15
|
+
*
|
|
16
|
+
* Only into a conversation the contact ALREADY has on this connection: the
|
|
17
|
+
* store's phone also carries the owner's family and friends, and a message to
|
|
18
|
+
* someone the store never talked to here is dropped (`no-conversation`), never
|
|
19
|
+
* stored and never opens a conversation.
|
|
20
|
+
*
|
|
21
|
+
* Idempotent on the channel's message id: a redelivery, or an id the engine
|
|
22
|
+
* already recorded for its own send, is a `duplicate`.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const later = (a: Date | null, b: Date): Date => (a && a > b ? a : b);
|
|
26
|
+
|
|
27
|
+
/** How many times a conversation write is re-decided after losing a compare-and-set. */
|
|
28
|
+
const MAX_WRITE_ATTEMPTS = 6;
|
|
29
|
+
|
|
30
|
+
export async function handleSentElsewhere(ctx: EngineContext, connection: StoredConnection, event: SentElsewhereEvent): Promise<EventOutcome> {
|
|
31
|
+
const { store } = ctx.config;
|
|
32
|
+
if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
|
|
33
|
+
const body = event.content.kind === "TEXT" ? event.content.text : null;
|
|
34
|
+
const conversation = await touchConversation(ctx, connection, event, body !== null);
|
|
35
|
+
if (!conversation) return { kind: "dropped", reason: "no-conversation" };
|
|
36
|
+
const inserted = await store.insertMessage({
|
|
37
|
+
conversationId: conversation.id,
|
|
38
|
+
tenantId: connection.tenantId,
|
|
39
|
+
channel: connection.channel,
|
|
40
|
+
direction: "OUTBOUND",
|
|
41
|
+
kind: body === null ? "OTHER" : "TEXT",
|
|
42
|
+
body,
|
|
43
|
+
options: null,
|
|
44
|
+
attachmentRef: null,
|
|
45
|
+
externalId: event.externalId,
|
|
46
|
+
deliveryStatus: "SENT",
|
|
47
|
+
authorKind: "STAFF",
|
|
48
|
+
staffUserId: null,
|
|
49
|
+
createdAt: event.sentAt,
|
|
50
|
+
});
|
|
51
|
+
if (!inserted.created) return { kind: "duplicate" };
|
|
52
|
+
await notifyStaffReply(ctx, conversation, inserted.message);
|
|
53
|
+
return { kind: "staff-message", conversationId: conversation.id, messageId: inserted.message.id };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The contact's conversation on this connection, brought up to this message's time; null when there is none. */
|
|
57
|
+
async function touchConversation(
|
|
58
|
+
ctx: EngineContext,
|
|
59
|
+
connection: StoredConnection,
|
|
60
|
+
event: SentElsewhereEvent,
|
|
61
|
+
carriesText: boolean,
|
|
62
|
+
): Promise<ConversationView | null> {
|
|
63
|
+
const { store } = ctx.config;
|
|
64
|
+
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
|
|
65
|
+
const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
|
|
66
|
+
if (!existing || existing.connectionId !== connection.id) return null;
|
|
67
|
+
const updated = await store.updateConversation(
|
|
68
|
+
connection.tenantId,
|
|
69
|
+
existing.id,
|
|
70
|
+
{ lastMessageAt: later(existing.lastMessageAt, event.sentAt), ...(carriesText ? { hasText: true } : {}) },
|
|
71
|
+
{ state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },
|
|
72
|
+
);
|
|
73
|
+
if (updated) return updated;
|
|
74
|
+
}
|
|
75
|
+
throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function notifyStaffReply(ctx: EngineContext, conversation: ConversationView, message: MessageView): Promise<void> {
|
|
79
|
+
const hook = ctx.config.hooks?.onStaffReply;
|
|
80
|
+
if (!hook) return;
|
|
81
|
+
try {
|
|
82
|
+
await hook({ conversation, message });
|
|
83
|
+
} catch (error) {
|
|
84
|
+
// Stored; a retry would be a no-op. The host's failure is the host's to log and recover from.
|
|
85
|
+
ctx.config.logger.error(`messaging.inbound: onStaffReply failed for ${conversation.id}: ${errorText(error)}`, { error });
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/core/types.ts
CHANGED
|
@@ -102,7 +102,28 @@ export interface OptOutEvent {
|
|
|
102
102
|
at: Date;
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
-
|
|
105
|
+
/**
|
|
106
|
+
* A message the account itself sent from ANOTHER device (the owner's phone,
|
|
107
|
+
* typed in the app), seen on a linked-device channel. The engine stores it as
|
|
108
|
+
* an OUTBOUND message of the conversation authored by `STAFF` and tells the
|
|
109
|
+
* host (`hooks.onStaffReply`), so the host can step its agent aside.
|
|
110
|
+
*
|
|
111
|
+
* Never the echo of a send the engine made: the channel adapter dedupes those
|
|
112
|
+
* before they become events. `content` is the text, or `OTHER` for media.
|
|
113
|
+
*/
|
|
114
|
+
export interface SentElsewhereEvent {
|
|
115
|
+
type: "sent_elsewhere";
|
|
116
|
+
/** The channel account that sent it. */
|
|
117
|
+
accountId: string;
|
|
118
|
+
/** The recipient's address on the channel. */
|
|
119
|
+
contactId: string;
|
|
120
|
+
/** The channel's id for the message. */
|
|
121
|
+
externalId: string;
|
|
122
|
+
sentAt: Date;
|
|
123
|
+
content: InboundContent;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent | SentElsewhereEvent;
|
|
106
127
|
|
|
107
128
|
/** A message the tenant sends, normalized across channels. */
|
|
108
129
|
export type OutboundContent =
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ChannelMediaFailure, ChannelSendFailure, OPEN_SEND_POLICY, type ChannelAdapter, type SendPolicy } from "../core/channel";
|
|
2
|
+
import { WHATSAPP_CHANNEL } from "../whatsapp";
|
|
3
|
+
import { parseEnvelope } from "./envelope";
|
|
4
|
+
import type { WhatsAppWebSession } from "./session";
|
|
5
|
+
|
|
6
|
+
export interface WhatsAppWebAdapterConfig {
|
|
7
|
+
/**
|
|
8
|
+
* The session that serves an account: one session, or a lookup by the
|
|
9
|
+
* connection's account id (the linked number's digits). A session serves
|
|
10
|
+
* only the account it is linked to.
|
|
11
|
+
*/
|
|
12
|
+
sessions: WhatsAppWebSession | ((accountId: string) => WhatsAppWebSession | undefined);
|
|
13
|
+
/**
|
|
14
|
+
* The channel key. Default `whatsapp`, the Cloud adapter's: a host switches a
|
|
15
|
+
* number between the two transports by mounting one adapter or the other,
|
|
16
|
+
* and its connections and conversations stay where they are. Give another
|
|
17
|
+
* key (`whatsapp-web`) to run both side by side.
|
|
18
|
+
*/
|
|
19
|
+
kind?: string;
|
|
20
|
+
/**
|
|
21
|
+
* When free-form sends are allowed. Default: always. A personal account has
|
|
22
|
+
* no service window; that window is a rule of the Business API.
|
|
23
|
+
*/
|
|
24
|
+
policy?: SendPolicy;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The WhatsApp Web adapter: the same `ChannelAdapter` as the Cloud one, over
|
|
29
|
+
* a Baileys session instead of the Graph API.
|
|
30
|
+
*
|
|
31
|
+
* - `handshake` and `verify`: there is no webhook. The verify FAILS CLOSED,
|
|
32
|
+
* so the webhook route refuses any POST to this channel: inbound arrives
|
|
33
|
+
* only from the session's own socket, through `engine.receive`.
|
|
34
|
+
* - `parse` reads the session's envelope (normalized events, never Baileys'
|
|
35
|
+
* raw objects).
|
|
36
|
+
* - `send` and `fetchMedia` go through the session. The connection's
|
|
37
|
+
* credential is not used: the linked device's keys live in the session's
|
|
38
|
+
* auth store.
|
|
39
|
+
*/
|
|
40
|
+
export function createWhatsAppWebAdapter(config: WhatsAppWebAdapterConfig): ChannelAdapter {
|
|
41
|
+
const sessionFor = (accountId: string): WhatsAppWebSession | undefined => {
|
|
42
|
+
if (typeof config.sessions === "function") return config.sessions(accountId);
|
|
43
|
+
return config.sessions.accountId() === accountId ? config.sessions : undefined;
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
kind: config.kind ?? WHATSAPP_CHANNEL,
|
|
47
|
+
handshake: () => null,
|
|
48
|
+
verify: () => false,
|
|
49
|
+
parse: parseEnvelope,
|
|
50
|
+
send: async ({ accountId, to, content }) => {
|
|
51
|
+
const session = sessionFor(accountId);
|
|
52
|
+
if (!session) throw new ChannelSendFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
|
|
53
|
+
return session.send(to, content);
|
|
54
|
+
},
|
|
55
|
+
fetchMedia: async ({ accountId, mediaId, maxBytes, timeoutMs }) => {
|
|
56
|
+
const session = sessionFor(accountId);
|
|
57
|
+
if (!session) throw new ChannelMediaFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
|
|
58
|
+
return session.downloadMedia(mediaId, { maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) });
|
|
59
|
+
},
|
|
60
|
+
policy: config.policy ?? OPEN_SEND_POLICY,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { BaileysAuthState, BaileysModule } from "./baileys-port";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* WHERE A LINKED SESSION'S KEYS LIVE. The host's, never the package's.
|
|
5
|
+
*
|
|
6
|
+
* A Baileys session is a linked device: its auth state (the account's
|
|
7
|
+
* identity and Signal keys) gives whoever holds it full access to the
|
|
8
|
+
* account, every chat included. The package therefore writes NOTHING itself:
|
|
9
|
+
* the host passes a store, and decides where it lives and how it is sealed
|
|
10
|
+
* (an encrypted column, a secrets manager, a 0600 file on the owner's
|
|
11
|
+
* machine). The package never logs a value, never puts one in an error.
|
|
12
|
+
*
|
|
13
|
+
* Values are opaque JSON text (Baileys' `BufferJSON`); keys are
|
|
14
|
+
* `creds` and `<category>-<id>`.
|
|
15
|
+
*/
|
|
16
|
+
export interface AuthStateStore {
|
|
17
|
+
read(key: string): Promise<string | null>;
|
|
18
|
+
write(key: string, value: string): Promise<void>;
|
|
19
|
+
remove(key: string): Promise<void>;
|
|
20
|
+
/** Remove every key of this session. Optional: without it, a logout removes only `creds`, which already unlinks it. */
|
|
21
|
+
clear?(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** An in-memory store: for tests, and for a session that may be lost at restart (it must pair again). */
|
|
25
|
+
export function createMemoryAuthStateStore(): AuthStateStore & { keys(): string[]; clear(): Promise<void> } {
|
|
26
|
+
const values = new Map<string, string>();
|
|
27
|
+
return {
|
|
28
|
+
read: async (key) => values.get(key) ?? null,
|
|
29
|
+
write: async (key, value) => {
|
|
30
|
+
values.set(key, value);
|
|
31
|
+
},
|
|
32
|
+
remove: async (key) => {
|
|
33
|
+
values.delete(key);
|
|
34
|
+
},
|
|
35
|
+
keys: () => [...values.keys()],
|
|
36
|
+
clear: async () => {
|
|
37
|
+
values.clear();
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const CREDS_KEY = "creds";
|
|
43
|
+
const APP_STATE_SYNC_KEY = "app-state-sync-key";
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Baileys' auth state over a host store: the same recipe as Baileys' own
|
|
47
|
+
* `useMultiFileAuthState`, with the store in place of the folder. A store with
|
|
48
|
+
* no creds yet starts a NEW device (the session pairs); `saveCreds` must run on
|
|
49
|
+
* every `creds.update`.
|
|
50
|
+
*/
|
|
51
|
+
export async function loadAuthState(
|
|
52
|
+
baileys: Pick<BaileysModule<unknown>, "initAuthCreds" | "BufferJSON" | "proto">,
|
|
53
|
+
store: AuthStateStore,
|
|
54
|
+
): Promise<{ state: BaileysAuthState; saveCreds: () => Promise<void>; isNew: boolean }> {
|
|
55
|
+
const encode = (value: unknown): string => JSON.stringify(value, baileys.BufferJSON.replacer);
|
|
56
|
+
const decode = (text: string | null): unknown => (text === null ? null : (JSON.parse(text, baileys.BufferJSON.reviver) as unknown));
|
|
57
|
+
|
|
58
|
+
const stored = decode(await store.read(CREDS_KEY));
|
|
59
|
+
const isNew = stored === null || typeof stored !== "object";
|
|
60
|
+
const creds = isNew ? baileys.initAuthCreds() : (stored as object);
|
|
61
|
+
const appStateKey = baileys.proto?.Message?.AppStateSyncKeyData;
|
|
62
|
+
|
|
63
|
+
const state: BaileysAuthState = {
|
|
64
|
+
creds,
|
|
65
|
+
keys: {
|
|
66
|
+
get: async (type, ids) => {
|
|
67
|
+
const found: Record<string, unknown> = {};
|
|
68
|
+
await Promise.all(
|
|
69
|
+
ids.map(async (id) => {
|
|
70
|
+
let value = decode(await store.read(`${type}-${id}`));
|
|
71
|
+
if (type === APP_STATE_SYNC_KEY && value && appStateKey) value = appStateKey.fromObject(value);
|
|
72
|
+
found[id] = value ?? undefined;
|
|
73
|
+
}),
|
|
74
|
+
);
|
|
75
|
+
return found;
|
|
76
|
+
},
|
|
77
|
+
set: async (data) => {
|
|
78
|
+
const writes = Object.entries(data).flatMap(([category, entries]) =>
|
|
79
|
+
Object.entries(entries).map(([id, value]) => (value ? store.write(`${category}-${id}`, encode(value)) : store.remove(`${category}-${id}`))),
|
|
80
|
+
);
|
|
81
|
+
await Promise.all(writes);
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
return { state, saveCreds: () => store.write(CREDS_KEY, encode(creds)), isNew };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Forget a session's keys, after a logout: the next start pairs a NEW device. */
|
|
89
|
+
export async function clearAuthState(store: AuthStateStore): Promise<void> {
|
|
90
|
+
if (store.clear) await store.clear();
|
|
91
|
+
else await store.remove(CREDS_KEY);
|
|
92
|
+
}
|