@im-more/dsh-whatsapp 0.0.0-stage → 0.1.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.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +12 -0
  3. package/lib/index.js +1694 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +66 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +164 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +40 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +63 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +64 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +244 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +53 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +149 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +48 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +52 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +16 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +15 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/interactive.d.ts +45 -0
  30. package/lib/types/interactive.d.ts.map +1 -0
  31. package/lib/types/interactive.js +111 -0
  32. package/lib/types/interactive.js.map +1 -0
  33. package/lib/types/internal.d.ts +28 -0
  34. package/lib/types/internal.d.ts.map +1 -0
  35. package/lib/types/internal.js +35 -0
  36. package/lib/types/internal.js.map +1 -0
  37. package/lib/types/media.d.ts +17 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +49 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/modes/shared.d.ts +112 -0
  42. package/lib/types/modes/shared.d.ts.map +1 -0
  43. package/lib/types/modes/shared.js +285 -0
  44. package/lib/types/modes/shared.js.map +1 -0
  45. package/lib/types/modes/text.d.ts +19 -0
  46. package/lib/types/modes/text.d.ts.map +1 -0
  47. package/lib/types/modes/text.js +126 -0
  48. package/lib/types/modes/text.js.map +1 -0
  49. package/lib/types/request.d.ts +61 -0
  50. package/lib/types/request.d.ts.map +1 -0
  51. package/lib/types/request.js +193 -0
  52. package/lib/types/request.js.map +1 -0
  53. package/lib/types/send.d.ts +47 -0
  54. package/lib/types/send.d.ts.map +1 -0
  55. package/lib/types/send.js +74 -0
  56. package/lib/types/send.js.map +1 -0
  57. package/lib/types/signature.d.ts +33 -0
  58. package/lib/types/signature.d.ts.map +1 -0
  59. package/lib/types/signature.js +46 -0
  60. package/lib/types/signature.js.map +1 -0
  61. package/lib/types/transport/webhook.d.ts +50 -0
  62. package/lib/types/transport/webhook.d.ts.map +1 -0
  63. package/lib/types/transport/webhook.js +197 -0
  64. package/lib/types/transport/webhook.js.map +1 -0
  65. package/lib/types/types.d.ts +198 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +2 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/package.json +61 -3
  70. package/src/bot.ts +233 -0
  71. package/src/config.ts +98 -0
  72. package/src/decode.ts +335 -0
  73. package/src/errors.ts +189 -0
  74. package/src/identity.ts +76 -0
  75. package/src/index.ts +100 -0
  76. package/src/interactive.ts +135 -0
  77. package/src/internal.ts +49 -0
  78. package/src/media.ts +59 -0
  79. package/src/modes/shared.ts +354 -0
  80. package/src/modes/text.ts +174 -0
  81. package/src/request.ts +238 -0
  82. package/src/send.ts +120 -0
  83. package/src/signature.ts +54 -0
  84. package/src/transport/webhook.ts +267 -0
  85. package/src/types.ts +244 -0
  86. package/README.md +0 -3
