@theokit/gateway 0.12.0 → 0.15.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/CHANGELOG.md CHANGED
@@ -1,5 +1,213 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 00af16f: `BasePlatformAdapter` gains `react(channelId, messageId, emoji)`, which adds an emoji reaction to an inbound message. The default resolves `react_unsupported`; the Discord, Slack, Telegram and Matrix adapters implement it.
8
+ - db894a4: Make `raft` a first-party platform.
9
+
10
+ `@theokit/gateway` gains the `raft` key in `PlatformEventRegistry`, the `RaftMessageEvent` type
11
+ and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member. Code
12
+ that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default must
13
+ add it.
14
+
15
+ - 3efe7e7: Make `wechat` a first-party platform.
16
+
17
+ `@theokit/gateway` gains the `wechat` key in `PlatformEventRegistry`, the `WeChatMessageEvent` type
18
+ and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member. Code
19
+ that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default must
20
+ add it.
21
+
22
+ - 5980e00: Make `wecom` a first-party platform.
23
+
24
+ `@theokit/gateway` gains the `wecom` key in `PlatformEventRegistry`, the `WeComMessageEvent` type
25
+ and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member. Code
26
+ that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default must
27
+ add it.
28
+
29
+ - d7ed3ab: Make `yuanbao` a first-party platform.
30
+
31
+ `@theokit/gateway` gains the `yuanbao` key in `PlatformEventRegistry`, the `YuanbaoMessageEvent`
32
+ type and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member.
33
+ Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never`
34
+ default must add it.
35
+
36
+ - 6555723: Make `zalo` a first-party platform.
37
+
38
+ `@theokit/gateway` gains the `zalo` key in `PlatformEventRegistry`, the `ZaloMessageEvent` type and
39
+ a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member. Code that
40
+ lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default must add
41
+ it.
42
+
43
+ - 00733b8: `@theokit/gateway` exports `WeixinAdapterBase` and `parseFlatXml`: the token, send and dispatch flow and the XML reader that the WeChat and WeCom adapters used to carry a copy each. The WeChat and WeCom adapters now extend the base.
44
+
45
+ ### Patch Changes
46
+
47
+ - bac158b: Keep the outbound checks and the inbound handler wiring in `BasePlatformAdapter`.
48
+
49
+ `BasePlatformAdapter` gains protected `refuseUnsendable`, `outboundText`, `subscribe`, `deliverInbound`
50
+ and `dispatchOnce`, so the `empty_text`, `not_connected` and `invalid_channel` checks, the
51
+ markdown translation, the handler slot and the dedup-then-dispatch step exist once instead of in
52
+ the adapters. Every adapter answers the same codes and messages as before.
53
+
54
+ ## 0.14.0
55
+
56
+ ### Minor Changes
57
+
58
+ - 458c34c: Wire channels from descriptors, and keep the channels that connect when another cannot.
59
+
60
+ `@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
61
+ `ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
62
+ `ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
63
+ entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
64
+ `""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
65
+ keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
66
+ other error propagates. It connects nothing and makes no network call.
67
+
68
+ `GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
69
+ and `StartResult` is exported.
70
+ The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
71
+ connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
72
+ only for the ones that connected, and reports the rest with a redacted reason.
73
+
74
+ `start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
75
+ values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
76
+ but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
77
+ fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
78
+
79
+ `@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
80
+ required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
81
+ `GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
82
+ `telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
83
+ that is not an array of strings; through `createChannels`, an absent or empty token is rejected
84
+ first, as `missing_required_config`.
85
+
86
+ `@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
87
+ `x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
88
+ payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
89
+ `"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
90
+ payload holds a text message for the handler and none is subscribed: before the runner started,
91
+ after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
92
+ `"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
93
+ `lineChannel.create` checks field types before the adapter's constructor.
94
+
95
+ `LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
96
+ `"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
97
+ that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
98
+ answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
99
+ one event still receives the rest of the batch. Code that ignores the value is unaffected; a
100
+ subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
101
+ unchanged and still answers 200 before it dispatches.
102
+
103
+ Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
104
+ range stays `>=0.9.0 <1.0.0`.
105
+
106
+ - e009dc3: Pair each platform with the rendering `ChatPresenter` needs.
107
+
108
+ `@theokit/gateway` exports `channelRendering(platform)` and the type `ChannelRendering`, a
109
+ `{ translate, format }` pair to spread into `@theokit/presenter`'s `ChatPresenter` options.
110
+ whatsapp and slack get single-character emphasis (`*bold*`, `_italic_`, `~strike~`), discord,
111
+ mattermost and teams keep markdown, and telegram, matrix, email, line and sms get the four inline
112
+ markers removed with `format: "plain"`. Before this, the presenter's defaults put `**bold**` on
113
+ the wire as characters on matrix and email, and handed telegram and slack a bold spelled for
114
+ another dialect.
115
+
116
+ Only bold, italic, strikethrough and inline code are translated. Headings, links, lists and block
117
+ quotes pass through, and fenced code blocks are not handled yet: the inline-code rule rewrites
118
+ their backticks. A platform the table does not know throws a `RangeError`. `toDialect` is
119
+ unchanged, and `@theokit/gateway` still does not depend on `@theokit/presenter`.
120
+
121
+ - 67e0b78: Make `nostr`, `feishu_lark`, `synology_chat`, `tlon_urbit` and `twitch` first-party platforms.
122
+
123
+ `@theokit/gateway` gains the five keys in `PlatformEventRegistry`, the `NostrMessageEvent`,
124
+ `FeishuLarkMessageEvent`, `SynologyChatMessageEvent`, `TlonUrbitMessageEvent` and
125
+ `TwitchMessageEvent` types, and a `channelRendering` row for each (`plain`, markers removed).
126
+ `PlatformName` grows by five members. Code that lists every platform in a
127
+ `Record<PlatformName, …>` or in a switch with a `never` default must add the five, and a package
128
+ that registered one of these keys through module augmentation now collides with the first-party
129
+ one (TS2717) and should drop it. The ten event types added since 0.11.0 are now declared in one
130
+ module beside the registry; every name is still exported from the package entry as before.
131
+
132
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
133
+
134
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
135
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
136
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
137
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
138
+ field. The runner and the router refuse an outbound carrying attachments as
139
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
140
+ `supportsAttachments`.
141
+
142
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
143
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
144
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
145
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
146
+
147
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
148
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
149
+ dropping the image.
150
+
151
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
152
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
153
+ as a handler error is. Dispatch still does not throw.
154
+
155
+ - 782e448: Carry voice in both directions. The inbound event gains an optional `audio` field, an
156
+ `InboundAudio` with the voice note's bytes, media type and duration in seconds, and
157
+ `OutboundAttachment` gains an `audio` member beside `image`. The Telegram adapter reads a polled
158
+ voice note through `getFile` and a download bounded at 20 MiB and 30 seconds, delivering the
159
+ message without `audio` and one stderr line when it cannot, and sends an audio attachment through
160
+ `sendVoice` with the reply text as its caption. Every other adapter refuses audio as it refuses an
161
+ image. Code that switches exhaustively on `OutboundAttachment["kind"]` gains a case.
162
+ - 48b1b04: Make `buzz` a first-party platform.
163
+
164
+ `@theokit/gateway` gains the `buzz` key in `PlatformEventRegistry`, the `BuzzMessageEvent`
165
+ type and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member.
166
+ Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default
167
+ must add it.
168
+
169
+ - 1b27d5d: Make `clickclack` a first-party platform.
170
+
171
+ `@theokit/gateway` gains the `clickclack` key in `PlatformEventRegistry`, the `ClickClackMessageEvent`
172
+ type and a `channelRendering` row (`plain`, markers removed). `PlatformName` grows by one member.
173
+ Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a `never` default
174
+ must add it.
175
+
176
+ - baadf93: Make `zalo_personal` a first-party platform.
177
+
178
+ `@theokit/gateway` gains the `zalo_personal` key in `PlatformEventRegistry`, the
179
+ `ZaloPersonalMessageEvent` type and a `channelRendering` row (`plain`, markers removed).
180
+ `PlatformName` grows by one member. Code that lists every platform in a `Record<PlatformName, …>`
181
+ or in a switch with a `never` default must add it.
182
+
183
+ - e980fb8: `@theokit/gateway` exports `SeenIds` (a bounded set of delivered ids) and `splitKeepingRows` (a
184
+ grapheme-safe split that keeps Markdown table rows whole). The SMS and LINE adapters import
185
+ `splitKeepingRows` instead of carrying copies; their peer floor is now `>=0.13.0`.
186
+ - 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
187
+
188
+ ### Patch Changes
189
+
190
+ - e9be726: Keep Markdown table rows intact through translation and splitting.
191
+
192
+ `channelRendering(platform).translate` and `toDialect` now rewrite a table row (a line whose first
193
+ non-blank character is `|`) one cell at a time. Before, an emphasis span could open in one cell
194
+ and close in the next, so `| 2 x *a | b* y |` lost both stars on the ten platforms that rewrite
195
+ markers. Text where no span crosses a row's pipe translates exactly as before. A lone `\r` counts
196
+ as a line ending, as in GFM. Inline code that holds an unescaped pipe inside a row is split at
197
+ that pipe, as GFM splits the cell, so its backticks no longer pair and the platforms that strip
198
+ markers now keep them.
199
+
200
+ `splitForLine` and `splitForSMS` no longer cut a table row in two at a part
201
+ boundary. When a cut would fall inside a row that fits in one part, the part ends before that row
202
+ and the row starts the next part. A row longer than a part is still cut by length. Every
203
+ character is kept, and every part stays within its limit (with the `(i/N) ` prefix counted on
204
+ SMS, whose numbering follows the new part count) except a single grapheme longer than the limit,
205
+ which is emitted whole as its own part, as before. Text with no table row splits exactly as
206
+ before. Two rows that each fill a part exactly arrive as three parts, the second holding only the
207
+ line ending between them.
208
+
209
+ No export, signature, dependency or peer range changes.
210
+
3
211
  ## 0.12.0
