@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/opt-out.ts","../src/whatsapp/parse.ts","../src/whatsapp/graph.ts","../src/whatsapp/media.ts","../src/whatsapp/signature.ts","../src/whatsapp/signup.ts","../src/whatsapp/index.ts"],"sourcesContent":["/**\n * The words that opt a contact out, by default: the Portuguese and English\n * stop words a WhatsApp user is told to send. A host replaces the list through\n * the adapter's config.\n */\nexport const DEFAULT_OPT_OUT_KEYWORDS: readonly string[] = [\"PARAR\", \"SAIR\", \"STOP\", \"CANCELAR\"];\n\n/** Upper case, accents stripped, surrounding space, punctuation and emoji trimmed. */\nfunction fold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\")\n .toUpperCase();\n}\n\n/**\n * Is this text an opt-out? Only when the WHOLE message is one keyword —\n * case- and accent-insensitive, ignoring punctuation and emoji around it — so\n * \"parar\", \"PARAR.\" and \"Parar!\" opt out, and \"parar de enviar\" (a sentence,\n * maybe about something else) does not.\n */\nexport function isOptOutText(text: string, keywords: readonly string[] = DEFAULT_OPT_OUT_KEYWORDS): boolean {\n const folded = fold(text);\n return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);\n}\n","import type {\n InboundContent,\n InboundMessageEvent,\n NormalizedEvent,\n OptOutEvent,\n ReceiptStatus,\n StatusEvent,\n} from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\n\n/**\n * The WhatsApp Cloud API webhook payload, read defensively: every field is\n * checked before it is trusted, an unknown shape is skipped rather than\n * thrown on, and only `JSON.parse` itself may throw (bytes that are not JSON).\n *\n * Shape: `{ object: \"whatsapp_business_account\", entry: [{ id, changes: [{\n * field, value: { metadata: { phone_number_id }, contacts, messages,\n * statuses, user_preferences } }] }] }`. Events come out in payload order.\n */\n\ntype Json = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isObject) : []);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Meta's timestamps are Unix SECONDS, as a string. Null when absent or malformed. */\nfunction when(value: unknown): Date | null {\n const seconds = typeof value === \"string\" || typeof value === \"number\" ? Number(value) : Number.NaN;\n return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : null;\n}\n\ninterface Change {\n value: Json;\n accountId: string;\n}\n\n/** Every `value` of every change, with the account it was delivered to. */\nfunction changes(payload: unknown): Change[] {\n if (!isObject(payload) || payload.object !== \"whatsapp_business_account\") return [];\n return list(payload.entry)\n .flatMap((entry) => list(entry.changes))\n .flatMap((change): Change[] => {\n const value = change.value;\n const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;\n return isObject(value) && accountId ? [{ value, accountId }] : [];\n });\n}\n\n/** One reader per message `type`; null when the type's object is missing or malformed. */\nconst CONTENT_READERS: Readonly<Record<string, (message: Json) => InboundContent | null>> = {\n text: (message) => {\n const body = isObject(message.text) ? text(message.text.body) : null;\n return body ? { kind: \"TEXT\", text: body } : null;\n },\n interactive: (message) => {\n const interactive = isObject(message.interactive) ? message.interactive : {};\n const reply = interactive.button_reply ?? interactive.list_reply;\n const id = isObject(reply) ? text(reply.id) : null;\n return isObject(reply) && id ? { kind: \"INTERACTIVE\", replyId: id, title: text(reply.title) ?? \"\" } : null;\n },\n // A quick-reply button on a template message.\n button: (message) => {\n if (!isObject(message.button)) return null;\n const title = text(message.button.text) ?? \"\";\n return { kind: \"INTERACTIVE\", replyId: text(message.button.payload) ?? title, title };\n },\n audio: (message) => {\n const id = isObject(message.audio) ? text(message.audio.id) : null;\n return isObject(message.audio) && id ? { kind: \"AUDIO\", mediaId: id, mimeType: text(message.audio.mime_type) } : null;\n },\n};\n\n/** The content of one message, by its `type`; anything unread is OTHER. */\nfunction contentOf(message: Json): InboundContent {\n const type = text(message.type) ?? \"unknown\";\n return CONTENT_READERS[type]?.(message) ?? { kind: \"OTHER\", channelType: type };\n}\n\n/** The words a person typed or tapped, for the opt-out check. */\nfunction wordsOf(content: InboundContent): string | null {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"INTERACTIVE\") return content.title;\n return null;\n}\n\n/** The profile name Meta sends per sender, keyed by wa_id. */\nfunction contactNames(value: Json): Map<string, string> {\n const names = new Map<string, string>();\n for (const contact of list(value.contacts)) {\n const waId = text(contact.wa_id);\n const name = isObject(contact.profile) ? text(contact.profile.name) : null;\n if (waId && name) names.set(waId, name);\n }\n return names;\n}\n\nfunction messageEvent(\n message: Json,\n accountId: string,\n names: Map<string, string>,\n keywords: readonly string[],\n): InboundMessageEvent | null {\n const contactId = text(message.from);\n const externalId = text(message.id);\n const sentAt = when(message.timestamp);\n if (!contactId || !externalId || !sentAt) return null;\n const content = contentOf(message);\n const words = wordsOf(content);\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: names.get(contactId) ?? null,\n externalId,\n sentAt,\n content,\n optOut: words !== null && isOptOutText(words, keywords),\n };\n}\n\nfunction messageEvents(value: Json, accountId: string, keywords: readonly string[]): InboundMessageEvent[] {\n const names = contactNames(value);\n return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);\n}\n\nconst RECEIPTS: Readonly<Record<string, ReceiptStatus>> = {\n sent: \"SENT\",\n delivered: \"DELIVERED\",\n read: \"READ\",\n failed: \"FAILED\",\n};\n\n/** The first error of a failed status, as `code: title`. */\nfunction errorOf(status: Json): string | null {\n const [first] = list(status.errors);\n if (!first) return null;\n const code = first.code === undefined ? \"\" : String(first.code);\n const title = text(first.title) ?? text(first.message) ?? \"\";\n return [code, title].filter(Boolean).join(\": \") || null;\n}\n\nfunction statusEvents(value: Json, accountId: string): StatusEvent[] {\n const out: StatusEvent[] = [];\n for (const status of list(value.statuses)) {\n const externalId = text(status.id);\n const receipt = RECEIPTS[text(status.status) ?? \"\"];\n const at = when(status.timestamp);\n if (!externalId || !receipt || !at) continue;\n out.push({\n type: \"status\",\n accountId,\n externalId,\n status: receipt,\n at,\n contactId: text(status.recipient_id),\n error: receipt === \"FAILED\" ? errorOf(status) : null,\n callbackData: text(status.biz_opaque_callback_data),\n });\n }\n return out;\n}\n\n/** Meta's own opt-out: a `user_preferences` change whose value is `stop`. */\nfunction preferenceEvents(value: Json, accountId: string): OptOutEvent[] {\n const out: OptOutEvent[] = [];\n for (const preference of list(value.user_preferences)) {\n const contactId = text(preference.wa_id);\n const at = when(preference.timestamp);\n if (contactId && at && text(preference.value)?.toLowerCase() === \"stop\") {\n out.push({ type: \"opt_out\", accountId, contactId, at });\n }\n }\n return out;\n}\n\n/**\n * Every event in a WhatsApp webhook payload (already `JSON.parse`d): inbound\n * messages (with the opt-out keyword check), delivery receipts, and Meta's\n * own opt-out signal.\n */\nexport function parseWhatsAppPayload(\n payload: unknown,\n options: { optOutKeywords?: readonly string[] } = {},\n): NormalizedEvent[] {\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n const out: NormalizedEvent[] = [];\n for (const { value, accountId } of changes(payload)) {\n out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));\n }\n return out;\n}\n\n/**\n * Only the delivery receipts of a WhatsApp webhook payload — for a host that\n * tracks receipts of messages it sends some other way (a platform\n * notification number) without mounting the connector.\n */\nexport function parseWhatsAppStatuses(payload: unknown): StatusEvent[] {\n return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));\n}\n","import { ChannelSendFailure } from \"../core/channel\";\nimport type { OutboundContent } from \"../core/types\";\n\n/**\n * The only way the adapter reaches Meta: an injected fetch. The global\n * `fetch` satisfies it; a test answers it with a recording fake.\n *\n * A JSON call reads `text()` only. A media download also asks for\n * `redirect: \"manual\"` (a 3xx comes back as itself, never followed) and reads\n * the binary body through `body` (a stream, read up to the size cap) or, when\n * there is none, `arrayBuffer()`. All three are optional so a text-only fake\n * still satisfies the port.\n */\nexport type FetchPort = (url: string, init: FetchInit) => Promise<FetchResponse>;\n\nexport interface FetchInit {\n method: string;\n headers: Record<string, string>;\n body?: string;\n /** `manual` for a media download: a redirect is answered, never followed. */\n redirect?: \"manual\" | \"follow\" | \"error\";\n /** Aborts the call at a media download's deadline. */\n signal?: AbortSignal;\n}\n\nexport interface FetchResponse {\n status: number;\n text(): Promise<string>;\n arrayBuffer?(): Promise<ArrayBuffer>;\n /** The body as a stream; read chunk by chunk so an oversized one is cut off early. */\n body?: { getReader(): FetchBodyReader; cancel?(reason?: unknown): Promise<void> } | null;\n headers?: { get(name: string): string | null };\n}\n\nexport interface FetchBodyReader {\n read(): Promise<{ done: boolean; value?: Uint8Array }>;\n cancel(reason?: unknown): Promise<void>;\n}\n\n/**\n * The hosts Meta serves WhatsApp media from: the URL a media lookup returns is\n * `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=…`, and the\n * CDN families behind it. `*.` matches any subdomain (not the bare domain).\n */\nexport const DEFAULT_META_MEDIA_HOSTS: readonly string[] = [\"lookaside.fbsbx.com\", \"*.fbcdn.net\", \"*.whatsapp.net\"];\n\n/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */\nexport interface GraphConfig {\n fetch: FetchPort;\n /** `https://graph.facebook.com` — no trailing slash needed. */\n baseUrl: string;\n /** `v23.0` — the Graph API version every call is pinned to. */\n apiVersion: string;\n /**\n * The hosts a media URL may point at; any other is refused before the token\n * is sent to it. Exact names, or `*.domain` for its subdomains. Default\n * {@link DEFAULT_META_MEDIA_HOSTS}.\n */\n mediaHosts?: readonly string[];\n}\n\n/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */\nexport class GraphError extends ChannelSendFailure {\n readonly status: number;\n constructor(status: number, code: string, message: string) {\n super(code, message);\n this.name = \"GraphError\";\n this.status = status;\n }\n}\n\ntype Json = Record<string, unknown>;\n\ninterface GraphCall {\n method: \"GET\" | \"POST\";\n path: string;\n token?: string;\n query?: Record<string, string>;\n body?: unknown;\n redirect?: FetchInit[\"redirect\"];\n signal?: AbortSignal;\n}\n\n/** Drops trailing \"/\" characters in one linear pass (a regex here backtracks quadratically on library input). */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return end === value.length ? value : value.slice(0, end);\n}\n\n/** The URL and the request init of one call. The token travels in a header, never in the URL. */\nfunction requestOf(graph: GraphConfig, call: GraphCall) {\n const base = trimTrailingSlashes(graph.baseUrl);\n const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (call.token) headers.authorization = `Bearer ${call.token}`;\n if (call.body !== undefined) headers[\"content-type\"] = \"application/json\";\n return {\n url: `${base}/${graph.apiVersion}/${call.path}${query}`,\n init: {\n method: call.method,\n headers,\n ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),\n ...(call.redirect ? { redirect: call.redirect } : {}),\n ...(call.signal ? { signal: call.signal } : {}),\n } satisfies FetchInit,\n };\n}\n\n/** A body as a JSON object; anything else (empty, HTML, an array) as `{}`. */\nfunction objectOf(raw: string): Json {\n try {\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as Json) : {};\n } catch {\n return {};\n }\n}\n\n/** Meta's error envelope (`{ error: { code, message } }`) as a {@link GraphError}. */\nfunction graphErrorOf(status: number, json: Json): GraphError {\n const error = typeof json.error === \"object\" && json.error !== null ? (json.error as Json) : {};\n const code = error.code === undefined ? `HTTP_${status}` : String(error.code);\n const message = typeof error.message === \"string\" ? error.message : `Graph answered ${status}`;\n return new GraphError(status, code, message.slice(0, 300));\n}\n\n/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */\nexport async function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json> {\n const { url, init } = requestOf(graph, call);\n const response = await graph.fetch(url, init);\n const json = objectOf(await response.text());\n if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);\n return json;\n}\n\n/** The Cloud API body for one outbound message. */\nexport function messageBody(to: string, content: OutboundContent): Json {\n const base = { messaging_product: \"whatsapp\", recipient_type: \"individual\", to };\n if (content.kind === \"TEXT\") return { ...base, type: \"text\", text: { body: content.text, preview_url: false } };\n if (content.kind === \"BUTTONS\") {\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"button\",\n body: { text: content.text },\n action: { buttons: content.buttons.map((button) => ({ type: \"reply\", reply: { id: button.id, title: button.title } })) },\n },\n };\n }\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"list\",\n body: { text: content.text },\n action: {\n button: content.buttonLabel,\n sections: content.sections.map((section) => ({\n ...(section.title ? { title: section.title } : {}),\n rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...(row.description ? { description: row.description } : {}) })),\n })),\n },\n },\n };\n}\n\n/** Send one message from a phone number; resolves to its wamid. */\nexport async function sendWhatsAppMessage(\n graph: GraphConfig,\n input: { token: string; phoneNumberId: string; to: string; content: OutboundContent },\n): Promise<{ externalId: string }> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.phoneNumberId)}/messages`,\n token: input.token,\n body: messageBody(input.to, input.content),\n });\n const [first] = Array.isArray(json.messages) ? (json.messages as Json[]) : [];\n const id = first && typeof first.id === \"string\" ? first.id : null;\n if (!id) throw new GraphError(200, \"NO_MESSAGE_ID\", \"Graph accepted the message but returned no id\");\n return { externalId: id };\n}\n","import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, isPositiveSafeInteger, type ChannelMedia } from \"../core/channel\";\nimport { DEFAULT_META_MEDIA_HOSTS, graphRequest, type FetchResponse, type GraphConfig } from \"./graph\";\n\n/**\n * A WhatsApp media download, the Cloud API way: `GET /{version}/{media-id}`\n * with the business token answers `{ url, mime_type, file_size }`, and a\n * `GET` of that URL with the same token answers the bytes.\n *\n * The token travels in the Authorization header only, and only to a Meta\n * media host over https: the URL comes from Meta, but it is still checked\n * against the configured hosts before the token is sent to it, and a redirect\n * is refused rather than followed to wherever it points. The size is capped\n * twice — the declared `file_size` before the download, the bytes actually\n * read during it — the whole download has a deadline, and the media lives\n * only in the returned memory.\n */\n\nconst OCTET_STREAM = \"application/octet-stream\";\n\n/** Does `host` match one allowlist entry: an exact name, or `*.domain` for its subdomains. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const pattern = entry.toLowerCase();\n // \"*.fbcdn.net\" matches \"x.fbcdn.net\" through its \".fbcdn.net\" suffix, never \"fbcdn.net\" or \"evilfbcdn.net\".\n return pattern.startsWith(\"*.\") ? host.endsWith(pattern.slice(1)) : host === pattern;\n });\n}\n\n/** The media URL Meta returned, checked: https, no userinfo, an allowed host. */\nfunction checkedMediaUrl(raw: unknown, allowed: readonly string[]): string {\n if (typeof raw !== \"string\" || raw === \"\") throw new ChannelMediaFailure(\"NO_MEDIA_URL\", \"Graph returned no media url\");\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new ChannelMediaFailure(\"MEDIA_URL_INVALID\", \"Graph returned a media url that does not parse\");\n }\n if (url.protocol !== \"https:\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url is not https\");\n if (url.username || url.password) throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url carries credentials\");\n if (url.port !== \"\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url names an explicit port\");\n if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {\n throw new ChannelMediaFailure(\"MEDIA_HOST_REFUSED\", `the media host ${url.hostname} is not a Meta media host`);\n }\n return url.toString();\n}\n\nconst tooLarge = (size: number, maxBytes: number) =>\n new ChannelMediaFailure(\"TOO_LARGE\", `the media is ${size} bytes, over the ${maxBytes}-byte cap`);\n\n/** A declared size over the cap refuses the download before it starts. */\nfunction checkDeclaredSize(declared: unknown, maxBytes: number): void {\n const size = typeof declared === \"number\" ? declared : typeof declared === \"string\" ? Number(declared) : NaN;\n if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);\n}\n\n/** Concatenate the chunks read so far. */\nfunction joined(chunks: Uint8Array[], total: number): Uint8Array {\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/** The download's deadline: one abort signal for both calls, and a race for every read. */\ninterface Deadline {\n signal: AbortSignal;\n /** `promise`, or a `TIMEOUT` failure once the deadline passes — whichever comes first. */\n race<T>(promise: Promise<T>): Promise<T>;\n clear(): void;\n}\n\nconst timedOut = (timeoutMs: number) =>\n new ChannelMediaFailure(\"TIMEOUT\", `the media download did not finish within ${timeoutMs} ms`);\n\nfunction deadlineOf(timeoutMs: number): Deadline {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(timedOut(timeoutMs));\n }, timeoutMs);\n });\n // The race below observes it; this only keeps an unobserved expiry from being reported unhandled.\n expired.catch(() => undefined);\n return {\n signal: controller.signal,\n race: async (promise) => {\n try {\n return await Promise.race([promise, expired]);\n } catch (error) {\n // A port that honours the signal rejects with its own abort error: it is the deadline all the same.\n throw controller.signal.aborted ? timedOut(timeoutMs) : error;\n }\n },\n clear: () => clearTimeout(timer),\n };\n}\n\n/** Release a body that will not be read; never throws. */\nfunction discardBody(response: FetchResponse): void {\n try {\n void Promise.resolve(response.body?.cancel?.()).catch(() => undefined);\n } catch {\n // A body that cannot even be cancelled is left to the garbage collector.\n }\n}\n\n/** Read a stream, cancelling it the moment it passes the cap or the deadline. */\nasync function readStreamCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const reader = response.body!.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await deadline.race(reader.read());\n if (done) break;\n if (!value) continue;\n total += value.length;\n if (total > maxBytes) throw tooLarge(total, maxBytes);\n chunks.push(value);\n }\n } catch (error) {\n void reader.cancel().catch(() => undefined);\n throw error;\n }\n return joined(chunks, total);\n}\n\n/** The body's bytes, never more than `maxBytes` of them — whatever the headers declared. */\nasync function readBodyCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const declared = response.headers?.get(\"content-length\");\n if (declared) {\n try {\n checkDeclaredSize(declared, maxBytes);\n } catch (error) {\n discardBody(response);\n throw error;\n }\n }\n if (response.body && typeof response.body.getReader === \"function\") return readStreamCapped(response, maxBytes, deadline);\n if (!response.arrayBuffer) throw new ChannelMediaFailure(\"NO_BINARY_BODY\", \"the fetch port cannot read a binary body\");\n // Only for a port with no stream: it reads the WHOLE body before the cap can be checked.\n const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));\n if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);\n return bytes;\n}\n\n/** GET the media URL with the token in a header; a redirect or a non-2xx is refused, its body discarded. */\nasync function downloadFrom(graph: GraphConfig, url: string, token: string, deadline: Deadline): Promise<FetchResponse> {\n const response = await deadline.race(\n graph.fetch(url, {\n method: \"GET\",\n headers: { authorization: `Bearer ${token}`, accept: \"*/*\" },\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n if (response.status >= 200 && response.status < 300) return response;\n discardBody(response);\n if (response.status >= 300 && response.status < 400) {\n throw new ChannelMediaFailure(\"REDIRECT_REFUSED\", `the media download answered ${response.status}; redirects are not followed`);\n }\n throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);\n}\n\n/** A cap or deadline that would not bound anything (NaN, Infinity, 0, negative, fractional) is refused. */\nfunction checkLimits(maxBytes: number, timeoutMs: number): void {\n if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {\n throw new ChannelMediaFailure(\"BAD_OPTIONS\", \"maxBytes and timeoutMs must be positive safe integers\");\n }\n}\n\n/** Download one WhatsApp media object into memory. */\nexport async function downloadWhatsAppMedia(\n graph: GraphConfig,\n input: { token: string; mediaId: string; maxBytes: number; timeoutMs?: number },\n): Promise<ChannelMedia> {\n const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;\n checkLimits(input.maxBytes, timeoutMs);\n const deadline = deadlineOf(timeoutMs);\n try {\n const meta = await deadline.race(\n graphRequest(graph, {\n method: \"GET\",\n path: encodeURIComponent(input.mediaId),\n token: input.token,\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);\n checkDeclaredSize(meta.file_size, input.maxBytes);\n const response = await downloadFrom(graph, url, input.token, deadline);\n const bytes = await readBodyCapped(response, input.maxBytes, deadline);\n const declaredType = typeof meta.mime_type === \"string\" && meta.mime_type ? meta.mime_type : null;\n const mimeType = declaredType ?? response.headers?.get(\"content-type\") ?? OCTET_STREAM;\n return { bytes, mimeType, size: bytes.length };\n } finally {\n deadline.clear();\n }\n}\n","import { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Meta's webhook proofs, as standalone functions: the connector's WhatsApp\n * adapter uses them, and so can any other WhatsApp webhook a host runs (a\n * platform notification number's receipts), without mounting the connector.\n */\n\n/** The header Meta signs every webhook POST with. */\nexport const META_SIGNATURE_HEADER = \"x-hub-signature-256\";\n\nconst SIGNATURE = /^sha256=([0-9a-f]{64})$/i;\n\n/**\n * Does `signatureHeader` prove `rawBody` was signed with `appSecret`?\n *\n * HMAC-SHA256 over the RAW body bytes exactly as received (a re-serialized\n * JSON body never matches; hand the bytes, not a decoded string, where the\n * framework gives them), compared in constant time. Fails CLOSED: an empty\n * secret, a missing header, a header in any other shape, or a digest of the\n * wrong length is `false` — never an exception, never `true`.\n */\nexport function verifyMetaSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, appSecret: string): boolean {\n if (!appSecret || !signatureHeader) return false;\n const match = SIGNATURE.exec(signatureHeader.trim());\n if (!match) return false;\n const expected = createHmac(\"sha256\", appSecret).update(rawBody).digest();\n const given = Buffer.from(match[1]!, \"hex\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n\n/** What the subscription handshake answers. */\nexport type MetaHandshake = { ok: true; challenge: string } | { ok: false };\n\n/**\n * Meta's `GET` subscription handshake: `hub.mode=subscribe`, the\n * `hub.verify_token` configured on the app, and a `hub.challenge` to echo.\n * The token is compared in constant time; an empty configured token refuses\n * every handshake.\n */\nexport function verifyMetaSubscription(\n query: Readonly<Record<string, string | undefined>>,\n verifyToken: string,\n): MetaHandshake {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (!verifyToken || mode !== \"subscribe\" || !token || !challenge) return { ok: false };\n // Digests of equal length, so the comparison leaks neither content nor length.\n const digest = (value: string) => createHash(\"sha256\").update(value, \"utf8\").digest();\n return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };\n}\n","import { GraphError, graphRequest, type GraphConfig } from \"./graph\";\n\n/**\n * Embedded Signup, server half. The browser half (Meta's SDK popup) hands the\n * host a short-lived `code`; these three calls turn it into a connection:\n *\n * 1. {@link exchangeSignupCode} — the code for a business token;\n * 2. {@link readSignupAccounts} — which WhatsApp Business Accounts the token\n * was granted, and each one's phone numbers (id + display number);\n * 3. {@link subscribeAppToWaba} — subscribe the app to the chosen account's\n * webhooks, so its messages reach the connector.\n *\n * Then the host calls `engine.connect(...)` with the phone number id, the\n * display number and the token, which the engine seals. None of these\n * functions logs or returns anything but what is named.\n */\n\ntype Json = Record<string, unknown>;\n\n/** The app's own identity on Meta. The secret is the host's, read where it keeps secrets. */\nexport interface MetaAppCredentials {\n appId: string;\n appSecret: string;\n}\n\n/** Exchange Embedded Signup's code for a business integration token. */\nexport async function exchangeSignupCode(\n graph: GraphConfig,\n input: MetaAppCredentials & { code: string; redirectUri?: string },\n): Promise<{ accessToken: string }> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: \"oauth/access_token\",\n query: {\n client_id: input.appId,\n client_secret: input.appSecret,\n code: input.code,\n ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),\n },\n });\n if (typeof json.access_token !== \"string\" || json.access_token.length === 0) {\n throw new GraphError(200, \"NO_ACCESS_TOKEN\", \"Graph answered the code exchange without a token\");\n }\n return { accessToken: json.access_token };\n}\n\n/** One phone number of a WhatsApp Business Account. */\nexport interface SignupPhoneNumber {\n /** The phone_number_id: the connection's external account id. */\n id: string;\n /** What a person reads (`+55 11 98765-4321`): the connection's display address. */\n displayPhoneNumber: string;\n verifiedName: string | null;\n}\n\nexport interface SignupAccount {\n /** The WABA id: the connection's external parent id. */\n wabaId: string;\n phoneNumbers: SignupPhoneNumber[];\n}\n\n/**\n * The WhatsApp Business Accounts the token was granted (read from the token's\n * own granular scopes, with the app's token), and each one's phone numbers.\n */\nexport async function readSignupAccounts(\n graph: GraphConfig,\n input: MetaAppCredentials & { accessToken: string },\n): Promise<SignupAccount[]> {\n const debug = await graphRequest(graph, {\n method: \"GET\",\n path: \"debug_token\",\n query: { input_token: input.accessToken },\n token: `${input.appId}|${input.appSecret}`,\n });\n const data = typeof debug.data === \"object\" && debug.data !== null ? (debug.data as Json) : {};\n const scopes = Array.isArray(data.granular_scopes) ? (data.granular_scopes as Json[]) : [];\n const wabaIds = new Set(\n scopes\n .filter((scope) => scope.scope === \"whatsapp_business_management\" && Array.isArray(scope.target_ids))\n .flatMap((scope) => (scope.target_ids as unknown[]).filter((id): id is string => typeof id === \"string\")),\n );\n const accounts: SignupAccount[] = [];\n for (const wabaId of wabaIds) {\n accounts.push({ wabaId, phoneNumbers: await readPhoneNumbers(graph, wabaId, input.accessToken) });\n }\n return accounts;\n}\n\nasync function readPhoneNumbers(graph: GraphConfig, wabaId: string, accessToken: string): Promise<SignupPhoneNumber[]> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: `${encodeURIComponent(wabaId)}/phone_numbers`,\n query: { fields: \"id,display_phone_number,verified_name\" },\n token: accessToken,\n });\n const rows = Array.isArray(json.data) ? (json.data as Json[]) : [];\n return rows\n .filter((row) => typeof row.id === \"string\" && typeof row.display_phone_number === \"string\")\n .map((row) => ({\n id: row.id as string,\n displayPhoneNumber: row.display_phone_number as string,\n verifiedName: typeof row.verified_name === \"string\" ? row.verified_name : null,\n }));\n}\n\n/** Subscribe the app to a WABA's webhooks. Resolves when Meta answers `success: true`. */\nexport async function subscribeAppToWaba(graph: GraphConfig, input: { wabaId: string; accessToken: string }): Promise<void> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.wabaId)}/subscribed_apps`,\n token: input.accessToken,\n });\n if (json.success !== true) throw new GraphError(200, \"NOT_SUBSCRIBED\", \"Graph did not confirm the subscription\");\n}\n","/**\n * `@12-apps/messaging/whatsapp` — the WhatsApp Cloud API channel adapter.\n *\n * `createWhatsAppAdapter(config)` is what a host hands the engine. The pieces\n * are exported on their own too: the signature check and the receipt parser\n * serve any WhatsApp webhook (a platform notification number), and the\n * Embedded Signup helpers serve the host's connect flow.\n *\n * `@12-apps/notifications` has its own WhatsApp transport, for one-way\n * notification messages. It is deliberately NOT reused here: this adapter\n * carries a conversation (inbound, the service window, opt-out, receipts),\n * which that transport has no model for.\n */\n\nimport { serviceWindowPolicy, type ChannelAdapter } from \"../core/channel\";\nimport { parseWhatsAppPayload } from \"./parse\";\nimport { sendWhatsAppMessage, type GraphConfig } from \"./graph\";\nimport { downloadWhatsAppMedia } from \"./media\";\nimport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from \"./signature\";\n\n/** The channel key every WhatsApp row carries. */\nexport const WHATSAPP_CHANNEL = \"whatsapp\";\n\n/** WhatsApp's customer service window: free-form messages only within 24 h of the contact's last message. */\nexport const WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1000;\n\nexport interface WhatsAppAdapterConfig {\n /** The Meta app's secret: every webhook POST is signed with it. Empty refuses every delivery. */\n appSecret: string;\n /** The token configured on the app's webhook subscription. Empty refuses every handshake. */\n verifyToken: string;\n /** The Graph API: fetch, base URL and version. */\n graph: GraphConfig;\n /** The whole-message words that opt a contact out. Default: PARAR, SAIR, STOP, CANCELAR. */\n optOutKeywords?: readonly string[];\n}\n\n/** The WhatsApp Cloud adapter. */\nexport function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter {\n return {\n kind: WHATSAPP_CHANNEL,\n handshake: (query) => verifyMetaSubscription(query, config.verifyToken),\n verify: ({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret),\n parse: (rawBody) =>\n parseWhatsAppPayload(JSON.parse(rawBody) as unknown, {\n ...(config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}),\n }),\n send: ({ credential, accountId, to, content }) =>\n sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),\n fetchMedia: ({ credential, mediaId, maxBytes, timeoutMs }) =>\n downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }),\n policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),\n };\n}\n\nexport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from \"./signature\";\nexport { parseWhatsAppPayload, parseWhatsAppStatuses } from \"./parse\";\nexport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\nexport {\n DEFAULT_META_MEDIA_HOSTS,\n GraphError,\n graphRequest,\n messageBody,\n sendWhatsAppMessage,\n type FetchBodyReader,\n type FetchInit,\n type FetchPort,\n type FetchResponse,\n type GraphConfig,\n} from \"./graph\";\nexport { downloadWhatsAppMedia } from \"./media\";\nexport {\n exchangeSignupCode,\n readSignupAccounts,\n subscribeAppToWaba,\n type MetaAppCredentials,\n type SignupAccount,\n type SignupPhoneNumber,\n} from \"./signup\";\n"],"mappings":";;;;;;;;;;;;AAKO,IAAM,2BAA8C,CAAC,SAAS,QAAQ,QAAQ,UAAU;AAG/F,SAAS,KAAKA,OAAsB;AAClC,SAAOA,MACJ,UAAU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C5E,EAAE;AACN;AAfe;AAkBf,eAAsB,mBAAmB,OAAoB,OAA+D;AAC1H,QAAM,OAAO,MAAM,aAAa,OAAO;AAAA,IACrC,QAAQ;AAAA,IACR,MAAM,GAAG,mBAAmB,MAAM,MAAM,CAAC;AAAA,IACzC,OAAO,MAAM;AAAA,EACf,CAAC;AACD,MAAI,KAAK,YAAY,KAAM,OAAM,IAAI,WAAW,KAAK,kBAAkB,wCAAwC;AACjH;AAPsB;;;ACtFf,IAAM,mBAAmB;AAGzB,IAAM,6BAA6B,KAAK,KAAK,KAAK;AAclD,SAAS,sBAAsB,QAA+C;AACnF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,WAAW,wBAAC,UAAU,uBAAuB,OAAO,OAAO,WAAW,GAA3D;AAAA,IACX,QAAQ,wBAAC,EAAE,SAAS,OAAO,MAAM,oBAAoB,SAAS,OAAO,qBAAqB,GAAG,OAAO,SAAS,GAArG;AAAA,IACR,OAAO,wBAAC,YACN,qBAAqB,KAAK,MAAM,OAAO,GAAc;AAAA,MACnD,GAAI,OAAO,iBAAiB,EAAE,gBAAgB,OAAO,eAAe,IAAI,CAAC;AAAA,IAC3E,CAAC,GAHI;AAAA,IAIP,MAAM,wBAAC,EAAE,YAAY,WAAW,IAAI,QAAQ,MAC1C,oBAAoB,OAAO,OAAO,EAAE,OAAO,YAAY,eAAe,WAAW,IAAI,QAAQ,CAAC,GAD1F;AAAA,IAEN,YAAY,wBAAC,EAAE,YAAY,SAAS,UAAU,UAAU,MACtD,sBAAsB,OAAO,OAAO,EAAE,OAAO,YAAY,SAAS,UAAU,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC,EAAG,CAAC,GADrH;AAAA,IAEZ,QAAQ,oBAAoB,0BAA0B;AAAA,EACxD;AACF;AAfgB;","names":["text"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-
|
|
1
|
+
import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-BWhnnuip.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* THE STORE PORT: every read and write the engine makes, as named operations.
|
|
@@ -236,6 +236,11 @@ interface InboundMessageNotice {
|
|
|
236
236
|
conversation: ConversationView;
|
|
237
237
|
message: MessageView;
|
|
238
238
|
}
|
|
239
|
+
/** What `onStaffReply` is told: the conversation, and the stored message the owner sent from another device. */
|
|
240
|
+
interface StaffReplyNotice {
|
|
241
|
+
conversation: ConversationView;
|
|
242
|
+
message: MessageView;
|
|
243
|
+
}
|
|
239
244
|
/** What a re-opened conversation may become. */
|
|
240
245
|
type ReopenState = Exclude<ConversationState, "OPTED_OUT">;
|
|
241
246
|
/** The host's answers to what only it knows about a conversation. All optional. */
|
|
@@ -248,6 +253,16 @@ interface MessagingHooks {
|
|
|
248
253
|
* retried, because the message is already stored. Default: nothing.
|
|
249
254
|
*/
|
|
250
255
|
onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;
|
|
256
|
+
/**
|
|
257
|
+
* The account's owner answered a contact from ANOTHER device (their phone),
|
|
258
|
+
* on a channel that shows it (WhatsApp Web's `sent_elsewhere` event). The
|
|
259
|
+
* message is stored first, as an outbound `STAFF` message, and this runs once
|
|
260
|
+
* per stored message, never for a redelivery and never for the echo of a send
|
|
261
|
+
* the engine made. The engine changes no state itself: a host that wants its
|
|
262
|
+
* agent to step aside does it here (`setState(..., "HUMAN")`, a timer).
|
|
263
|
+
* A throw is logged, never retried. Default: nothing.
|
|
264
|
+
*/
|
|
265
|
+
onStaffReply?(notice: StaffReplyNotice): Promise<void> | void;
|
|
251
266
|
/**
|
|
252
267
|
* The state a CLOSED or OPTED_OUT conversation re-opens into when its
|
|
253
268
|
* contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`
|
|
@@ -319,9 +334,11 @@ declare const MESSAGING_DEFAULTS: {
|
|
|
319
334
|
* the event is dropped (the edge already answered 200, so the channel stops
|
|
320
335
|
* redelivering) and a tenant can never receive another tenant's traffic.
|
|
321
336
|
*/
|
|
322
|
-
type EventOutcome =
|
|
337
|
+
type EventOutcome =
|
|
338
|
+
/** `no-conversation`: a message the owner sent from their phone to a contact the store has no conversation with here. */
|
|
339
|
+
{
|
|
323
340
|
kind: "dropped";
|
|
324
|
-
reason: "unknown-account" | "not-connected";
|
|
341
|
+
reason: "unknown-account" | "not-connected" | "no-conversation";
|
|
325
342
|
} | {
|
|
326
343
|
kind: "duplicate";
|
|
327
344
|
} | {
|
|
@@ -331,6 +348,12 @@ type EventOutcome = {
|
|
|
331
348
|
} | {
|
|
332
349
|
kind: "opted-out";
|
|
333
350
|
conversationId: string;
|
|
351
|
+
}
|
|
352
|
+
/** A message the owner sent from another device, stored as the store's own. */
|
|
353
|
+
| {
|
|
354
|
+
kind: "staff-message";
|
|
355
|
+
conversationId: string;
|
|
356
|
+
messageId: string;
|
|
334
357
|
} | {
|
|
335
358
|
kind: "receipt";
|
|
336
359
|
applied: boolean;
|
|
@@ -448,4 +471,4 @@ declare function createMessagingEngine(config: MessagingEngineConfig): {
|
|
|
448
471
|
};
|
|
449
472
|
type MessagingEngine = ReturnType<typeof createMessagingEngine>;
|
|
450
473
|
|
|
451
|
-
export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES as D, type EventOutcome as E, type InboundMessageNotice as I, type MessagingStore as M, type NewConnection as N, PROCESS_DELIVERY_JOB as P, type StoredConnection as S, type ConversationPatch as a, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p,
|
|
474
|
+
export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES as D, type EventOutcome as E, type InboundMessageNotice as I, type MessagingStore as M, type NewConnection as N, PROCESS_DELIVERY_JOB as P, type StoredConnection as S, type ConversationPatch as a, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p, type StaffReplyNotice as q, createMessagingEngine as r };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { S as StoredConnection, M as MessagingStore } from './engine-
|
|
2
|
-
export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as createMessagingEngine } from './engine-
|
|
3
|
-
import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-
|
|
4
|
-
export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as
|
|
1
|
+
import { S as StoredConnection, M as MessagingStore } from './engine-BybESJ7p.js';
|
|
2
|
+
export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as StaffReplyNotice, r as createMessagingEngine } from './engine-BybESJ7p.js';
|
|
3
|
+
import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-BWhnnuip.js';
|
|
4
|
+
export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as SentElsewhereEvent, w as StatusEvent, x as isWindowOpen, y as serviceWindowPolicy } from './channel-BWhnnuip.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* The engine's refusals, as typed errors with machine codes. The sentence a
|
package/dist/index.js
CHANGED
|
@@ -95,6 +95,62 @@ function bodyHash(rawBody) {
|
|
|
95
95
|
}
|
|
96
96
|
__name(bodyHash, "bodyHash");
|
|
97
97
|
|
|
98
|
+
// src/core/sent-elsewhere.ts
|
|
99
|
+
var later = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
|
|
100
|
+
var MAX_WRITE_ATTEMPTS = 6;
|
|
101
|
+
async function handleSentElsewhere(ctx, connection, event) {
|
|
102
|
+
const { store } = ctx.config;
|
|
103
|
+
if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
|
|
104
|
+
const body = event.content.kind === "TEXT" ? event.content.text : null;
|
|
105
|
+
const conversation = await touchConversation(ctx, connection, event, body !== null);
|
|
106
|
+
if (!conversation) return { kind: "dropped", reason: "no-conversation" };
|
|
107
|
+
const inserted = await store.insertMessage({
|
|
108
|
+
conversationId: conversation.id,
|
|
109
|
+
tenantId: connection.tenantId,
|
|
110
|
+
channel: connection.channel,
|
|
111
|
+
direction: "OUTBOUND",
|
|
112
|
+
kind: body === null ? "OTHER" : "TEXT",
|
|
113
|
+
body,
|
|
114
|
+
options: null,
|
|
115
|
+
attachmentRef: null,
|
|
116
|
+
externalId: event.externalId,
|
|
117
|
+
deliveryStatus: "SENT",
|
|
118
|
+
authorKind: "STAFF",
|
|
119
|
+
staffUserId: null,
|
|
120
|
+
createdAt: event.sentAt
|
|
121
|
+
});
|
|
122
|
+
if (!inserted.created) return { kind: "duplicate" };
|
|
123
|
+
await notifyStaffReply(ctx, conversation, inserted.message);
|
|
124
|
+
return { kind: "staff-message", conversationId: conversation.id, messageId: inserted.message.id };
|
|
125
|
+
}
|
|
126
|
+
__name(handleSentElsewhere, "handleSentElsewhere");
|
|
127
|
+
async function touchConversation(ctx, connection, event, carriesText) {
|
|
128
|
+
const { store } = ctx.config;
|
|
129
|
+
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
|
|
130
|
+
const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
|
|
131
|
+
if (!existing || existing.connectionId !== connection.id) return null;
|
|
132
|
+
const updated = await store.updateConversation(
|
|
133
|
+
connection.tenantId,
|
|
134
|
+
existing.id,
|
|
135
|
+
{ lastMessageAt: later(existing.lastMessageAt, event.sentAt), ...carriesText ? { hasText: true } : {} },
|
|
136
|
+
{ state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
|
|
137
|
+
);
|
|
138
|
+
if (updated) return updated;
|
|
139
|
+
}
|
|
140
|
+
throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);
|
|
141
|
+
}
|
|
142
|
+
__name(touchConversation, "touchConversation");
|
|
143
|
+
async function notifyStaffReply(ctx, conversation, message) {
|
|
144
|
+
const hook = ctx.config.hooks?.onStaffReply;
|
|
145
|
+
if (!hook) return;
|
|
146
|
+
try {
|
|
147
|
+
await hook({ conversation, message });
|
|
148
|
+
} catch (error) {
|
|
149
|
+
ctx.config.logger.error(`messaging.inbound: onStaffReply failed for ${conversation.id}: ${errorText(error)}`, { error });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
__name(notifyStaffReply, "notifyStaffReply");
|
|
153
|
+
|
|
98
154
|
// src/core/inbound.ts
|
|
99
155
|
async function handleEvent(ctx, channel, event) {
|
|
100
156
|
const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);
|
|
@@ -102,6 +158,7 @@ async function handleEvent(ctx, channel, event) {
|
|
|
102
158
|
if (connection.status !== "CONNECTED") return { kind: "dropped", reason: "not-connected" };
|
|
103
159
|
if (event.type === "message") return handleMessage(ctx, connection, event);
|
|
104
160
|
if (event.type === "opt_out") return handleOptOut(ctx, connection, event);
|
|
161
|
+
if (event.type === "sent_elsewhere") return handleSentElsewhere(ctx, connection, event);
|
|
105
162
|
const applied = await ctx.config.store.applyReceipt({
|
|
106
163
|
tenantId: connection.tenantId,
|
|
107
164
|
channel,
|
|
@@ -126,8 +183,8 @@ function columnsOf(content) {
|
|
|
126
183
|
}
|
|
127
184
|
}
|
|
128
185
|
__name(columnsOf, "columnsOf");
|
|
129
|
-
var
|
|
130
|
-
var
|
|
186
|
+
var later2 = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
|
|
187
|
+
var MAX_WRITE_ATTEMPTS2 = 6;
|
|
131
188
|
async function handleMessage(ctx, connection, event) {
|
|
132
189
|
const { store } = ctx.config;
|
|
133
190
|
if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
|
|
@@ -154,7 +211,7 @@ async function handleMessage(ctx, connection, event) {
|
|
|
154
211
|
__name(handleMessage, "handleMessage");
|
|
155
212
|
async function openConversation(ctx, connection, event, carriesText) {
|
|
156
213
|
const { store } = ctx.config;
|
|
157
|
-
for (let attempt = 0; attempt <
|
|
214
|
+
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS2; attempt += 1) {
|
|
158
215
|
const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
|
|
159
216
|
const result = existing ? await updateExisting(ctx, connection, existing, event, carriesText) : await createFirst(ctx, connection, event, carriesText);
|
|
160
217
|
if (result) return result;
|
|
@@ -187,10 +244,10 @@ async function updateExisting(ctx, connection, existing, event, carriesText) {
|
|
|
187
244
|
{
|
|
188
245
|
// Left out when unchanged: the write never carries a state it did not decide.
|
|
189
246
|
...state !== existing.state ? { state } : {},
|
|
190
|
-
...event.optOut ? { optedOutAt:
|
|
247
|
+
...event.optOut ? { optedOutAt: later2(existing.optedOutAt, event.sentAt) } : {},
|
|
191
248
|
...connection.id !== existing.connectionId ? { connectionId: connection.id } : {},
|
|
192
|
-
lastInboundAt:
|
|
193
|
-
lastMessageAt:
|
|
249
|
+
lastInboundAt: later2(existing.lastInboundAt, event.sentAt),
|
|
250
|
+
lastMessageAt: later2(existing.lastMessageAt, event.sentAt),
|
|
194
251
|
...event.contactName ? { contactName: event.contactName } : {},
|
|
195
252
|
...carriesText ? { hasText: true } : {}
|
|
196
253
|
},
|
|
@@ -221,7 +278,7 @@ async function notifyHost(ctx, conversation, message) {
|
|
|
221
278
|
__name(notifyHost, "notifyHost");
|
|
222
279
|
async function handleOptOut(ctx, connection, event) {
|
|
223
280
|
const { store } = ctx.config;
|
|
224
|
-
for (let attempt = 0; attempt <
|
|
281
|
+
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS2; attempt += 1) {
|
|
225
282
|
const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
|
|
226
283
|
if (!existing) {
|
|
227
284
|
const created = await store.createConversation({
|
|
@@ -244,7 +301,7 @@ async function handleOptOut(ctx, connection, event) {
|
|
|
244
301
|
existing.id,
|
|
245
302
|
{
|
|
246
303
|
...existing.state !== "OPTED_OUT" ? { state: "OPTED_OUT" } : {},
|
|
247
|
-
optedOutAt:
|
|
304
|
+
optedOutAt: later2(existing.optedOutAt, event.at)
|
|
248
305
|
},
|
|
249
306
|
{ state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
|
|
250
307
|
);
|