@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/lib/index.js ADDED
@@ -0,0 +1,1694 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { Adapter, ElementRegistry, PlatformError } from "@deepseek-ai/cordis-plugin-im-core";
3
+ import { h, isPhrasingContainer, normalize } from "@deepseek-ai/satori-element";
4
+ import { createHmac, timingSafeEqual } from "node:crypto";
5
+ // lib/types/config.js
6
+ /** Validated WhatsApp adapter configuration. */
7
+ const Config = z.object({
8
+ phoneNumberId: z.string().required(),
9
+ systemToken: z.string().role("secret").required(),
10
+ verifyToken: z.string().role("secret").required(),
11
+ secret: z.string().role("secret").required(),
12
+ apiBaseUrl: z.string().role("url").default("https://graph.facebook.com"),
13
+ webhook: z.object({ path: z.string().default("/whatsapp") }).default({}),
14
+ linkPreview: z.boolean().default(true)
15
+ });
16
+ /**
17
+ * Normalize a route path: absolute, no trailing slash.
18
+ *
19
+ * @param path - a configured path.
20
+ * @returns the pathname to register on the web server.
21
+ */
22
+ function routePath(path) {
23
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
24
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
25
+ }
26
+ /**
27
+ * The configuration the adapter cannot work from, as far as it can tell locally.
28
+ *
29
+ * WhatsApp has only the webhook transport, so a profile without a usable callback path receives nothing; the check
30
+ * runs when the bot starts, not on the first delivery.
31
+ *
32
+ * @param config - the validated configuration.
33
+ * @returns the configuration error, or undefined when the configuration is usable.
34
+ */
35
+ function configError(config) {
36
+ if (config.phoneNumberId === "") return /* @__PURE__ */ new Error("whatsapp: phoneNumberId is required (the Graph id of the phone number, from the Meta app WhatsApp API setup)");
37
+ if (config.systemToken === "") return /* @__PURE__ */ new Error("whatsapp: systemToken is required (the system user token that authenticates every Graph call)");
38
+ if (config.verifyToken === "") return /* @__PURE__ */ new Error("whatsapp: verifyToken is required (the subscription handshake compares it with hub.verify_token)");
39
+ if (config.secret === "") return /* @__PURE__ */ new Error("whatsapp: secret is required (the App Secret; it verifies X-Hub-Signature-256 of every delivery)");
40
+ if (config.apiBaseUrl === "") return /* @__PURE__ */ new Error("whatsapp: apiBaseUrl is required (the Graph API root, https://graph.facebook.com by default)");
41
+ let origin;
42
+ try {
43
+ origin = new URL(config.apiBaseUrl);
44
+ } catch {
45
+ return /* @__PURE__ */ new Error(`whatsapp: apiBaseUrl must be an absolute URL, got "${config.apiBaseUrl}"`);
46
+ }
47
+ if (origin.protocol !== "https:") return /* @__PURE__ */ new Error(`whatsapp: apiBaseUrl must be an https URL, got "${config.apiBaseUrl}" (every Graph call carries a bearer token)`);
48
+ }
49
+ // lib/types/errors.js
50
+ /**
51
+ * The failure shape of one Graph call and its mapping onto the core platform taxonomy.
52
+ *
53
+ * Meta rejects a message in one atomic request — authentication, the recipient, the 24-hour window, template
54
+ * parameters and media ids are all checked before anything is delivered — so an answer carrying an error code means
55
+ * nothing was published. Only a failure whose answer itself is inconclusive leaves the outcome unknown.
56
+ */
57
+ /**
58
+ * One failed Graph call.
59
+ *
60
+ * The Graph API answers a refusal with `{ error: { message, type, code, error_subcode?, fbtrace_id,
61
+ * error_data? } }`, or with a page no proxy should produce.
62
+ */
63
+ var WhatsappApiError = class extends Error {
64
+ status;
65
+ code;
66
+ subcode;
67
+ platformMessage;
68
+ type;
69
+ details;
70
+ bodyText;
71
+ nonJson;
72
+ constructor(message, init = {}) {
73
+ super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
74
+ this.name = "WhatsappApiError";
75
+ this.status = init.status;
76
+ this.code = init.code;
77
+ this.subcode = init.subcode;
78
+ this.platformMessage = init.platformMessage;
79
+ this.type = init.type;
80
+ this.details = init.details;
81
+ this.bodyText = init.bodyText;
82
+ this.nonJson = init.nonJson ?? false;
83
+ }
84
+ };
85
+ /**
86
+ * The Graph codes that override the status-based default (§7.2).
87
+ *
88
+ * The `132xxx` entries are template errors: this adapter sends no template, and the table stays for a caller of
89
+ * `bot.internal.sendMessage` and for a future template mode.
90
+ */
91
+ const CODE_RULES = /* @__PURE__ */ new Map([
92
+ [190, {
93
+ kind: "permission",
94
+ published: "no"
95
+ }],
96
+ [100, {
97
+ kind: "invalid",
98
+ published: "no"
99
+ }],
100
+ [131008, {
101
+ kind: "invalid",
102
+ published: "no"
103
+ }],
104
+ [131009, {
105
+ kind: "invalid",
106
+ published: "no"
107
+ }],
108
+ [131021, {
109
+ kind: "invalid",
110
+ published: "no"
111
+ }],
112
+ [131026, {
113
+ kind: "not-found",
114
+ published: "no"
115
+ }],
116
+ [131047, {
117
+ kind: "invalid",
118
+ published: "no"
119
+ }],
120
+ [4, {
121
+ kind: "rate-limit",
122
+ published: "no"
123
+ }],
124
+ [80007, {
125
+ kind: "rate-limit",
126
+ published: "no"
127
+ }],
128
+ [130429, {
129
+ kind: "rate-limit",
130
+ published: "no"
131
+ }],
132
+ [131048, {
133
+ kind: "rate-limit",
134
+ published: "no"
135
+ }],
136
+ [131056, {
137
+ kind: "rate-limit",
138
+ published: "no"
139
+ }],
140
+ [368, {
141
+ kind: "permission",
142
+ published: "no"
143
+ }],
144
+ [131031, {
145
+ kind: "permission",
146
+ published: "no"
147
+ }],
148
+ [131042, {
149
+ kind: "permission",
150
+ published: "no"
151
+ }],
152
+ [133004, {
153
+ kind: "permission",
154
+ published: "no"
155
+ }],
156
+ [133005, {
157
+ kind: "permission",
158
+ published: "no"
159
+ }],
160
+ [133006, {
161
+ kind: "permission",
162
+ published: "no"
163
+ }],
164
+ [133008, {
165
+ kind: "permission",
166
+ published: "no"
167
+ }],
168
+ [133010, {
169
+ kind: "permission",
170
+ published: "no"
171
+ }],
172
+ [131e3, {
173
+ kind: "retryable",
174
+ published: "unknown"
175
+ }],
176
+ [131016, {
177
+ kind: "retryable",
178
+ published: "unknown"
179
+ }],
180
+ [132e3, {
181
+ kind: "invalid",
182
+ published: "no"
183
+ }],
184
+ [132001, {
185
+ kind: "invalid",
186
+ published: "no"
187
+ }],
188
+ [132005, {
189
+ kind: "invalid",
190
+ published: "no"
191
+ }],
192
+ [132007, {
193
+ kind: "invalid",
194
+ published: "no"
195
+ }],
196
+ [132012, {
197
+ kind: "invalid",
198
+ published: "no"
199
+ }],
200
+ [132015, {
201
+ kind: "invalid",
202
+ published: "no"
203
+ }],
204
+ [132016, {
205
+ kind: "invalid",
206
+ published: "no"
207
+ }]
208
+ ]);
209
+ /** The message of a re-engagement refusal names the window and the only way out of it. */
210
+ const CLOSED_WINDOW = "whatsapp: the 24-hour customer service window is closed (131047): a free-form message cannot be sent until the recipient writes again, and only a template message could reach them before that";
211
+ /** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
212
+ function isAbortError(error) {
213
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
214
+ }
215
+ /**
216
+ * Map any failure onto the core platform taxonomy.
217
+ *
218
+ * @param error - the caught failure.
219
+ * @returns the classified platform error.
220
+ */
221
+ function classifyWhatsappError(error) {
222
+ if (error instanceof PlatformError) return error;
223
+ if (error instanceof WhatsappApiError) {
224
+ const code = error.code ?? error.status;
225
+ const init = {
226
+ ...code === void 0 ? {} : { code },
227
+ cause: error
228
+ };
229
+ if (error.status === void 0 || error.nonJson) return new PlatformError("retryable", error.message, {
230
+ ...init,
231
+ published: "unknown"
232
+ });
233
+ if (error.code === 131047) return new PlatformError("invalid", CLOSED_WINDOW, {
234
+ code: error.code,
235
+ published: "no",
236
+ cause: error
237
+ });
238
+ const rule = error.code === void 0 ? void 0 : CODE_RULES.get(error.code);
239
+ if (rule !== void 0) return new PlatformError(rule.kind, error.message, {
240
+ ...init,
241
+ published: rule.published
242
+ });
243
+ if (error.status >= 500) return new PlatformError("retryable", error.message, {
244
+ ...init,
245
+ published: "unknown"
246
+ });
247
+ return new PlatformError("invalid", error.message, {
248
+ ...init,
249
+ published: "no"
250
+ });
251
+ }
252
+ if (isAbortError(error)) return new PlatformError("fatal", error.message, {
253
+ published: "unknown",
254
+ cause: error
255
+ });
256
+ const message = error instanceof Error ? error.message : String(error);
257
+ return new PlatformError("retryable", `whatsapp: request failed: ${message}`, {
258
+ published: "unknown",
259
+ cause: error
260
+ });
261
+ }
262
+ // lib/types/identity.js
263
+ /**
264
+ * The phone number a bot speaks for.
265
+ *
266
+ * The Cloud API names a number by its Graph id in every path (`POST /{phoneNumberId}/messages`), while the webhook
267
+ * addresses it by `metadata.phone_number_id`. The adapter configures the id (one row per number) and proves on connect
268
+ * that the configured token reaches that number: a token/row mismatch would otherwise surface only on the first send.
269
+ */
270
+ /** Failure to confirm the configured phone number. */
271
+ var WhatsappIdentityError = class extends Error {
272
+ constructor(message) {
273
+ super(message);
274
+ this.name = "WhatsappIdentityError";
275
+ }
276
+ };
277
+ /**
278
+ * Read the configured phone number.
279
+ *
280
+ * @param request - the Graph client of the configured number.
281
+ * @param phoneNumberId - the configured Graph id.
282
+ * @returns the number's display name and itself.
283
+ * @throws WhatsappApiError when the token cannot read that number.
284
+ */
285
+ async function fetchPhoneNumber(request, phoneNumberId) {
286
+ return await request.get(`/${encodeURIComponent(phoneNumberId)}`, { fields: "display_phone_number,verified_name" });
287
+ }
288
+ /**
289
+ * Verify a `GET /{phoneNumberId}` answer against the configured id.
290
+ *
291
+ * @param phoneNumberId - the configured Graph id.
292
+ * @param info - the read-back.
293
+ * @returns the Graph id, which is `phoneNumberId`.
294
+ * @throws WhatsappIdentityError when the answer names another number.
295
+ */
296
+ function verifyIdentity(phoneNumberId, info) {
297
+ if (info.id !== phoneNumberId) throw new WhatsappIdentityError(`whatsapp: phoneNumberId is ${phoneNumberId} but GET /${phoneNumberId} returned ${info.id}`);
298
+ return info.id;
299
+ }
300
+ /**
301
+ * The bot's own platform identity.
302
+ *
303
+ * The display phone number is the only human-readable name the Cloud API gives a business number; `wa_id` is not in
304
+ * any payload, and deriving it from the display form would be a guess.
305
+ *
306
+ * @param info - the verified read-back.
307
+ * @returns the user of `bot.user`.
308
+ */
309
+ function userOf(info) {
310
+ return {
311
+ id: info.id,
312
+ name: info.display_phone_number,
313
+ isBot: true
314
+ };
315
+ }
316
+ // lib/types/internal.js
317
+ var Internal = class {
318
+ http;
319
+ constructor(http) {
320
+ this.http = http;
321
+ }
322
+ async getPhoneNumbers(id) {
323
+ const { data } = await this.http.get(`/${id}/phone_numbers`);
324
+ return data;
325
+ }
326
+ async messageReaction(selfId, channelId, messageId, emoji) {
327
+ await this.http.post(`/${selfId}/messages`, {
328
+ messaging_product: "whatsapp",
329
+ to: channelId,
330
+ recipient_type: "individual",
331
+ type: "reaction",
332
+ reaction: {
333
+ message_id: messageId,
334
+ emoji
335
+ }
336
+ });
337
+ }
338
+ async sendMessage(selfId, data) {
339
+ return await this.http.post(`/${selfId}/messages`, data);
340
+ }
341
+ getMedia(mediaId) {
342
+ return this.http.get("/" + mediaId);
343
+ }
344
+ uploadMedia(selfId, form) {
345
+ return this.http.post(`/${selfId}/media`, form);
346
+ }
347
+ };
348
+ // lib/types/media.js
349
+ /**
350
+ * Inbound media: the `satori:` route behind an image, audio, video or document element.
351
+ *
352
+ * The webhook names a media id, never a URL. Reading the bytes takes two requests: `GET /{mediaId}` resolves a
353
+ * short-lived address, and fetching that address — still with the bearer token — returns the bytes. The address is
354
+ * therefore resolved per request instead of being baked into the stored message.
355
+ */
356
+ /** Message of any caught value, for a log line. */
357
+ function messageOf$4(error) {
358
+ return error instanceof Error ? error.message : String(error);
359
+ }
360
+ /**
361
+ * Serve the bytes of one received media object.
362
+ *
363
+ * @param bot - the receiving adapter.
364
+ * @param mediaId - the media id the webhook named.
365
+ * @returns the download answer, status and content headers included, or `502` when either step failed.
366
+ */
367
+ async function serveMedia(bot, mediaId) {
368
+ let address;
369
+ try {
370
+ address = (await bot.internal.getMedia(mediaId)).url;
371
+ } catch (error) {
372
+ bot.ctx.logger.warn("whatsapp: media %s could not be resolved: %s", mediaId, messageOf$4(error));
373
+ return new Response(null, { status: 502 });
374
+ }
375
+ let downloaded;
376
+ try {
377
+ downloaded = await bot.request.download(address);
378
+ } catch (error) {
379
+ bot.ctx.logger.warn("whatsapp: media %s could not be downloaded: %s", mediaId, messageOf$4(error));
380
+ return new Response(null, { status: 502 });
381
+ }
382
+ const headers = new Headers();
383
+ const mime = downloaded.headers.get("content-type");
384
+ if (mime !== null) headers.set("content-type", mime);
385
+ const length = downloaded.headers.get("content-length");
386
+ if (length !== null) headers.set("content-length", length);
387
+ return new Response(downloaded.status === 200 ? downloaded.body : null, {
388
+ status: downloaded.status,
389
+ headers
390
+ });
391
+ }
392
+ // lib/types/modes/shared.js
393
+ /**
394
+ * Shared types and the draft machinery of the single `text` mode.
395
+ *
396
+ * One draft is exactly one platform message: WhatsApp has no request that carries several messages, so every draft is
397
+ * a `POST /{phoneNumberId}/messages` of its own. Text accumulates into a body that the platform's inline marks can
398
+ * format, each media element becomes a message of its own, and reply buttons become one interactive message.
399
+ */
400
+ /** The platform's documented bounds. */
401
+ const WHATSAPP_LIMITS = {
402
+ /** One text message body: 4,096 characters. */
403
+ text: 4096,
404
+ /** Reply buttons one interactive message accepts. */
405
+ buttons: 3,
406
+ /** One reply button title: 20 characters. */
407
+ buttonTitle: 20
408
+ };
409
+ /**
410
+ * The media types the Cloud API accepts, verbatim from the platform's documented list.
411
+ *
412
+ * The upload endpoint answers `100`/`131009` for anything else, so the adapter refuses an unsupported source before it
413
+ * sends a request. `audio/opus` is the one entry the upstream adapter added to the platform list.
414
+ */
415
+ const SUPPORTED_MEDIA = [
416
+ "audio/aac",
417
+ "audio/mp4",
418
+ "audio/mpeg",
419
+ "audio/amr",
420
+ "audio/ogg",
421
+ "audio/opus",
422
+ "application/vnd.ms-powerpoint",
423
+ "application/msword",
424
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
425
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
426
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
427
+ "application/pdf",
428
+ "text/plain",
429
+ "application/vnd.ms-excel",
430
+ "image/jpeg",
431
+ "image/png",
432
+ "image/webp",
433
+ "video/mp4",
434
+ "video/3gpp"
435
+ ];
436
+ /** Report inline media that moves out of its text run into a message of its own. */
437
+ function reportMovedMedia(el, ctx) {
438
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
439
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
440
+ tag: el.type,
441
+ reason: "whatsapp-media-split",
442
+ path: ctx.stableId(el)
443
+ });
444
+ }
445
+ /**
446
+ * The latest paragraph, line or space boundary at or before `limit`.
447
+ *
448
+ * The whitespace that ends the boundary stays in the chunk, so concatenating the chunks reproduces the input.
449
+ *
450
+ * @param text - the text to cut.
451
+ * @param limit - the maximum chunk length in UTF-16 code units.
452
+ * @returns the cut index including the boundary whitespace, or -1 for none.
453
+ */
454
+ function boundaryCut(text, limit) {
455
+ const window = text.slice(0, limit);
456
+ const paragraph = window.lastIndexOf("\n\n");
457
+ if (paragraph >= 0) return paragraph + 2;
458
+ const line = window.lastIndexOf("\n");
459
+ if (line >= 0) return line + 1;
460
+ const space = window.lastIndexOf(" ");
461
+ if (space >= 0) return space + 1;
462
+ return -1;
463
+ }
464
+ /** Move a cut left by one unit when it would fall inside a surrogate pair. */
465
+ function avoidSplitPair(text, cut) {
466
+ if (cut <= 0 || cut >= text.length) return cut;
467
+ const before = text.charCodeAt(cut - 1);
468
+ const after = text.charCodeAt(cut);
469
+ return before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343 ? cut - 1 : cut;
470
+ }
471
+ /**
472
+ * Cut text into chunks a text message accepts.
473
+ *
474
+ * Point cuts prefer a paragraph break, then a line break, then a space, then a code-unit boundary that does not split a
475
+ * surrogate pair. The chunks concatenate back to the input.
476
+ *
477
+ * @param text - the text to cut.
478
+ * @param limit - the maximum chunk length in UTF-16 code units.
479
+ * @returns one or more chunks.
480
+ */
481
+ function splitText(text, limit) {
482
+ if (text.length <= limit) return [text];
483
+ const chunks = [];
484
+ let rest = text;
485
+ while (rest.length > limit) {
486
+ let cut = boundaryCut(rest, limit);
487
+ if (cut <= 0) cut = Math.max(1, limit);
488
+ cut = Math.max(1, avoidSplitPair(rest, cut));
489
+ chunks.push(rest.slice(0, cut));
490
+ rest = rest.slice(cut);
491
+ }
492
+ if (rest !== "") chunks.push(rest);
493
+ return chunks;
494
+ }
495
+ /** The carrier text of a message that exists only to show replies, and of every later button group. */
496
+ const BUTTON_CARRIER = " ";
497
+ /** One media draft of a node. */
498
+ function mediaDraftOf(node) {
499
+ return {
500
+ kind: "media",
501
+ type: node.kind === "file" ? "document" : node.kind,
502
+ ref: node.ref,
503
+ ...node.name === void 0 ? {} : { name: node.name }
504
+ };
505
+ }
506
+ /**
507
+ * Fold a node stream into platform messages.
508
+ *
509
+ * Text accumulates into one body; a media element closes the text body that precedes it and becomes a message of its
510
+ * own; buttons become one interactive message per three, sent before the text that follows the last media element, as
511
+ * the platform shows the body on the first group and nothing on the rest.
512
+ *
513
+ * @param nodes - rendered nodes, in document order.
514
+ * @param ctx - the render context, for the split count.
515
+ * @returns one draft per platform message, in send order; never empty.
516
+ */
517
+ function assembleDraft(nodes, ctx) {
518
+ const drafts = [];
519
+ const buttons = [];
520
+ let buffer = "";
521
+ let split = 0;
522
+ const flushText = () => {
523
+ const text = buffer;
524
+ buffer = "";
525
+ if (text === "") return;
526
+ const chunks = splitText(text, WHATSAPP_LIMITS.text);
527
+ split += chunks.length - 1;
528
+ for (const chunk of chunks) drafts.push({
529
+ kind: "text",
530
+ body: chunk
531
+ });
532
+ };
533
+ const flushButtons = () => {
534
+ const body = buffer === "" ? BUTTON_CARRIER : buffer;
535
+ buffer = "";
536
+ for (let index = 0; index < buttons.length; index += WHATSAPP_LIMITS.buttons) drafts.push({
537
+ kind: "buttons",
538
+ body: index === 0 ? body : BUTTON_CARRIER,
539
+ buttons: buttons.slice(index, index + WHATSAPP_LIMITS.buttons)
540
+ });
541
+ buttons.length = 0;
542
+ };
543
+ for (const node of nodes) switch (node.type) {
544
+ case "text":
545
+ buffer += node.text;
546
+ break;
547
+ case "media":
548
+ flushText();
549
+ drafts.push(mediaDraftOf(node));
550
+ break;
551
+ case "button": buttons.push({
552
+ id: node.id,
553
+ title: node.title
554
+ });
555
+ }
556
+ if (buttons.length > 0) flushButtons();
557
+ flushText();
558
+ ctx.report.split += split;
559
+ if (drafts.length === 0) drafts.push({
560
+ kind: "text",
561
+ body: BUTTON_CARRIER
562
+ });
563
+ return drafts;
564
+ }
565
+ /** One resolved resource key of a prepared draft. */
566
+ function resolvedKey(prepared, ref) {
567
+ const resolved = prepared.resolved.get(ref);
568
+ if (resolved === void 0) throw new Error("whatsapp: media was not prepared before serialize");
569
+ return resolved.key;
570
+ }
571
+ /** The platform-neutral part of a request body. */
572
+ function baseOf(to, ctx) {
573
+ return {
574
+ messaging_product: "whatsapp",
575
+ recipient_type: "individual",
576
+ to,
577
+ ...ctx.index !== 0 || ctx.quote === void 0 ? {} : { context: { message_id: ctx.quote } }
578
+ };
579
+ }
580
+ /** One media request body, per kind, because the media detail sits under the type name. */
581
+ function mediaPayload(type, id, base) {
582
+ switch (type) {
583
+ case "image": return {
584
+ ...base,
585
+ type: "image",
586
+ image: { id }
587
+ };
588
+ case "audio": return {
589
+ ...base,
590
+ type: "audio",
591
+ audio: { id }
592
+ };
593
+ case "video": return {
594
+ ...base,
595
+ type: "video",
596
+ video: { id }
597
+ };
598
+ case "document": return {
599
+ ...base,
600
+ type: "document",
601
+ document: { id }
602
+ };
603
+ case "sticker": return {
604
+ ...base,
605
+ type: "sticker",
606
+ sticker: { id }
607
+ };
608
+ }
609
+ }
610
+ /**
611
+ * Build the exact request body of one prepared draft.
612
+ *
613
+ * @param prepared - the draft with its resource keys resolved.
614
+ * @param ctx - the send context: target, part index and quoted message.
615
+ * @param linkPreview - whether a text body asks the client for a link preview.
616
+ * @returns the request body.
617
+ */
618
+ function serializeDraft(prepared, ctx, linkPreview) {
619
+ const draft = prepared.draft;
620
+ const base = baseOf(ctx.target.chat.id, ctx);
621
+ switch (draft.kind) {
622
+ case "text": return {
623
+ ...base,
624
+ type: "text",
625
+ text: {
626
+ body: draft.body,
627
+ preview_url: linkPreview
628
+ }
629
+ };
630
+ case "media": return mediaPayload(draft.type, resolvedKey(prepared, draft.ref), base);
631
+ case "buttons": {
632
+ const buttons = draft.buttons.map((button) => ({
633
+ type: "reply",
634
+ id: button.id,
635
+ title: button.title
636
+ }));
637
+ return {
638
+ ...base,
639
+ type: "button",
640
+ body: { text: draft.body },
641
+ action: { buttons }
642
+ };
643
+ }
644
+ }
645
+ }
646
+ /**
647
+ * Hard platform limits of one draft, checked before any request.
648
+ *
649
+ * Text splitting and button grouping already keep the draft inside the character and count bounds; what `assemble`
650
+ * cannot guarantee without changing the content is a button title over 20 characters, which the platform refuses.
651
+ *
652
+ * @param draft - the assembled draft.
653
+ * @returns every violation the platform would refuse.
654
+ */
655
+ function checkDraft(draft) {
656
+ if (draft.kind !== "buttons") return [];
657
+ const violations = [];
658
+ for (const button of draft.buttons) {
659
+ if (button.title.length <= WHATSAPP_LIMITS.buttonTitle) continue;
660
+ violations.push({
661
+ kind: "size",
662
+ limit: WHATSAPP_LIMITS.buttonTitle,
663
+ actual: button.title.length,
664
+ message: `WhatsApp reply button titles accept ${WHATSAPP_LIMITS.buttonTitle} characters, "${button.title}" has ${button.title.length}`
665
+ });
666
+ }
667
+ return violations;
668
+ }
669
+ // lib/types/modes/text.js
670
+ /**
671
+ * `text` mode: the only outbound representation the Cloud API programs against.
672
+ *
673
+ * The body is sent verbatim — WhatsApp has no escaping convention — but the platform documents four inline marks plus a
674
+ * quoted-line prefix, so bold, italic, strike-through, monospace and block quotes reach the reader formatted instead of
675
+ * disappearing. A link keeps its URL in the body because the platform has no link mark. Everything else takes the core
676
+ * fallback and is reported as degraded; media becomes a message of its own.
677
+ */
678
+ /** The text run of rendered children and the nodes that cannot ride inside it. */
679
+ function textRun(nodes) {
680
+ let text = "";
681
+ const rest = [];
682
+ for (const node of nodes) if (node.type === "text") text += node.text;
683
+ else rest.push(node);
684
+ return {
685
+ text,
686
+ rest
687
+ };
688
+ }
689
+ /** One inline mark around the rendered children, keeping any media of the subtree outside it. */
690
+ function marked(children, ctx, open, close = open) {
691
+ const run = textRun(ctx.render(children));
692
+ if (run.text === "") return run.rest;
693
+ return [{
694
+ type: "text",
695
+ text: `${open}${run.text}${close}`
696
+ }, ...run.rest];
697
+ }
698
+ /** One media message; a media element standing in phrasing content is reported as moved, not as degraded. */
699
+ function mediaNode(kind, el, ctx, src, meta) {
700
+ reportMovedMedia(el, ctx);
701
+ return {
702
+ type: "media",
703
+ kind,
704
+ ref: ctx.resource(kind, src, meta),
705
+ ...meta.name === void 0 ? {} : { name: meta.name }
706
+ };
707
+ }
708
+ /** The reply button of one `button[type=action]`. */
709
+ function buttonNode(el, ctx) {
710
+ const attrs = el.attrs;
711
+ if (attrs.type !== "action") throw new Error(`whatsapp: <button type="${attrs.type}"> has no native handler`);
712
+ return {
713
+ type: "button",
714
+ id: attrs.id,
715
+ title: ctx.text(el.children).trim()
716
+ };
717
+ }
718
+ /**
719
+ * Build the `text` mode.
720
+ *
721
+ * @param config - the adapter configuration; it carries the link preview switch of every text body.
722
+ * @returns the single mode this adapter registers.
723
+ */
724
+ function createTextMode(config) {
725
+ return {
726
+ id: "text",
727
+ elements: new ElementRegistry().register("text", (el) => ({
728
+ type: "text",
729
+ text: el.attrs.content
730
+ })).register("br", () => ({
731
+ type: "text",
732
+ text: "\n"
733
+ })).register("p", (el, ctx) => [...ctx.render(el.children), {
734
+ type: "text",
735
+ text: "\n\n"
736
+ }]).register("b", (el, ctx) => marked(el.children, ctx, "*")).register("i", (el, ctx) => marked(el.children, ctx, "_")).register("s", (el, ctx) => marked(el.children, ctx, "~")).register("code", (el, ctx) => marked(el.children, ctx, "```")).register("pre", (el, ctx) => marked(el.children, ctx, "```\n", "\n```"), { variants: ["lang"] }).register("blockquote", (el, ctx) => {
737
+ const run = textRun(ctx.render(el.children));
738
+ return [{
739
+ type: "text",
740
+ text: run.text.replace(/\n+$/, "").split("\n").map((line) => `> ${line}`).join("\n")
741
+ }, ...run.rest];
742
+ }).register("a", (el, ctx) => {
743
+ const run = textRun(ctx.render(el.children));
744
+ return [{
745
+ type: "text",
746
+ text: run.text.trim() === "" ? el.attrs.href : `${run.text} (${el.attrs.href})`
747
+ }, ...run.rest];
748
+ }).register("img", (el, ctx) => mediaNode("image", el, ctx, el.attrs.src, {}), { variants: ["inline"] }).register("audio", (el, ctx) => mediaNode("audio", el, ctx, el.attrs.src, {
749
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
750
+ ...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
751
+ })).register("video", (el, ctx) => mediaNode("video", el, ctx, el.attrs.src, {
752
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
753
+ ...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
754
+ })).register("file", (el, ctx) => mediaNode("file", el, ctx, el.attrs.src, {
755
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
756
+ ...el.attrs.size === void 0 ? {} : { size: el.attrs.size }
757
+ })).register("button", (el, ctx) => buttonNode(el, ctx), { variants: ["action"] }).register("button-group", (el, ctx) => ctx.render(el.children)),
758
+ limits: { "limit.text.chars": WHATSAPP_LIMITS.text },
759
+ assemble: (nodes, _envelope, ctx) => assembleDraft(nodes, ctx),
760
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx, config.linkPreview),
761
+ check: (draft) => checkDraft(draft)
762
+ };
763
+ }
764
+ // lib/types/request.js
765
+ /**
766
+ * The transport every WhatsApp Cloud API call shares: API root, bearer authentication, Graph error decoding, JSON
767
+ * unwrapping, and the byte download of an inbound media.
768
+ *
769
+ * `Internal` (the migrated platform API map) and the hand-written calls (identity, media address, upload, download) go
770
+ * through the same class, so they cannot diverge in authentication or failure handling.
771
+ */
772
+ /** How much of a body that carried no Graph error is kept in the error and the log; enough to recognise a gateway page. */
773
+ const BODY_PREFIX_BYTES = 512;
774
+ /** Message of any caught value, for a log line. */
775
+ function messageOf$3(error) {
776
+ return error instanceof Error ? error.message : String(error);
777
+ }
778
+ /** Whether a failed `ctx.http` call was the caller's cancellation rather than a transport failure. */
779
+ function isCancellation(cause, signal) {
780
+ if (signal?.aborted === true) return true;
781
+ if ((cause instanceof Error || cause instanceof DOMException) && cause.name === "AbortError") return true;
782
+ return signal?.reason !== void 0 && cause === signal.reason;
783
+ }
784
+ /** A cancelled request rejects with the signal's reason, so the classifier sees the cancellation itself. */
785
+ function cancellation(cause, signal) {
786
+ return signal?.aborted === true ? signal.reason : cause;
787
+ }
788
+ /** One JSON object, when the value is a plain object. */
789
+ function asRecord(value) {
790
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
791
+ }
792
+ /** The `error` member of a Graph answer, when the answer carries one. */
793
+ function errorEnvelopeOf(body) {
794
+ return asRecord(asRecord(body)?.error);
795
+ }
796
+ /**
797
+ * One numeric member of a Graph error envelope; the platform sends a number, an older reply a numeric string.
798
+ * @param value - the member to read.
799
+ * @returns the number, or undefined when the member is absent or not numeric.
800
+ */
801
+ function numberOf(value) {
802
+ if (typeof value === "number" && Number.isFinite(value)) return value;
803
+ if (typeof value === "string" && value !== "" && Number.isFinite(Number(value))) return Number(value);
804
+ }
805
+ /**
806
+ * The Graph API client of one configured phone number.
807
+ *
808
+ * Every call carries `Authorization: Bearer <systemToken>`; a refusal raises {@link WhatsappApiError} carrying the
809
+ * HTTP status and the Graph error `code`, which {@link classifyWhatsappError} maps onto the core taxonomy.
810
+ */
811
+ var WhatsAppRequest = class {
812
+ ctx;
813
+ config;
814
+ /** API root without its trailing slashes (`apiBaseUrl`, or a Graph version pinned into it). */
815
+ baseUrl;
816
+ constructor(ctx, config) {
817
+ this.ctx = ctx;
818
+ this.config = config;
819
+ this.baseUrl = config.apiBaseUrl.replace(/\/+$/, "");
820
+ }
821
+ /**
822
+ * One endpoint under the API root.
823
+ * @param method - HTTP method.
824
+ * @param path - endpoint path, starting with `/`.
825
+ * @param data - JSON body or multipart form; absent on a read.
826
+ * @param signal - cancellation.
827
+ * @returns the parsed JSON answer.
828
+ * @throws WhatsappApiError when the call failed or did not answer with JSON.
829
+ */
830
+ async invoke(method, path, data, signal) {
831
+ const url = `${this.baseUrl}${path}`;
832
+ let response;
833
+ try {
834
+ response = await this.ctx.http(url, {
835
+ method,
836
+ headers: { authorization: `Bearer ${this.config.systemToken}` },
837
+ ...data === void 0 ? {} : { data },
838
+ ...signal === void 0 ? {} : { signal }
839
+ });
840
+ } catch (cause) {
841
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
842
+ throw new WhatsappApiError(`whatsapp: ${method} ${path} request failed: ${messageOf$3(cause)}`, { cause });
843
+ }
844
+ let text;
845
+ try {
846
+ text = await response.text();
847
+ } catch (cause) {
848
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
849
+ throw new WhatsappApiError(`whatsapp: ${method} ${path} answered ${response.status} but its body could not be read`, {
850
+ status: response.status,
851
+ cause
852
+ });
853
+ }
854
+ let body;
855
+ let nonJson = false;
856
+ if (text !== "") try {
857
+ body = JSON.parse(text);
858
+ } catch {
859
+ nonJson = true;
860
+ }
861
+ if (response.status < 200 || response.status >= 300 || nonJson) {
862
+ const envelope = errorEnvelopeOf(body);
863
+ const platformMessage = typeof envelope?.message === "string" ? envelope.message : void 0;
864
+ const errorData = asRecord(envelope?.error_data);
865
+ throw new WhatsappApiError(`whatsapp: ${method} ${path} answered ${response.status}` + (platformMessage === void 0 ? "" : `: ${platformMessage}`), {
866
+ status: response.status,
867
+ ...numberOf(envelope?.code) === void 0 ? {} : { code: numberOf(envelope?.code) },
868
+ ...numberOf(envelope?.error_subcode) === void 0 ? {} : { subcode: numberOf(envelope?.error_subcode) },
869
+ ...platformMessage === void 0 ? {} : { platformMessage },
870
+ ...typeof envelope?.type === "string" ? { type: envelope.type } : {},
871
+ ...typeof errorData?.details === "string" ? { details: errorData.details } : {},
872
+ ...text === "" ? {} : { bodyText: text.slice(0, BODY_PREFIX_BYTES) },
873
+ nonJson
874
+ });
875
+ }
876
+ return body;
877
+ }
878
+ /**
879
+ * Read one endpoint.
880
+ * @param path - endpoint path, starting with `/`.
881
+ * @param params - query parameters, when the endpoint takes any.
882
+ * @param signal - cancellation.
883
+ * @returns the parsed JSON answer.
884
+ */
885
+ async get(path, params, signal) {
886
+ let search = "";
887
+ if (params !== void 0) {
888
+ const query = new URLSearchParams();
889
+ for (const [key, value] of Object.entries(params)) query.append(key, String(value));
890
+ search = query.toString();
891
+ }
892
+ return await this.invoke("GET", `${path}${search === "" ? "" : `?${search}`}`, void 0, signal);
893
+ }
894
+ /**
895
+ * Post one JSON body or multipart form to an endpoint.
896
+ * @param path - endpoint path, starting with `/`.
897
+ * @param data - JSON body or {@link FormData}.
898
+ * @param signal - cancellation.
899
+ * @returns the parsed JSON answer.
900
+ */
901
+ async post(path, data, signal) {
902
+ return await this.invoke("POST", path, data, signal);
903
+ }
904
+ /**
905
+ * Download the bytes behind a resolved media address.
906
+ *
907
+ * The media address is short-lived and requires the same bearer token as the API itself. The answer is returned as
908
+ * it arrived, whatever its status: the caller maps `200` to the bytes and anything else to "unavailable".
909
+ *
910
+ * @param url - the address `GET /{mediaId}` returned.
911
+ * @param signal - cancellation.
912
+ * @returns the download answer.
913
+ * @throws WhatsappApiError when the request never got an answer.
914
+ */
915
+ async download(url, signal) {
916
+ try {
917
+ return await this.ctx.http(url, {
918
+ headers: { authorization: `Bearer ${this.config.systemToken}` },
919
+ ...signal === void 0 ? {} : { signal }
920
+ });
921
+ } catch (cause) {
922
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
923
+ throw new WhatsappApiError(`whatsapp: media download failed: ${messageOf$3(cause)}`, { cause });
924
+ }
925
+ }
926
+ };
927
+ // lib/types/send.js
928
+ /**
929
+ * Outbound: one request per draft, and the two reaction hooks.
930
+ *
931
+ * The Cloud API answers `POST /{phoneNumberId}/messages` with `{ messages: [{ id }], contacts }`. The id is the
932
+ * `wamid` of the published message; an answer without one means the request was accepted but its outcome cannot be
933
+ * described, so it is reported as a platform error with an unknown outcome instead of a success.
934
+ */
935
+ /** The media id a media request carries, when the payload is a media message. */
936
+ function mediaIdOf(payload) {
937
+ switch (payload.type) {
938
+ case "image": return payload.image?.id;
939
+ case "audio": return payload.audio?.id;
940
+ case "video": return payload.video?.id;
941
+ case "document": return payload.document?.id;
942
+ case "sticker": return payload.sticker?.id;
943
+ default: return;
944
+ }
945
+ }
946
+ /**
947
+ * Send one serialized payload and report the part the platform created.
948
+ *
949
+ * @param deps - the adapter's API surface.
950
+ * @param payload - one request body.
951
+ * @param _target - the chat the payload goes to; the recipient rides `payload.to`.
952
+ * @param _ctx - the core send context; this adapter keeps no per-part state.
953
+ * @returns the published part.
954
+ * @throws PlatformError `invalid` when the answer carries no message id, with an unknown outcome.
955
+ */
956
+ async function sendPayload(deps, payload, _target, _ctx) {
957
+ const id = (await deps.internal.sendMessage(deps.selfId, payload))?.messages?.[0]?.id;
958
+ if (id === void 0 || id === "") throw new PlatformError("invalid", "whatsapp: sendMessage answered without a message id", { published: "unknown" });
959
+ const mediaId = mediaIdOf(payload);
960
+ return {
961
+ id,
962
+ kind: "message",
963
+ time: Date.now(),
964
+ raw: {
965
+ waId: payload.to,
966
+ ...mediaId === void 0 ? {} : { mediaId }
967
+ }
968
+ };
969
+ }
970
+ /**
971
+ * Add the reaction of the bot to one published message.
972
+ *
973
+ * @param deps - the adapter's API surface.
974
+ * @param message - the message to react to.
975
+ * @param emoji - the reaction, passed through as the payload spells it.
976
+ */
977
+ async function createReaction(deps, message, emoji) {
978
+ await deps.internal.messageReaction(deps.selfId, message.chat.id, message.id, emoji);
979
+ }
980
+ /**
981
+ * Remove the reaction of the bot from one published message.
982
+ *
983
+ * The platform represents "no reaction" as an empty emoji on the same endpoint, so the emoji to remove is not part of
984
+ * the request: a number holds one reaction per message, and clearing it clears whichever one it is.
985
+ *
986
+ * @param deps - the adapter's API surface.
987
+ * @param message - the message to clear the reaction of.
988
+ * @param _emoji - unused; the platform removes the single reaction a number may hold.
989
+ */
990
+ async function deleteReaction(deps, message, _emoji) {
991
+ await deps.internal.messageReaction(deps.selfId, message.chat.id, message.id, "");
992
+ }
993
+ // lib/types/interactive.js
994
+ /**
995
+ * Inbound interactions and reactions.
996
+ *
997
+ * A WhatsApp reply button, list pick or template quick reply is not a text message: it answers a message this bot sent
998
+ * (through `context.message_id`), and the host routes it to the callback registered under the id the button carried.
999
+ * A reaction is the platform's only other inbound signal; removing one is an empty emoji.
1000
+ */
1001
+ /**
1002
+ * Decode a reaction into `reaction-added` or `reaction-removed`.
1003
+ *
1004
+ * The reaction names the message it applies to, the reactor and the emoji; the chat is the reactor's own conversation,
1005
+ * which is the only chat a reaction payload can come from.
1006
+ *
1007
+ * @param bot - the receiving adapter.
1008
+ * @param message - the reaction message.
1009
+ * @param context - the chat, sender and referrer of the payload.
1010
+ * @returns the session to publish.
1011
+ */
1012
+ function decodeReaction(bot, message, context) {
1013
+ return bot.session({
1014
+ type: message.reaction.emoji === "" ? "reaction-removed" : "reaction-added",
1015
+ id: message.id,
1016
+ timestamp: context.timestamp,
1017
+ reaction: {
1018
+ message: {
1019
+ id: message.reaction.message_id,
1020
+ chat: context.chat
1021
+ },
1022
+ emoji: message.reaction.emoji,
1023
+ user: context.user
1024
+ },
1025
+ raw: message
1026
+ });
1027
+ }
1028
+ /** The message an interaction answers: the one it quotes, or its own when the payload names no context. */
1029
+ function answeredMessageId(message) {
1030
+ return message.context?.id ?? message.id;
1031
+ }
1032
+ /**
1033
+ * Decode a reply button or a list pick.
1034
+ *
1035
+ * @param bot - the receiving adapter.
1036
+ * @param message - the interactive message.
1037
+ * @param context - the chat, sender and referrer of the payload.
1038
+ * @returns the `interaction/button` or `interaction/select` session.
1039
+ */
1040
+ function decodeInteractive(bot, message, context) {
1041
+ const chat = context.chat;
1042
+ const answer = {
1043
+ id: answeredMessageId(message),
1044
+ chat
1045
+ };
1046
+ switch (message.interactive.type) {
1047
+ case "button_reply": return bot.session({
1048
+ type: "interaction/button",
1049
+ id: message.id,
1050
+ timestamp: context.timestamp,
1051
+ button: {
1052
+ bot,
1053
+ id: message.interactive.button_reply.id,
1054
+ user: context.user,
1055
+ chat,
1056
+ message: answer,
1057
+ referrer: context.referrer,
1058
+ time: context.timestamp
1059
+ },
1060
+ raw: message
1061
+ });
1062
+ case "list_reply": return bot.session({
1063
+ type: "interaction/select",
1064
+ id: message.id,
1065
+ timestamp: context.timestamp,
1066
+ select: {
1067
+ bot,
1068
+ id: message.interactive.list_reply.id,
1069
+ values: [message.interactive.list_reply.title],
1070
+ user: context.user,
1071
+ chat,
1072
+ message: answer,
1073
+ referrer: context.referrer,
1074
+ time: context.timestamp
1075
+ },
1076
+ raw: message
1077
+ });
1078
+ }
1079
+ }
1080
+ /**
1081
+ * Decode a template quick reply.
1082
+ *
1083
+ * A template's quick reply carries an optional `payload`; a template written without one leaves the button text as the
1084
+ * only identity the reply has.
1085
+ *
1086
+ * @param bot - the receiving adapter.
1087
+ * @param message - the `button` message.
1088
+ * @param context - the chat, sender and referrer of the payload.
1089
+ * @returns the `interaction/button` session.
1090
+ */
1091
+ function decodeTemplateButton(bot, message, context) {
1092
+ return bot.session({
1093
+ type: "interaction/button",
1094
+ id: message.id,
1095
+ timestamp: context.timestamp,
1096
+ button: {
1097
+ bot,
1098
+ id: message.button.payload ?? message.button.text,
1099
+ user: context.user,
1100
+ chat: context.chat,
1101
+ message: {
1102
+ id: message.context?.id ?? message.id,
1103
+ chat: context.chat
1104
+ },
1105
+ referrer: context.referrer,
1106
+ time: context.timestamp
1107
+ },
1108
+ raw: message
1109
+ });
1110
+ }
1111
+ // lib/types/decode.js
1112
+ /**
1113
+ * Inbound decoding: one change of a webhook delivery becomes zero or more intake `Session`s.
1114
+ *
1115
+ * The Cloud API pushes everything at once — several entries, each with several changes, each with several messages —
1116
+ * and there is no API that reads a message back, so this payload is the only copy of the content. Every message is
1117
+ * decoded; a chat is always the sender's own `wa_id`, because this adapter supports no group.
1118
+ */
1119
+ /** Message of any caught value, for a log line. */
1120
+ function messageOf$2(error) {
1121
+ return error instanceof Error ? error.message : String(error);
1122
+ }
1123
+ /** The direct chat of one sender; a Cloud API conversation has exactly one peer. */
1124
+ function chatRefOf(message) {
1125
+ return {
1126
+ id: message.from,
1127
+ type: "direct"
1128
+ };
1129
+ }
1130
+ /**
1131
+ * The sender of one message.
1132
+ *
1133
+ * The payload names the sender's display name in `contacts`, keyed by `wa_id` — a batch can carry several senders, so
1134
+ * the entry is matched instead of taken from the first position.
1135
+ * @param message - the message being decoded.
1136
+ * @param contacts - the `contacts` array of the same change.
1137
+ * @returns the sender reference, named when the payload names it.
1138
+ */
1139
+ function senderOf(message, contacts) {
1140
+ const name = contacts?.find((contact) => contact.wa_id === message.from)?.profile.name;
1141
+ return {
1142
+ id: message.from,
1143
+ ...name === void 0 ? {} : { name },
1144
+ isBot: false
1145
+ };
1146
+ }
1147
+ /** The platform timestamp of a message: Meta sends seconds as a string. */
1148
+ function timeOf(message) {
1149
+ const seconds = Number.parseInt(message.timestamp, 10);
1150
+ return Number.isFinite(seconds) ? seconds * 1e3 : Date.now();
1151
+ }
1152
+ /** The adapter context an interaction or reaction session is built from. */
1153
+ function contextOf(bot, message, contacts) {
1154
+ return {
1155
+ chat: chatRefOf(message),
1156
+ user: senderOf(message, contacts),
1157
+ referrer: {
1158
+ waId: message.from,
1159
+ messageId: message.id,
1160
+ phoneNumberId: bot.config.phoneNumberId,
1161
+ timestamp: timeOf(message)
1162
+ },
1163
+ timestamp: timeOf(message)
1164
+ };
1165
+ }
1166
+ /** The `satori:` address of one received media object. */
1167
+ function mediaSource(bot, media) {
1168
+ return bot.getInternalUrl(`/assets/${encodeURIComponent(media.id)}`);
1169
+ }
1170
+ /** The caption that precedes a media element, when the sender typed one. */
1171
+ function captionOf(media) {
1172
+ return media.caption === void 0 || media.caption === "" ? [] : [media.caption];
1173
+ }
1174
+ /** The elements of one media message: its caption, then the media itself. */
1175
+ function mediaNodes(bot, message) {
1176
+ const media = message[message.type];
1177
+ if (media === void 0) return [];
1178
+ const src = mediaSource(bot, media);
1179
+ const name = media.filename === void 0 ? {} : { name: media.filename };
1180
+ switch (message.type) {
1181
+ case "image": return [...captionOf(media), h("img", { src })];
1182
+ case "audio": return [...captionOf(media), h("audio", {
1183
+ src,
1184
+ ...name
1185
+ })];
1186
+ case "video": return [...captionOf(media), h("video", {
1187
+ src,
1188
+ ...name
1189
+ })];
1190
+ case "document": return [...captionOf(media), h("file", {
1191
+ src,
1192
+ ...name
1193
+ })];
1194
+ }
1195
+ }
1196
+ /**
1197
+ * The elements of one message of a type that carries content.
1198
+ *
1199
+ * @param bot - the receiving adapter.
1200
+ * @param message - the decoded message.
1201
+ * @returns its elements, possibly empty for a shape this snapshot does not carry.
1202
+ */
1203
+ function contentNodes(bot, message) {
1204
+ switch (message.type) {
1205
+ case "text": return message.text.body === "" ? [] : [message.text.body];
1206
+ case "image":
1207
+ case "audio":
1208
+ case "video":
1209
+ case "document": return mediaNodes(bot, message);
1210
+ case "sticker": return message.sticker === void 0 ? [] : [h("img", {
1211
+ src: mediaSource(bot, message.sticker),
1212
+ alt: "[贴纸]"
1213
+ })];
1214
+ case "location": return [`📍 ${message.location.latitude}, ${message.location.longitude}`];
1215
+ case "contacts": {
1216
+ const names = message.contacts.map((contact) => contact.name.formatted_name);
1217
+ return [names.length === 0 ? "联系人" : `联系人:${names.join("、")}`, h("raw", {
1218
+ platform: "whatsapp",
1219
+ type: "contacts",
1220
+ data: message.contacts
1221
+ })];
1222
+ }
1223
+ case "system": return message.system.body === "" ? [] : [message.system.body];
1224
+ default: return [];
1225
+ }
1226
+ }
1227
+ /**
1228
+ * The content tree of one message, never empty.
1229
+ * @param bot - the receiving adapter.
1230
+ * @param message - the decoded message.
1231
+ * @returns the normalized `<message>` root.
1232
+ */
1233
+ function contentOf(bot, message) {
1234
+ const nodes = contentNodes(bot, message);
1235
+ if (nodes.length > 0) return normalize(h("message", nodes));
1236
+ return normalize(h("message", h("raw", {
1237
+ platform: "whatsapp",
1238
+ type: message.type,
1239
+ data: message
1240
+ })));
1241
+ }
1242
+ /** The quote an inbound message answers, when the payload names one. */
1243
+ function quoteOf(message) {
1244
+ if (message.context === void 0) return void 0;
1245
+ return {
1246
+ id: message.context.id,
1247
+ sender: { id: message.context.from }
1248
+ };
1249
+ }
1250
+ /**
1251
+ * Decode one ordinary message into a `message` session.
1252
+ *
1253
+ * @param bot - the receiving adapter.
1254
+ * @param message - the decoded message.
1255
+ * @param contacts - the `contacts` array of the same change.
1256
+ * @returns the session to publish.
1257
+ */
1258
+ function messageSession(bot, message, contacts) {
1259
+ const context = contextOf(bot, message, contacts);
1260
+ const quote = quoteOf(message);
1261
+ const inbound = {
1262
+ id: message.id,
1263
+ chat: context.chat,
1264
+ sender: context.user,
1265
+ content: contentOf(bot, message),
1266
+ ...quote === void 0 ? {} : { quote },
1267
+ mentions: {
1268
+ self: false,
1269
+ all: false,
1270
+ users: []
1271
+ },
1272
+ time: context.timestamp,
1273
+ referrer: context.referrer,
1274
+ raw: message
1275
+ };
1276
+ return bot.session({
1277
+ type: "message",
1278
+ id: message.id,
1279
+ timestamp: context.timestamp,
1280
+ message: inbound,
1281
+ raw: message
1282
+ });
1283
+ }
1284
+ /** Log one delivery receipt; the platform's own view of an outbound message has no DSH event. */
1285
+ function logStatus(bot, status) {
1286
+ if (status.status !== "failed") {
1287
+ bot.ctx.logger.debug("whatsapp: message %s is %s", status.id, status.status);
1288
+ return;
1289
+ }
1290
+ const errors = status.errors ?? [];
1291
+ bot.ctx.logger.warn("whatsapp: delivery of %s to %s failed: %s", status.id, status.recipient_id, errors.length === 0 ? "no error detail" : errors.map((error) => [
1292
+ String(error.code),
1293
+ error.title,
1294
+ error.error_data?.details
1295
+ ].filter((part) => part !== void 0 && part !== "").join(" ")).join("; "));
1296
+ }
1297
+ /**
1298
+ * Decode every message of one change.
1299
+ *
1300
+ * A non-`messages` change family is dropped with a debug line: the IM host has no consumer for account, template or
1301
+ * quality updates. Delivery receipts never reach the message store.
1302
+ *
1303
+ * @param bot - the receiving adapter.
1304
+ * @param change - one change of one entry.
1305
+ * @returns the sessions to publish, in payload order.
1306
+ */
1307
+ function decodeChange(bot, change) {
1308
+ if (change.field !== "messages") {
1309
+ bot.ctx.logger.debug("whatsapp: ignoring a %s change", change.field);
1310
+ return [];
1311
+ }
1312
+ for (const status of change.value.statuses ?? []) logStatus(bot, status);
1313
+ for (const error of change.value.errors ?? []) bot.ctx.logger.warn("whatsapp: the webhook reported an error: %s", messageOf$2(error));
1314
+ const sessions = [];
1315
+ for (const message of change.value.messages ?? []) {
1316
+ const session = decodeMessage(bot, message, change.value.contacts);
1317
+ if (session !== void 0) sessions.push(session);
1318
+ }
1319
+ return sessions;
1320
+ }
1321
+ /**
1322
+ * Decode one message of the payload.
1323
+ *
1324
+ * @param bot - the receiving adapter.
1325
+ * @param message - one `messages` entry.
1326
+ * @param contacts - the `contacts` array of the same change.
1327
+ * @returns the session to publish, or undefined for a message this adapter drops.
1328
+ */
1329
+ function decodeMessage(bot, message, contacts) {
1330
+ if (message.group_id !== void 0) return;
1331
+ switch (message.type) {
1332
+ case "reaction": return decodeReaction(bot, message, contextOf(bot, message, contacts));
1333
+ case "interactive": return decodeInteractive(bot, message, contextOf(bot, message, contacts));
1334
+ case "button": return decodeTemplateButton(bot, message, contextOf(bot, message, contacts));
1335
+ default: return messageSession(bot, message, contacts);
1336
+ }
1337
+ }
1338
+ // lib/types/signature.js
1339
+ /** Header Meta signs a delivery with. */
1340
+ const SIGNATURE_HEADER = "x-hub-signature-256";
1341
+ /**
1342
+ * The `X-Hub-Signature-256` value of one delivery.
1343
+ *
1344
+ * Meta signs the request body exactly as it arrived, keyed by the App Secret.
1345
+ *
1346
+ * @param secret - the App Secret.
1347
+ * @param body - the raw request body, before any decoding.
1348
+ * @returns `sha256=` followed by the hex HMAC-SHA256 of the body.
1349
+ */
1350
+ function signatureOf(secret, body) {
1351
+ return `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
1352
+ }
1353
+ /**
1354
+ * Compare two strings without leaking where they differ.
1355
+ *
1356
+ * Used for the app secret signature and for the subscription token: both are compared against a value the request
1357
+ * merely claims to know, so the comparison itself must not become an oracle.
1358
+ *
1359
+ * @param expected - the value computed from the request.
1360
+ * @param received - the value the request carried, if it carried one.
1361
+ * @returns whether the two are equal.
1362
+ */
1363
+ function constantTimeEqual(expected, received) {
1364
+ if (received === void 0) return false;
1365
+ const left = Buffer.from(expected, "utf8");
1366
+ const right = Buffer.from(received, "utf8");
1367
+ if (left.length !== right.length) return false;
1368
+ return timingSafeEqual(left, right);
1369
+ }
1370
+ /**
1371
+ * Whether a delivery carries the signature of `body`.
1372
+ *
1373
+ * @param secret - the App Secret.
1374
+ * @param body - the raw request body.
1375
+ * @param received - the header value, if the request carried one.
1376
+ * @returns whether the header matches.
1377
+ */
1378
+ function matchesSignature(secret, body, received) {
1379
+ return constantTimeEqual(signatureOf(secret, body), received);
1380
+ }
1381
+ // lib/types/transport/webhook.js
1382
+ /**
1383
+ * The webhook transport.
1384
+ *
1385
+ * The Cloud API has no long connection, polling or gateway: Meta posts every event to one public HTTPS callback, and
1386
+ * the subscription is confirmed once by a `GET` handshake on the same path. The route is registered on the profile's
1387
+ * `webServer`, which owns the listener and the public address; the adapter keeps the handler anonymous and
1388
+ * authenticates every delivery with the App Secret.
1389
+ *
1390
+ * A delivery is acknowledged only after intake stored every message it carries, so a retrying platform can resend a
1391
+ * delivery whose intake failed, and every refusal happens before any work is done.
1392
+ */
1393
+ /** Message of any caught value, for a log line. */
1394
+ function messageOf$1(error) {
1395
+ return error instanceof Error ? error.message : String(error);
1396
+ }
1397
+ /** One header of an inbound request, when it arrived exactly once. */
1398
+ function headerOf(request, name) {
1399
+ const value = request.headers[name];
1400
+ return typeof value === "string" ? value : void 0;
1401
+ }
1402
+ /** One plain object. */
1403
+ function isRecord(value) {
1404
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1405
+ }
1406
+ /** Read a request body to its end. The platform publishes no delivery-size limit, so the adapter imposes none. */
1407
+ async function readBody(request) {
1408
+ const chunks = [];
1409
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1410
+ return Buffer.concat(chunks).toString("utf8");
1411
+ }
1412
+ /** Write one bodiless answer. */
1413
+ function writeStatus(response, status, headers = {}) {
1414
+ response.writeHead(status, headers);
1415
+ response.end();
1416
+ }
1417
+ /** Write one answer with a body. */
1418
+ function writeBody(response, status, body, contentType) {
1419
+ response.writeHead(status, { "content-type": contentType });
1420
+ response.end(body);
1421
+ }
1422
+ /**
1423
+ * Whether a parsed JSON value is a delivery this handler can read.
1424
+ *
1425
+ * A change of the `messages` field carries the routing key, so its value is validated down to that key; every other
1426
+ * change family is only logged, so its value is taken as it came.
1427
+ * @param value - the parsed JSON value.
1428
+ * @returns whether the value is a webhook delivery.
1429
+ */
1430
+ function isWebhookBody(value) {
1431
+ if (!isRecord(value) || typeof value.object !== "string" || !Array.isArray(value.entry)) return false;
1432
+ for (const entry of value.entry) {
1433
+ if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;
1434
+ for (const change of entry.changes) {
1435
+ if (!isRecord(change) || typeof change.field !== "string" || !isRecord(change.value)) return false;
1436
+ if (change.field !== "messages") continue;
1437
+ const current = change.value;
1438
+ if (!isRecord(current.metadata) || typeof current.metadata.phone_number_id !== "string") return false;
1439
+ if (current.messages !== void 0 && !Array.isArray(current.messages)) return false;
1440
+ if (current.statuses !== void 0 && !Array.isArray(current.statuses)) return false;
1441
+ }
1442
+ }
1443
+ return true;
1444
+ }
1445
+ /**
1446
+ * The webhook route.
1447
+ *
1448
+ * `start` registers the one route that answers both the handshake and every delivery; `stop` releases it.
1449
+ */
1450
+ var WhatsappWebhook = class {
1451
+ bot;
1452
+ webServer;
1453
+ dispose;
1454
+ constructor(bot, webServer) {
1455
+ this.bot = bot;
1456
+ this.webServer = webServer;
1457
+ }
1458
+ /** Register the route. */
1459
+ start() {
1460
+ this.dispose = this.webServer.register({
1461
+ kind: "exact",
1462
+ path: routePath(this.bot.config.webhook.path),
1463
+ auth: "anonymous",
1464
+ handler: (request, response) => this.handle(request, response)
1465
+ });
1466
+ }
1467
+ /** Release the route. */
1468
+ stop() {
1469
+ this.dispose?.();
1470
+ this.dispose = void 0;
1471
+ }
1472
+ async handle(request, response) {
1473
+ try {
1474
+ if (request.method === "GET") {
1475
+ this.verify(request, response);
1476
+ return;
1477
+ }
1478
+ if (request.method !== "POST") {
1479
+ writeStatus(response, 405, { allow: "GET, POST" });
1480
+ return;
1481
+ }
1482
+ await this.deliver(request, response);
1483
+ } catch (error) {
1484
+ this.bot.ctx.logger.warn("whatsapp: webhook delivery failed: %s", messageOf$1(error));
1485
+ if (!response.headersSent) writeStatus(response, 500);
1486
+ else response.end();
1487
+ }
1488
+ }
1489
+ /**
1490
+ * The subscription handshake: `hub.mode` and `hub.verify_token` are checked, then `hub.challenge` is echoed.
1491
+ *
1492
+ * The token is a value a human typed into the Meta app panel, not a secret of the API surface, but it is compared in
1493
+ * constant time like the signature so the endpoint is not an oracle for it.
1494
+ */
1495
+ verify(request, response) {
1496
+ const query = new URL(request.url ?? "", "http://localhost").searchParams;
1497
+ const mode = query.get("hub.mode");
1498
+ const challenge = query.get("hub.challenge");
1499
+ const token = query.get("hub.verify_token") ?? void 0;
1500
+ if (mode !== "subscribe" || challenge === null || !constantTimeEqual(this.bot.config.verifyToken, token)) {
1501
+ writeStatus(response, 403);
1502
+ return;
1503
+ }
1504
+ writeBody(response, 200, challenge, "text/plain");
1505
+ }
1506
+ /** Verify, parse and store one delivery. */
1507
+ async deliver(request, response) {
1508
+ const received = headerOf(request, SIGNATURE_HEADER);
1509
+ if (received === void 0) {
1510
+ writeStatus(response, 401);
1511
+ return;
1512
+ }
1513
+ const body = await readBody(request);
1514
+ if (!matchesSignature(this.bot.config.secret, body, received)) {
1515
+ writeStatus(response, 401);
1516
+ return;
1517
+ }
1518
+ let parsed;
1519
+ try {
1520
+ parsed = JSON.parse(body);
1521
+ } catch (error) {
1522
+ this.bot.ctx.logger.warn("whatsapp: cannot parse a webhook delivery: %s", messageOf$1(error));
1523
+ writeStatus(response, 400);
1524
+ return;
1525
+ }
1526
+ if (!isWebhookBody(parsed)) {
1527
+ this.bot.ctx.logger.warn("whatsapp: a webhook delivery is not a WhatsApp payload");
1528
+ writeStatus(response, 400);
1529
+ return;
1530
+ }
1531
+ if (parsed.object !== "whatsapp_business_account") {
1532
+ this.bot.ctx.logger.debug("whatsapp: ignoring a %s delivery", parsed.object);
1533
+ writeStatus(response, 200);
1534
+ return;
1535
+ }
1536
+ for (const entry of parsed.entry) for (const change of entry.changes) {
1537
+ if (change.field === "messages" && change.value.metadata.phone_number_id !== this.bot.config.phoneNumberId) {
1538
+ this.bot.ctx.logger.debug("whatsapp: skipping a change of number %s", change.value.metadata.phone_number_id);
1539
+ continue;
1540
+ }
1541
+ for (const session of decodeChange(this.bot, change)) await this.bot.receive(session);
1542
+ }
1543
+ writeStatus(response, 200);
1544
+ }
1545
+ };
1546
+ // lib/types/bot.js
1547
+ /** Message of any caught value, for a log line. */
1548
+ function messageOf(error) {
1549
+ return error instanceof Error ? error.message : String(error);
1550
+ }
1551
+ /**
1552
+ * WhatsApp Cloud API adapter for one business phone number.
1553
+ *
1554
+ * The number is identified by configuration (`phoneNumberId`), confirmed with `GET /{phoneNumberId}` on connect. The
1555
+ * webhook is the only transport, `text` is the only mode, and every send is its own request: the platform has no
1556
+ * request that publishes several messages, no edit, no delete and no stream.
1557
+ *
1558
+ * The 24-hour customer service window is not tracked locally. A free-form message outside it is refused by the
1559
+ * platform (`131047`), which this adapter reports as an `invalid`, unpublished failure naming the template
1560
+ * requirement; no template message is sent by this version.
1561
+ */
1562
+ var WhatsappBot = class extends Adapter {
1563
+ /** The adapter needs the Satori service and the isolated `http` service. */
1564
+ static inject = ["satori", "http"];
1565
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
1566
+ static Config = Config;
1567
+ modes;
1568
+ modeOrder = ["text"];
1569
+ /** The Graph client every call goes through. */
1570
+ request;
1571
+ /** The platform API map, exposed through `bot.internal`. */
1572
+ internal;
1573
+ webhook;
1574
+ constructor(ctx, config) {
1575
+ super(ctx, config, {
1576
+ id: `whatsapp:${config.phoneNumberId}`,
1577
+ platform: "whatsapp",
1578
+ adapter: "whatsapp"
1579
+ });
1580
+ this.selfId = config.phoneNumberId;
1581
+ this.request = new WhatsAppRequest(ctx, config);
1582
+ this.internal = new Internal(this.request);
1583
+ this.modes = { text: createTextMode(config) };
1584
+ this.defineInternalRoute("/assets/:mediaId", async ({ params }) => serveMedia(this, params.mediaId));
1585
+ }
1586
+ async connect() {
1587
+ const invalid = configError(this.config);
1588
+ if (invalid !== void 0) {
1589
+ this.ctx.logger.error("whatsapp: connect failed: %s", invalid.message);
1590
+ throw invalid;
1591
+ }
1592
+ const webServer = this.ctx.get("webServer");
1593
+ if (webServer === void 0) {
1594
+ const error = /* @__PURE__ */ new Error("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");
1595
+ this.ctx.logger.error(error.message);
1596
+ throw error;
1597
+ }
1598
+ try {
1599
+ const info = await fetchPhoneNumber(this.request, this.config.phoneNumberId);
1600
+ this.selfId = verifyIdentity(this.config.phoneNumberId, info);
1601
+ this.user = userOf(info);
1602
+ const webhook = new WhatsappWebhook(this, webServer);
1603
+ webhook.start();
1604
+ this.webhook = webhook;
1605
+ this.online();
1606
+ } catch (error) {
1607
+ this.ctx.logger.error("whatsapp: connect failed: %s", messageOf(error));
1608
+ throw error;
1609
+ }
1610
+ }
1611
+ async disconnect() {
1612
+ const webhook = this.webhook;
1613
+ this.webhook = void 0;
1614
+ webhook?.stop();
1615
+ }
1616
+ /**
1617
+ * Turn one outbound attachment into the media id a message carries.
1618
+ *
1619
+ * The Cloud API uploads the bytes first and sends the message by id afterwards, so no staging is involved. A type
1620
+ * outside the platform's documented list is refused here instead of being dropped silently: the receipt has to say
1621
+ * that this attachment was not sent.
1622
+ */
1623
+ async upload(ref, _scope, ctx) {
1624
+ let fetched;
1625
+ try {
1626
+ fetched = await ctx.fetch(ref.src, ctx.signal);
1627
+ } catch (error) {
1628
+ if (ctx.signal.aborted) throw error;
1629
+ throw new PlatformError("invalid", `whatsapp: media source ${ref.src} could not be read: ${messageOf(error)}`, {
1630
+ published: "no",
1631
+ cause: error
1632
+ });
1633
+ }
1634
+ const mime = ref.meta.mime ?? fetched.mime;
1635
+ const name = ref.meta.name ?? fetched.name ?? "file";
1636
+ if (mime === void 0 || !SUPPORTED_MEDIA.includes(mime)) throw new PlatformError("invalid", `whatsapp: the platform does not accept ${mime ?? "an unspecified media type"} (${ref.src}); supported types are ${SUPPORTED_MEDIA.join(", ")}`, {
1637
+ code: "whatsapp-unsupported-media-type",
1638
+ published: "no"
1639
+ });
1640
+ const form = new FormData();
1641
+ form.append("file", new Blob([fetched.data], { type: mime }), name);
1642
+ form.append("type", mime);
1643
+ form.append("messaging_product", "whatsapp");
1644
+ return {
1645
+ key: (await this.internal.uploadMedia(this.selfId, form)).id,
1646
+ extra: {
1647
+ name,
1648
+ mime,
1649
+ size: fetched.data.byteLength
1650
+ }
1651
+ };
1652
+ }
1653
+ resourceScope(_target, _kind) {
1654
+ return this.id;
1655
+ }
1656
+ async sendPayload(payload, target, ctx) {
1657
+ return await this.call(() => sendPayload(this.deps(), payload, target, ctx));
1658
+ }
1659
+ async createReaction(message, emoji) {
1660
+ await this.call(() => createReaction(this.deps(), message, emoji));
1661
+ }
1662
+ async deleteReaction(message, emoji) {
1663
+ await this.call(() => deleteReaction(this.deps(), message, emoji));
1664
+ }
1665
+ classify(error) {
1666
+ return classifyWhatsappError(error);
1667
+ }
1668
+ deps() {
1669
+ return {
1670
+ selfId: this.selfId,
1671
+ internal: this.internal
1672
+ };
1673
+ }
1674
+ /**
1675
+ * Run one outbound call, naming a revoked token in the log.
1676
+ *
1677
+ * A token rejected at runtime (`190`) leaves the webhook working while every send fails, and nothing else surfaces
1678
+ * that state: the request itself only reaches the caller of this send.
1679
+ *
1680
+ * @param operation - the outbound call.
1681
+ * @returns what the call answered.
1682
+ */
1683
+ async call(operation) {
1684
+ try {
1685
+ return await operation();
1686
+ } catch (error) {
1687
+ if (error instanceof WhatsappApiError && error.code === 190) this.ctx.logger.error("whatsapp: the system user token was rejected; webhook intake continues but every send fails: %s", error.message);
1688
+ throw error;
1689
+ }
1690
+ }
1691
+ };
1692
+ export { Config, Internal, SIGNATURE_HEADER, SUPPORTED_MEDIA, WHATSAPP_LIMITS, WhatsAppRequest, WhatsappApiError, WhatsappBot, WhatsappBot as default, WhatsappIdentityError, WhatsappWebhook, assembleDraft, chatRefOf, checkDraft, classifyWhatsappError, configError, constantTimeEqual, contextOf, createReaction, createTextMode, decodeChange, decodeInteractive, decodeMessage, decodeReaction, decodeTemplateButton, deleteReaction, fetchPhoneNumber, matchesSignature, reportMovedMedia, routePath, sendPayload, senderOf, serializeDraft, serveMedia, signatureOf, splitText, timeOf, userOf, verifyIdentity };
1693
+
1694
+ //# sourceMappingURL=index.js.map