4
212
 
5
213
  ### Minor Changes
package/README.md CHANGED
@@ -16,8 +16,8 @@ pnpm add @theokit/gateway-discord discord.js
16
16
 
17
17
  ## How each adapter treats `OutboundMessage.format`
18
18
 
19
- **All ten honour it** — they read the field and let it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
20
- to read ten packages to learn which — so the classes are stated here.
19
+ **Every adapter honours it** — each reads the field and lets it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
20
+ to read every package to learn which — so the classes are stated here.
21
21
 
22
22
  | Platform | What it does with `format` |
23
23
  |---|---|
@@ -73,8 +73,8 @@ presenter per turn; it keeps state between `present()` calls.
73
73
  |---|---|---|
74
74
  | whatsapp | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` to ` ```c``` ` | `plain` |
75
75
  | slack | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` kept | `markdown` |
76
- | discord, mattermost, teams | unchanged | `markdown` |
77
- | telegram, matrix, email, line, sms | the markers removed, their content kept | `plain` |
76
+ | discord, mattermost, teams, signal, nextcloud_talk | unchanged | `markdown` |
77
+ | telegram, matrix, email, line, sms, imessage, google_chat, irc, nostr, feishu_lark, synology_chat, tlon_urbit, twitch | the markers removed, their content kept | `plain` |
78
78
 