package/src/bot.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { Adapter, PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
2
+ import type {
3
+ MessageRef,
4
+ Mode,
5
+ PrepareContext,
6
+ ResolvedResource,
7
+ ResourceKind,
8
+ ResourceRef,
9
+ SendContext,
10
+ SentPart,
11
+ Target,
12
+ } from '@deepseek-ai/cordis-plugin-im-core'
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import { Config, configError } from './config.ts'
15
+ import { classifyWhatsappError, WhatsappApiError } from './errors.ts'
16
+ import { fetchPhoneNumber, userOf, verifyIdentity } from './identity.ts'
17
+ import { Internal } from './internal.ts'
18
+ import { serveMedia } from './media.ts'
19
+ import { SUPPORTED_MEDIA } from './modes/shared.ts'
20
+ import type { WhatsappModeTypes } from './modes/shared.ts'
21
+ import { createTextMode } from './modes/text.ts'
22
+ import { WhatsAppRequest } from './request.ts'
23
+ import { createReaction, deleteReaction, sendPayload } from './send.ts'
24
+ import type { WhatsappSendDeps } from './send.ts'
25
+ import { WhatsappWebhook } from './transport/webhook.ts'
26
+ import type { WebServerLike } from './transport/webhook.ts'
27
+ import type { SendMessage } from './types.ts'
28
+
29
+ /** The single mode this adapter always registers. */
30
+ export interface WhatsappModes {
31
+ [mode: string]: Mode<WhatsappModeTypes>
32
+ text: Mode<WhatsappModeTypes>
33
+ }
34
+
35
+ /** Message of any caught value, for a log line. */
36
+ function messageOf(error: unknown): string {
37
+ return error instanceof Error ? error.message : String(error)
38
+ }
39
+
40
+ /**
41
+ * WhatsApp Cloud API adapter for one business phone number.
42
+ *
43
+ * The number is identified by configuration (`phoneNumberId`), confirmed with `GET /{phoneNumberId}` on connect. The
44
+ * webhook is the only transport, `text` is the only mode, and every send is its own request: the platform has no
45
+ * request that publishes several messages, no edit, no delete and no stream.
46
+ *
47
+ * The 24-hour customer service window is not tracked locally. A free-form message outside it is refused by the
48
+ * platform (`131047`), which this adapter reports as an `invalid`, unpublished failure naming the template
49
+ * requirement; no template message is sent by this version.
50
+ */
51
+ export class WhatsappBot extends Adapter<Config, WhatsappModes> {
52
+ /** The adapter needs the Satori service and the isolated `http` service. */
53
+ static override inject = ['satori', 'http']
54
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
55
+ static readonly Config = Config
56
+
57
+ readonly modes: WhatsappModes
58
+ readonly modeOrder = ['text'] as const
59
+
60
+ /** The Graph client every call goes through. */
61
+ readonly request: WhatsAppRequest
62
+ /** The platform API map, exposed through `bot.internal`. */
63
+ override readonly internal: Internal
64
+
65
+ private webhook: WhatsappWebhook | undefined
66
+
67
+ constructor(ctx: Context, config: Config) {
68
+ super(ctx, config, {
69
+ id: `whatsapp:${config.phoneNumberId}`,
70
+ platform: 'whatsapp',
71
+ adapter: 'whatsapp',
72
+ })
73
+ // `bot.id` has to be fixed at construction, so the number is configured rather than discovered; `connect` proves
74
+ // the token reaches it.
75
+ this.selfId = config.phoneNumberId
76
+ this.request = new WhatsAppRequest(ctx, config)
77
+ this.internal = new Internal(this.request)
78
+ this.modes = { text: createTextMode(config) }
79
+ this.defineInternalRoute('/assets/:mediaId', async ({ params }) =>
80
+ serveMedia(this, params.mediaId),
81
+ )
82
+ }
83
+
84
+ override async connect(): Promise<void> {
85
+ const invalid = configError(this.config)
86
+ if (invalid !== undefined) {
87
+ this.ctx.logger.error('whatsapp: connect failed: %s', invalid.message)
88
+ throw invalid
89
+ }
90
+ const webServer = this.ctx.get('webServer') as WebServerLike | undefined
91
+ if (webServer === undefined) {
92
+ const error = new Error(
93
+ 'whatsapp: this adapter needs a profile-provided webServer; WhatsApp has only the webhook transport, so add a webServer row to the profile and expose its callback path over public HTTPS',
94
+ )
95
+ this.ctx.logger.error(error.message)
96
+ throw error
97
+ }
98
+ try {
99
+ const info = await fetchPhoneNumber(
100
+ this.request,
101
+ this.config.phoneNumberId,
102
+ )
103
+ this.selfId = verifyIdentity(this.config.phoneNumberId, info)
104
+ this.user = userOf(info)
105
+ const webhook = new WhatsappWebhook(this, webServer)
106
+ webhook.start()
107
+ this.webhook = webhook
108
+ this.online()
109
+ } catch (error) {
110
+ // `Bot.start` only stores a connect failure on `bot.error`, so log it here.
111
+ this.ctx.logger.error('whatsapp: connect failed: %s', messageOf(error))
112
+ throw error
113
+ }
114
+ }
115
+
116
+ override async disconnect(): Promise<void> {
117
+ const webhook = this.webhook
118
+ this.webhook = undefined
119
+ webhook?.stop()
120
+ }
121
+
122
+ /**
123
+ * Turn one outbound attachment into the media id a message carries.
124
+ *
125
+ * The Cloud API uploads the bytes first and sends the message by id afterwards, so no staging is involved. A type
126
+ * outside the platform's documented list is refused here instead of being dropped silently: the receipt has to say
127
+ * that this attachment was not sent.
128
+ */
129
+ override async upload(
130
+ ref: ResourceRef,
131
+ _scope: string,
132
+ ctx: PrepareContext,
133
+ ): Promise<ResolvedResource> {
134
+ let fetched: Awaited<ReturnType<PrepareContext['fetch']>>
135
+ try {
136
+ fetched = await ctx.fetch(ref.src, ctx.signal)
137
+ } catch (error) {
138
+ // The bytes never reached a request: a source that cannot be read is a request-level failure, published: no.
139
+ if (ctx.signal.aborted) throw error
140
+ throw new PlatformError(
141
+ 'invalid',
142
+ `whatsapp: media source ${ref.src} could not be read: ${messageOf(error)}`,
143
+ {
144
+ published: 'no',
145
+ cause: error,
146
+ },
147
+ )
148
+ }
149
+ const mime = ref.meta.mime ?? fetched.mime
150
+ const name = ref.meta.name ?? fetched.name ?? 'file'
151
+ if (mime === undefined || !SUPPORTED_MEDIA.includes(mime)) {
152
+ throw new PlatformError(
153
+ 'invalid',
154
+ `whatsapp: the platform does not accept ${mime ?? 'an unspecified media type'} ` +
155
+ `(${ref.src}); supported types are ${SUPPORTED_MEDIA.join(', ')}`,
156
+ { code: 'whatsapp-unsupported-media-type', published: 'no' },
157
+ )
158
+ }
159
+ const form = new FormData()
160
+ form.append('file', new Blob([fetched.data], { type: mime }), name)
161
+ form.append('type', mime)
162
+ form.append('messaging_product', 'whatsapp')
163
+ const answer = await this.internal.uploadMedia(this.selfId, form)
164
+ return {
165
+ key: answer.id,
166
+ extra: { name, mime, size: fetched.data.byteLength },
167
+ }
168
+ }
169
+
170
+ override resourceScope(_target: Target, _kind: ResourceKind): string {
171
+ // A media id belongs to the number and is reusable from any chat.
172
+ return this.id
173
+ }
174
+
175
+ override async sendPayload(
176
+ payload: unknown,
177
+ target: Target,
178
+ ctx: SendContext,
179
+ ): Promise<SentPart> {
180
+ return await this.call(() =>
181
+ sendPayload(this.deps(), payload as SendMessage, target, ctx),
182
+ )
183
+ }
184
+
185
+ override async createReaction(
186
+ message: MessageRef,
187
+ emoji: string,
188
+ ): Promise<void> {
189
+ await this.call(() => createReaction(this.deps(), message, emoji))
190
+ }
191
+
192
+ override async deleteReaction(
193
+ message: MessageRef,
194
+ emoji: string,
195
+ ): Promise<void> {
196
+ await this.call(() => deleteReaction(this.deps(), message, emoji))
197
+ }
198
+
199
+ override classify(error: unknown) {
200
+ return classifyWhatsappError(error)
201
+ }
202
+
203
+ private deps(): WhatsappSendDeps {
204
+ return { selfId: this.selfId, internal: this.internal }
205
+ }
206
+
207
+ /**
208
+ * Run one outbound call, naming a revoked token in the log.
209
+ *
210
+ * A token rejected at runtime (`190`) leaves the webhook working while every send fails, and nothing else surfaces
211
+ * that state: the request itself only reaches the caller of this send.
212
+ *
213
+ * @param operation - the outbound call.
214
+ * @returns what the call answered.
215
+ */
216
+ private async call<T>(operation: () => Promise<T>): Promise<T> {
217
+ try {
218
+ return await operation()
219
+ } catch (error) {
220
+ if (error instanceof WhatsappApiError && error.code === 190) {
221
+ this.ctx.logger.error(
222
+ 'whatsapp: the system user token was rejected; webhook intake continues but every send fails: %s',
223
+ error.message,
224
+ )
225
+ }
226
+ throw error
227
+ }
228
+ }
229
+ }
230
+
231
+ export { Config }
232
+
233
+ export default WhatsappBot
package/src/config.ts ADDED
@@ -0,0 +1,98 @@
1
+ import z from '@deepseek-ai/schemastery'
2
+
3
+ /** One WhatsApp Cloud API phone number. */
4
+ export interface Config {
5
+ /** Graph id of the phone number (`metadata.phone_number_id` of every webhook, and the `{phoneNumberId}` of every call). */
6
+ phoneNumberId: string
7
+ /** System user token: the `Authorization: Bearer` value of every Graph call. */
8
+ systemToken: string
9
+ /** The `hub.verify_token` the subscription handshake must present; chosen by hand in the Meta app panel. */
10
+ verifyToken: string
11
+ /** App Secret: the HMAC key of `X-Hub-Signature-256`; no API call uses it. */
12
+ secret: string
13
+ /** Graph API root; pin a version by writing `https://graph.facebook.com/v21.0`. */
14
+ apiBaseUrl: string
15
+ webhook: {
16
+ /** Inbound webhook path: absolute, no trailing slash. */
17
+ path: string
18
+ }
19
+ /** Whether a text message asks the client to render a link preview (`text.preview_url`). */
20
+ linkPreview: boolean
21
+ }
22
+
23
+ /** Validated WhatsApp adapter configuration. */
24
+ export const Config: z<Config> = z.object({
25
+ phoneNumberId: z.string().required(),
26
+ systemToken: z.string().role('secret').required(),
27
+ verifyToken: z.string().role('secret').required(),
28
+ secret: z.string().role('secret').required(),
29
+ apiBaseUrl: z.string().role('url').default('https://graph.facebook.com'),
30
+ webhook: z
31
+ .object({
32
+ path: z.string().default('/whatsapp'),
33
+ })
34
+ .default({}),
35
+ linkPreview: z.boolean().default(true),
36
+ })
37
+
38
+ /**
39
+ * Normalize a route path: absolute, no trailing slash.
40
+ *
41
+ * @param path - a configured path.
42
+ * @returns the pathname to register on the web server.
43
+ */
44
+ export function routePath(path: string): string {
45
+ const withSlash = path.startsWith('/') ? path : `/${path}`
46
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') : withSlash
47
+ }
48
+
49
+ /**
50
+ * The configuration the adapter cannot work from, as far as it can tell locally.
51
+ *
52
+ * WhatsApp has only the webhook transport, so a profile without a usable callback path receives nothing; the check
53
+ * runs when the bot starts, not on the first delivery.
54
+ *
55
+ * @param config - the validated configuration.
56
+ * @returns the configuration error, or undefined when the configuration is usable.
57
+ */
58
+ export function configError(config: Config): Error | undefined {
59
+ if (config.phoneNumberId === '') {
60
+ return new Error(
61
+ 'whatsapp: phoneNumberId is required (the Graph id of the phone number, from the Meta app WhatsApp API setup)',
62
+ )
63
+ }
64
+ if (config.systemToken === '') {
65
+ return new Error(
66
+ 'whatsapp: systemToken is required (the system user token that authenticates every Graph call)',
67
+ )
68
+ }
69
+ if (config.verifyToken === '') {
70
+ return new Error(
71
+ 'whatsapp: verifyToken is required (the subscription handshake compares it with hub.verify_token)',
72
+ )
73
+ }
74
+ if (config.secret === '') {
75
+ return new Error(
76
+ 'whatsapp: secret is required (the App Secret; it verifies X-Hub-Signature-256 of every delivery)',
77
+ )
78
+ }
79
+ if (config.apiBaseUrl === '') {
80
+ return new Error(
81
+ 'whatsapp: apiBaseUrl is required (the Graph API root, https://graph.facebook.com by default)',
82
+ )
83
+ }
84
+ let origin: URL
85
+ try {
86
+ origin = new URL(config.apiBaseUrl)
87
+ } catch {
88
+ return new Error(
89
+ `whatsapp: apiBaseUrl must be an absolute URL, got "${config.apiBaseUrl}"`,
90
+ )
91
+ }
92
+ if (origin.protocol !== 'https:') {
93
+ return new Error(
94
+ `whatsapp: apiBaseUrl must be an https URL, got "${config.apiBaseUrl}" (every Graph call carries a bearer token)`,
95
+ )
96
+ }
97
+ return undefined
98
+ }
package/src/decode.ts ADDED
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Inbound decoding: one change of a webhook delivery becomes zero or more intake `Session`s.
3
+ *
4
+ * The Cloud API pushes everything at once — several entries, each with several changes, each with several messages —
5
+ * and there is no API that reads a message back, so this payload is the only copy of the content. Every message is
6
+ * decoded; a chat is always the sender's own `wa_id`, because this adapter supports no group.
7
+ */
8
+
9
+ import type {
10
+ ChatRef,
11
+ InboundMessage,
12
+ Session,
13
+ UserRef,
14
+ } from '@deepseek-ai/cordis-plugin-im-core'
15
+ import { h, normalize } from '@deepseek-ai/satori-element'
16
+ import type { Child } from '@deepseek-ai/satori-element'
17
+ import type { WhatsappBot } from './bot.ts'
18
+ import {
19
+ decodeInteractive,
20
+ decodeReaction,
21
+ decodeTemplateButton,
22
+ } from './interactive.ts'
23
+ import type {
24
+ Change,
25
+ MessageBody,
26
+ MessageBodyBase,
27
+ MessageBodyMedia,
28
+ ReceivedMedia,
29
+ StatusBody,
30
+ } from './types.ts'
31
+
32
+ /** Adapter-private context carried through `Target.referrer`. */
33
+ export interface WhatsappReferrer {
34
+ /** The peer's `wa_id`: the `chat.id` and the `to` of every send. */
35
+ waId: string
36
+ /** The `wamid` of the inbound message. */
37
+ messageId: string
38
+ /** The business number's Graph id; the `{phoneNumberId}` of every send. */
39
+ phoneNumberId: string
40
+ timestamp: number
41
+ }
42
+
43
+ /** What an interaction or reaction session needs from the payload it came from. */
44
+ export interface WhatsappContext {
45
+ chat: ChatRef
46
+ user: UserRef
47
+ referrer: WhatsappReferrer
48
+ timestamp: number
49
+ }
50
+
51
+ /** Message of any caught value, for a log line. */
52
+ function messageOf(error: unknown): string {
53
+ return error instanceof Error ? error.message : String(error)
54
+ }
55
+
56
+ /** The direct chat of one sender; a Cloud API conversation has exactly one peer. */
57
+ export function chatRefOf(message: MessageBodyBase): ChatRef {
58
+ return { id: message.from, type: 'direct' }
59
+ }
60
+
61
+ /**
62
+ * The sender of one message.
63
+ *
64
+ * The payload names the sender's display name in `contacts`, keyed by `wa_id` — a batch can carry several senders, so
65
+ * the entry is matched instead of taken from the first position.
66
+ * @param message - the message being decoded.
67
+ * @param contacts - the `contacts` array of the same change.
68
+ * @returns the sender reference, named when the payload names it.
69
+ */
70
+ export function senderOf(
71
+ message: MessageBodyBase,
72
+ contacts: Change['value']['contacts'],
73
+ ): UserRef {
74
+ const name = contacts?.find((contact) => contact.wa_id === message.from)
75
+ ?.profile.name
76
+ return {
77
+ id: message.from,
78
+ ...(name === undefined ? {} : { name }),
79
+ isBot: false,
80
+ }
81
+ }
82
+
83
+ /** The platform timestamp of a message: Meta sends seconds as a string. */
84
+ export function timeOf(message: MessageBodyBase): number {
85
+ const seconds = Number.parseInt(message.timestamp, 10)
86
+ return Number.isFinite(seconds) ? seconds * 1_000 : Date.now()
87
+ }
88
+
89
+ /** The adapter context an interaction or reaction session is built from. */
90
+ export function contextOf(
91
+ bot: WhatsappBot,
92
+ message: MessageBodyBase,
93
+ contacts: Change['value']['contacts'],
94
+ ): WhatsappContext {
95
+ return {
96
+ chat: chatRefOf(message),
97
+ user: senderOf(message, contacts),
98
+ referrer: {
99
+ waId: message.from,
100
+ messageId: message.id,
101
+ phoneNumberId: bot.config.phoneNumberId,
102
+ timestamp: timeOf(message),
103
+ },
104
+ timestamp: timeOf(message),
105
+ }
106
+ }
107
+
108
+ /** The `satori:` address of one received media object. */
109
+ function mediaSource(bot: WhatsappBot, media: ReceivedMedia): string {
110
+ return bot.getInternalUrl(`/assets/${encodeURIComponent(media.id)}`)
111
+ }
112
+
113
+ /** The caption that precedes a media element, when the sender typed one. */
114
+ function captionOf(media: ReceivedMedia): Child[] {
115
+ return media.caption === undefined || media.caption === ''
116
+ ? []
117
+ : [media.caption]
118
+ }
119
+
120
+ /** The elements of one media message: its caption, then the media itself. */
121
+ function mediaNodes(bot: WhatsappBot, message: MessageBodyMedia): Child[] {
122
+ const media = message[message.type]
123
+ if (media === undefined) return []
124
+ const src = mediaSource(bot, media)
125
+ const name = media.filename === undefined ? {} : { name: media.filename }
126
+ switch (message.type) {
127
+ case 'image':
128
+ return [...captionOf(media), h('img', { src })]
129
+ case 'audio':
130
+ // A voice note is an audio message recorded in the app; the vocabulary has no separate element for it.
131
+ return [...captionOf(media), h('audio', { src, ...name })]
132
+ case 'video':
133
+ return [...captionOf(media), h('video', { src, ...name })]
134
+ case 'document':
135
+ return [...captionOf(media), h('file', { src, ...name })]
136
+ }
137
+ }
138
+
139
+ /**
140
+ * The elements of one message of a type that carries content.
141
+ *
142
+ * @param bot - the receiving adapter.
143
+ * @param message - the decoded message.
144
+ * @returns its elements, possibly empty for a shape this snapshot does not carry.
145
+ */
146
+ function contentNodes(bot: WhatsappBot, message: MessageBody): Child[] {
147
+ switch (message.type) {
148
+ case 'text':
149
+ return message.text.body === '' ? [] : [message.text.body]
150
+ case 'image':
151
+ case 'audio':
152
+ case 'video':
153
+ case 'document':
154
+ return mediaNodes(bot, message)
155
+ case 'sticker':
156
+ return message.sticker === undefined
157
+ ? []
158
+ : [h('img', { src: mediaSource(bot, message.sticker), alt: '[贴纸]' })]
159
+ case 'location':
160
+ // The vocabulary has no location element; the coordinates are what a reader needs from one.
161
+ return [`📍 ${message.location.latitude}, ${message.location.longitude}`]
162
+ case 'contacts': {
163
+ const names = message.contacts.map(
164
+ (contact) => contact.name.formatted_name,
165
+ )
166
+ const summary =
167
+ names.length === 0 ? '联系人' : `联系人:${names.join('、')}`
168
+ return [
169
+ summary,
170
+ h('raw', {
171
+ platform: 'whatsapp',
172
+ type: 'contacts',
173
+ data: message.contacts,
174
+ }),
175
+ ]
176
+ }
177
+ case 'system':
178
+ return message.system.body === '' ? [] : [message.system.body]
179
+ default:
180
+ return []
181
+ }
182
+ }
183
+
184
+ /**
185
+ * The content tree of one message, never empty.
186
+ * @param bot - the receiving adapter.
187
+ * @param message - the decoded message.
188
+ * @returns the normalized `<message>` root.
189
+ */
190
+ function contentOf(
191
+ bot: WhatsappBot,
192
+ message: MessageBody,
193
+ ): InboundMessage['content'] {
194
+ const nodes = contentNodes(bot, message)
195
+ if (nodes.length > 0) return normalize(h('message', nodes))
196
+ // A type this snapshot does not model still reaches the model as its payload rather than disappearing.
197
+ return normalize(
198
+ h(
199
+ 'message',
200
+ h('raw', { platform: 'whatsapp', type: message.type, data: message }),
201
+ ),
202
+ )
203
+ }
204
+
205
+ /** The quote an inbound message answers, when the payload names one. */
206
+ function quoteOf(message: MessageBodyBase): InboundMessage['quote'] {
207
+ if (message.context === undefined) return undefined
208
+ return { id: message.context.id, sender: { id: message.context.from } }
209
+ }
210
+
211
+ /**
212
+ * Decode one ordinary message into a `message` session.
213
+ *
214
+ * @param bot - the receiving adapter.
215
+ * @param message - the decoded message.
216
+ * @param contacts - the `contacts` array of the same change.
217
+ * @returns the session to publish.
218
+ */
219
+ function messageSession(
220
+ bot: WhatsappBot,
221
+ message: MessageBody,
222
+ contacts: Change['value']['contacts'],
223
+ ): Session {
224
+ const context = contextOf(bot, message, contacts)
225
+ const quote = quoteOf(message)
226
+ const inbound: InboundMessage = {
227
+ id: message.id,
228
+ chat: context.chat,
229
+ sender: context.user,
230
+ content: contentOf(bot, message),
231
+ ...(quote === undefined ? {} : { quote }),
232
+ // A 1:1 WhatsApp conversation has no mention syntax and the platform names no mentioned user.
233
+ mentions: { self: false, all: false, users: [] },
234
+ time: context.timestamp,
235
+ referrer: context.referrer,
236
+ raw: message,
237
+ }
238
+ return bot.session({
239
+ type: 'message',
240
+ id: message.id,
241
+ timestamp: context.timestamp,
242
+ message: inbound,
243
+ raw: message,
244
+ })
245
+ }
246
+
247
+ /** Log one delivery receipt; the platform's own view of an outbound message has no DSH event. */
248
+ function logStatus(bot: WhatsappBot, status: StatusBody): void {
249
+ if (status.status !== 'failed') {
250
+ bot.ctx.logger.debug('whatsapp: message %s is %s', status.id, status.status)
251
+ return
252
+ }
253
+ // A failed delivery is where a closed 24-hour window, a rejected template and a refused recipient first appear.
254
+ const errors = status.errors ?? []
255
+ bot.ctx.logger.warn(
256
+ 'whatsapp: delivery of %s to %s failed: %s',
257
+ status.id,
258
+ status.recipient_id,
259
+ errors.length === 0
260
+ ? 'no error detail'
261
+ : errors
262
+ .map((error) =>
263
+ [String(error.code), error.title, error.error_data?.details]
264
+ .filter(
265
+ (part): part is string => part !== undefined && part !== '',
266
+ )
267
+ .join(' '),
268
+ )
269
+ .join('; '),
270
+ )
271
+ }
272
+
273
+ /**
274
+ * Decode every message of one change.
275
+ *
276
+ * A non-`messages` change family is dropped with a debug line: the IM host has no consumer for account, template or
277
+ * quality updates. Delivery receipts never reach the message store.
278
+ *
279
+ * @param bot - the receiving adapter.
280
+ * @param change - one change of one entry.
281
+ * @returns the sessions to publish, in payload order.
282
+ */
283
+ export function decodeChange(bot: WhatsappBot, change: Change): Session[] {
284
+ if (change.field !== 'messages') {
285
+ bot.ctx.logger.debug('whatsapp: ignoring a %s change', change.field)
286
+ return []
287
+ }
288
+ for (const status of change.value.statuses ?? []) logStatus(bot, status)
289
+ for (const error of change.value.errors ?? []) {
290
+ bot.ctx.logger.warn(
291
+ 'whatsapp: the webhook reported an error: %s',
292
+ messageOf(error),
293
+ )
294
+ }
295
+ const sessions: Session[] = []
296
+ for (const message of change.value.messages ?? []) {
297
+ const session = decodeMessage(bot, message, change.value.contacts)
298
+ if (session !== undefined) sessions.push(session)
299
+ }
300
+ return sessions
301
+ }
302
+
303
+ /**
304
+ * Decode one message of the payload.
305
+ *
306
+ * @param bot - the receiving adapter.
307
+ * @param message - one `messages` entry.
308
+ * @param contacts - the `contacts` array of the same change.
309
+ * @returns the session to publish, or undefined for a message this adapter drops.
310
+ */
311
+ export function decodeMessage(
312
+ bot: WhatsappBot,
313
+ message: MessageBody,
314
+ contacts: Change['value']['contacts'],
315
+ ): Session | undefined {
316
+ if (message.group_id !== undefined) {
317
+ // A group message names the member who wrote it, not the conversation; treating it as a direct chat would make
318
+ // the bot answer that member privately. v1 supports no group, so the message is dropped without a trace.
319
+ return undefined
320
+ }
321
+ switch (message.type) {
322
+ case 'reaction':
323
+ return decodeReaction(bot, message, contextOf(bot, message, contacts))
324
+ case 'interactive':
325
+ return decodeInteractive(bot, message, contextOf(bot, message, contacts))
326
+ case 'button':
327
+ return decodeTemplateButton(
328
+ bot,
329
+ message,
330
+ contextOf(bot, message, contacts),
331
+ )
332
+ default:
333
+ return messageSession(bot, message, contacts)
334
+ }
335
+ }