79
79
  - Only the four inline markers are translated: bold, italic, strikethrough and inline code.
80
80
  Headings, links, lists and block quotes reach every platform unchanged.
@@ -93,6 +93,80 @@ presenter per turn; it keeps state between `present()` calls.
93
93
  - `@theokit/presenter` is your dependency, not this package's: `@theokit/gateway` does not depend
94
94
  on it.
95
95
 
96
+ ## Sending an image
97
+
98
+ `ctx.reply` takes an optional `attachments` list of images, each an `OutboundAttachment`: its
99
+ bytes (`data`, a `Uint8Array`), their `mediaType`, and an optional `filename`. The runner carries
100
+ the list to the adapter's `sendMessage` as `OutboundMessage.attachments`, by reference, and leaves
101
+ an empty list out. `post_outbound` hooks see the same outbound, image bytes included. Do not change
102
+ the bytes or the list until the reply's promise settles: Telegram reads each image only when its
103
+ turn comes. `DeliveryRouter.send` takes the same `attachments` field for a scheduled delivery.
104
+
105
+ Only Telegram sends images today. Code that holds the adapter reads `supportsAttachments` before
106
+ attaching: every other adapter reports `false` and refuses an outbound carrying attachments with
107
+ `attachments_unsupported`, making no platform call, so an image is never dropped in silence. An
108
+ edit carrying attachments is refused the same way on every adapter, Telegram included.
109
+ `BasePlatformAdapter`, `OutboundAttachment` and `SendResult` come from `@theokit/gateway`.
110
+
111
+ ```typescript
112
+ async function sendChart(
113
+ adapter: BasePlatformAdapter,
114
+ channel: OutboundMessage["channel"],
115
+ chart: OutboundAttachment,
116
+ ): Promise<SendResult> {
117
+ // No image send on this platform: say so in text instead.
118
+ if (!adapter.supportsAttachments) {
119
+ const text = "The chart is ready, but this chat cannot show images.";
120
+ return adapter.sendMessage({ channel, text });
121
+ }
122
+ return adapter.sendMessage({ channel, text: "Here is the chart.", attachments: [chart] });
123
+ }
124
+ ```
125
+
126
+ The runner and the router answer `attachments_unsupported` themselves, with no `sendMessage` call,
127
+ when the adapter does not declare `supportsAttachments`, so an adapter that ignores the field
128
+ cannot drop the image and report success. A handler, which receives no adapter, branches on that
129
+ code:
130
+
131
+ ```typescript
132
+ const sent = await ctx.reply("Here is the chart.", { attachments: [chart] });
133
+ if (sent.error?.code === "attachments_unsupported") {
134
+ await ctx.reply("The chart is ready, but this chat cannot show images.");
135
+ }
136
+ ```
137
+
138
+ | Code | When |
139
+ |---|---|
140
+ | `attachments_unsupported` | the adapter cannot send attachments, the outbound is an edit, or (Telegram) an attachment's `kind` is neither `image` nor `audio` |
141
+ | `invalid_attachment` | Telegram only: `attachments` is not a list, holds more than 10 attachments, an entry has no bytes, an image is over 10 MiB, or an audio clip is over 50 MiB or its `mediaType` is not `audio/*` |
142
+
143
+ ## Voice notes and spoken replies
144
+
145
+ An inbound event may carry `audio`, an `InboundAudio`: the voice note's bytes (`data`, a
146
+ `Uint8Array`), their `mediaType` (such as `audio/ogg`) and `durationSeconds`, a whole number the
147
+ platform reported (0 when it reported none). The field is optional and absent on every message
148
+ without a voice note. Only the Telegram adapter fills it today, and only for updates it polls: a
149
+ voice arriving through a webhook is not read. A voice the adapter could not read leaves `audio`
150
+ absent and writes one stderr line naming the reason, so an empty `text` with no `audio` can mean
151
+ either; the message is delivered in both cases. The bytes reach `post_inbound` hooks by reference.
152
+
153
+ To answer with speech, attach an audio clip: `{ kind: "audio", mediaType: "audio/ogg", data }`.
154
+ `OutboundAttachment` is a union of the image and the audio member, told apart by `kind`; code
155
+ that switches on `kind` exhaustively gains a case. Every adapter but Telegram refuses an audio
156
+ attachment as it refuses an image, with `attachments_unsupported` and no platform call.
157
+
158
+ ```typescript
159
+ const runner = new GatewayRunner({
160
+ adapters: [adapter],
161
+ handler: async (event, ctx) => {
162
+ if (event.audio === undefined) return;
163
+ const text = await transcribe(event.audio.data, event.audio.mediaType);
164
+ const speech = await synthesize(await answer(text));
165
+ await ctx.reply(text, { attachments: [{ kind: "audio", mediaType: "audio/ogg", data: speech }] });
166
+ },
167
+ });
168
+ ```
169
+
96
170
  ## Editing a sent message
97
171
 
98
172
  Six adapters can replace the text of a message they sent, keeping its id: Telegram, Discord,
@@ -227,6 +301,13 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
227
301
  `GatewayConfigurationError` coded `missing_required_config` that names the keys, and reports a
228
302
  configuration error thrown by `create` the same way. Any other error propagates. It performs no
229
303
  network call.
304
+ - `createChannels` also returns `channels`: each built adapter paired with the descriptor that built it, in the order of `adapters`.
305
+ - `reconnect: { initialDelayMs, maxDelayMs, factor, maxAttempts }` retries an adapter whose
306
+ `connect()` threw a transient error (refused connection, DNS, 5xx) with exponential backoff and a
307
+ stderr line per attempt. It is off unless set, and takes effect only with
308
+ `connectFailure: "isolate"` (under `"rollback"` the start still rejects). A `connect()` that
309
+ returns `false`, or throws a 401/403 credential error, is reported once and never retried.
310
+ `start()` called again afterwards returns the updated `connected` and `failed`.
230
311
  - `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
231
312
  connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
232
313
  adapter failed, so check `connected` before you rely on the runner.
@@ -241,8 +322,9 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
241
322
  runner you build from adapters you constructed yourself is not checked, so give it one adapter
242
323
  per platform: with two of one platform the later one sends the earlier one's replies, and the
243
324
  earlier one is connected but never disconnected.
244
- - Under `"isolate"`, and under `"rollback"` until the first failure, `start()` waits for every
245
- connect, so a connect that never settles blocks it.
325
+ - `start()` waits for every connect under both `connectFailure` modes, so a connect that never
326
+ settles blocks it. Under `"rollback"` that holds after a failure too: a failing start rejects
327
+ only once its slowest connect settles.
246
328
  - A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
247
329
  `webhook.verify(adapter, { rawBody, headers })`, then parse the body and pass it to
248
330
  `webhook.ingest(adapter, payload)`, which answers `"delivered"`, `"malformed"` or
@@ -288,19 +370,32 @@ here). Both halves exist now, and the wiring needs three things that are easy to
288
370
  import { handleChannelWebhook } from "theokit/server/agent";
289
371
  import { route } from "theokit/server/define";
290
372
  import { whatsapp, whatsappSubscribe } from "theokit/server/webhook";
291
- import { normalizeInboundMessages, parseWebhookPayload } from "@theokit/gateway-whatsapp";
373
+ import { parseWebhookPayload, WhatsAppAdapter } from "@theokit/gateway-whatsapp";
374
+
375
+ // The adapter applies the sender allowlist and the group rule, and drops a message addressed to
376
+ // another phone number of the same Meta app. `normalizeInboundMessages` alone applies none of them.
377
+ const adapter = WhatsAppAdapter.fromCloud(
378
+ {
379
+ accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
380
+ phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
381
+ appSecret: process.env.META_APP_SECRET!,
382
+ },
383
+ { allowedSenders: process.env.WHATSAPP_ALLOWED },
384
+ );
385
+
386
+ async function onMessage({ payload }: { payload: unknown }): Promise<void> {
387
+ const envelope = parseWebhookPayload(payload);
388
+ if (envelope === null) return; // not a shape we know — answer normally
389
+ for (const event of adapter.toDeliverableEvents(envelope)) {
390
+ console.log(`${event.from}: ${event.text}`);
391
+ }
392
+ }
292
393
 
293
394
  const handle = ({ request }: { request: Request }) =>
294
395
  handleChannelWebhook(request, new URL(request.url).pathname, {
295
396
  validators: { whatsapp: whatsapp({ appSecret: process.env.META_APP_SECRET! }) },
296
397
  subscribe: { whatsapp: whatsappSubscribe({ verifyToken: process.env.META_VERIFY_TOKEN! }) },
297
- onMessage: async ({ payload }) => {
298
- const envelope = parseWebhookPayload(payload);
299
- if (envelope === null) return; // not a shape we know — answer normally
300
- for (const event of normalizeInboundMessages(envelope)) {
301
- console.log(`${event.from}: ${event.text}`);
302
- }
303
- },
398
+ onMessage,
304
399
  });
305
400
 
306
401
  // BOTH verbs, and `.csrf(false)` on each.
@@ -339,7 +434,7 @@ the raw body, the headers and the URL, and `ChannelMessage` provides none of the
339
434
  own `createWebhookServer` rather than this seam.
340
435
  Every other adapter exports its translation under its own name — `gateway-line` has
341
436
  `lineEventToMessageEvent`, `gateway-whatsapp` composes `parseWebhookPayload` with
342
- `normalizeInboundMessages` — each with its own signature: read the one you are using rather than
437
+ `WhatsAppAdapter.toDeliverableEvents` — each with its own signature: read the one you are using rather than
343
438
  assuming this one's.
344
439
 
345
440
  Adapters whose transport is a long-lived connection rather than a webhook own that transport and do