@kyyinfinite/zapo-message 0.0.0-stage → 1.0.1

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 (191) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/LICENSE +20 -0
  3. package/README.md +1401 -2
  4. package/build.config.json +28 -0
  5. package/dist/airich/airich.d.ts +180 -0
  6. package/dist/airich/airich.js +548 -0
  7. package/dist/airich/context.d.ts +24 -0
  8. package/dist/airich/context.js +48 -0
  9. package/dist/airich/encode.d.ts +3 -0
  10. package/dist/airich/encode.js +16 -0
  11. package/dist/airich/index.d.ts +20 -0
  12. package/dist/airich/index.js +11 -0
  13. package/dist/airich/inline.d.ts +45 -0
  14. package/dist/airich/inline.js +152 -0
  15. package/dist/airich/nodes.d.ts +30 -0
  16. package/dist/airich/nodes.js +121 -0
  17. package/dist/airich/primitives.d.ts +144 -0
  18. package/dist/airich/primitives.js +230 -0
  19. package/dist/airich/protocol.d.ts +35 -0
  20. package/dist/airich/protocol.js +65 -0
  21. package/dist/airich/table.d.ts +22 -0
  22. package/dist/airich/table.js +35 -0
  23. package/dist/airich/tokenizer.d.ts +13 -0
  24. package/dist/airich/tokenizer.js +717 -0
  25. package/dist/airich/transport.d.ts +15 -0
  26. package/dist/airich/transport.js +56 -0
  27. package/dist/branding.d.ts +5 -0
  28. package/dist/branding.js +9 -0
  29. package/dist/btn/builders.d.ts +246 -0
  30. package/dist/btn/builders.js +710 -0
  31. package/dist/btn/media-slot.d.ts +28 -0
  32. package/dist/btn/media-slot.js +323 -0
  33. package/dist/btn/media-source.d.ts +36 -0
  34. package/dist/btn/media-source.js +116 -0
  35. package/dist/btn/sharp-loader.d.ts +5 -0
  36. package/dist/btn/sharp-loader.js +18 -0
  37. package/dist/btn/thumbnail.d.ts +21 -0
  38. package/dist/btn/thumbnail.js +124 -0
  39. package/dist/btn/validators.d.ts +40 -0
  40. package/dist/btn/validators.js +135 -0
  41. package/dist/btn.d.ts +1 -0
  42. package/dist/btn.js +1 -0
  43. package/dist/core/async-send.d.ts +20 -0
  44. package/dist/core/async-send.js +1 -0
  45. package/dist/core/base-builder.d.ts +20 -0
  46. package/dist/core/base-builder.js +67 -0
  47. package/dist/core/errors.d.ts +30 -0
  48. package/dist/core/errors.js +61 -0
  49. package/dist/download.d.ts +24 -0
  50. package/dist/download.js +123 -0
  51. package/dist/index.d.ts +38 -0
  52. package/dist/index.js +22 -0
  53. package/dist/integration/augment.d.ts +97 -0
  54. package/dist/integration/augment.js +1 -0
  55. package/dist/integration/auto.d.ts +8 -0
  56. package/dist/integration/auto.js +79 -0
  57. package/dist/integration/index.d.ts +4 -0
  58. package/dist/integration/index.js +2 -0
  59. package/dist/integration/methods.d.ts +25 -0
  60. package/dist/integration/methods.js +24 -0
  61. package/dist/interactive.d.ts +24 -0
  62. package/dist/interactive.js +121 -0
  63. package/dist/media-gate.d.ts +99 -0
  64. package/dist/media-gate.js +322 -0
  65. package/dist/message/album.d.ts +33 -0
  66. package/dist/message/album.js +107 -0
  67. package/dist/message/contact.d.ts +29 -0
  68. package/dist/message/contact.js +123 -0
  69. package/dist/message/forward.d.ts +23 -0
  70. package/dist/message/forward.js +77 -0
  71. package/dist/message/index.d.ts +26 -0
  72. package/dist/message/index.js +13 -0
  73. package/dist/message/link-preview.d.ts +28 -0
  74. package/dist/message/link-preview.js +98 -0
  75. package/dist/message/location.d.ts +24 -0
  76. package/dist/message/location.js +94 -0
  77. package/dist/message/media.d.ts +90 -0
  78. package/dist/message/media.js +123 -0
  79. package/dist/message/poll.d.ts +24 -0
  80. package/dist/message/poll.js +98 -0
  81. package/dist/message/reaction.d.ts +20 -0
  82. package/dist/message/reaction.js +71 -0
  83. package/dist/message/sticker.d.ts +29 -0
  84. package/dist/message/sticker.js +44 -0
  85. package/dist/message/target.d.ts +18 -0
  86. package/dist/message/target.js +24 -0
  87. package/dist/message/text.d.ts +17 -0
  88. package/dist/message/text.js +29 -0
  89. package/dist/message/vcard.d.ts +9 -0
  90. package/dist/message/vcard.js +23 -0
  91. package/dist/message/webp.d.ts +6 -0
  92. package/dist/message/webp.js +57 -0
  93. package/dist/payloads.d.ts +180 -0
  94. package/dist/payloads.js +1 -0
  95. package/dist/serialize.d.ts +41 -0
  96. package/dist/serialize.js +93 -0
  97. package/dist/status.d.ts +3 -0
  98. package/dist/status.js +21 -0
  99. package/dist/zapo-client.d.ts +44 -0
  100. package/dist/zapo-client.js +1 -0
  101. package/examples/airich.ts +59 -0
  102. package/examples/buttons.ts +48 -0
  103. package/examples/client-methods.ts +58 -0
  104. package/examples/hybrid.ts +133 -0
  105. package/examples/serialize.ts +61 -0
  106. package/package.json +271 -4
  107. package/scripts/check-no-comments.mjs +101 -0
  108. package/scripts/compare-golden.mjs +461 -0
  109. package/scripts/lib-config.mjs +9 -0
  110. package/scripts/smoke-auto.mjs +75 -0
  111. package/scripts/test-external-consumer.mjs +316 -0
  112. package/scripts/verify-package.mjs +78 -0
  113. package/src/airich/airich.ts +970 -0
  114. package/src/airich/context.ts +96 -0
  115. package/src/airich/encode.ts +25 -0
  116. package/src/airich/index.ts +98 -0
  117. package/src/airich/inline.ts +272 -0
  118. package/src/airich/nodes.ts +174 -0
  119. package/src/airich/primitives.ts +474 -0
  120. package/src/airich/protocol.ts +133 -0
  121. package/src/airich/table.ts +70 -0
  122. package/src/airich/tokenizer.ts +799 -0
  123. package/src/airich/transport.ts +106 -0
  124. package/src/branding.ts +23 -0
  125. package/src/btn/builders.ts +1073 -0
  126. package/src/btn/media-slot.ts +486 -0
  127. package/src/btn/media-source.ts +189 -0
  128. package/src/btn/sharp-loader.ts +23 -0
  129. package/src/btn/thumbnail.ts +182 -0
  130. package/src/btn/validators.ts +237 -0
  131. package/src/btn.ts +8 -0
  132. package/src/core/async-send.ts +28 -0
  133. package/src/core/base-builder.ts +104 -0
  134. package/src/core/errors.ts +82 -0
  135. package/src/download.ts +212 -0
  136. package/src/index.ts +229 -0
  137. package/src/integration/augment.ts +262 -0
  138. package/src/integration/auto.ts +103 -0
  139. package/src/integration/index.ts +8 -0
  140. package/src/integration/methods.ts +45 -0
  141. package/src/interactive.ts +188 -0
  142. package/src/media-gate.ts +499 -0
  143. package/src/message/album.ts +187 -0
  144. package/src/message/contact.ts +170 -0
  145. package/src/message/forward.ts +123 -0
  146. package/src/message/index.ts +83 -0
  147. package/src/message/link-preview.ts +148 -0
  148. package/src/message/location.ts +150 -0
  149. package/src/message/media.ts +323 -0
  150. package/src/message/poll.ts +158 -0
  151. package/src/message/reaction.ts +133 -0
  152. package/src/message/sticker.ts +100 -0
  153. package/src/message/target.ts +38 -0
  154. package/src/message/text.ts +61 -0
  155. package/src/message/vcard.ts +36 -0
  156. package/src/message/webp.ts +78 -0
  157. package/src/payloads.ts +204 -0
  158. package/src/serialize.ts +180 -0
  159. package/src/status.ts +29 -0
  160. package/src/zapo-client.ts +84 -0
  161. package/test/airich-inline.test.ts +200 -0
  162. package/test/airich-primitives.test.ts +226 -0
  163. package/test/airich-tokenizer.test.ts +145 -0
  164. package/test/airich.golden.test.ts +406 -0
  165. package/test/airich.test.ts +1006 -0
  166. package/test/btn-button.test.ts +416 -0
  167. package/test/btn-header.test.ts +646 -0
  168. package/test/btn-legacy.test.ts +342 -0
  169. package/test/btn-lifecycle.test.ts +295 -0
  170. package/test/btn-list.test.ts +261 -0
  171. package/test/btn-media-source.test.ts +150 -0
  172. package/test/btn-thumbnail.test.ts +160 -0
  173. package/test/builder-compat.test.ts +264 -0
  174. package/test/helpers.ts +27 -0
  175. package/test/hybrid-airich.test.ts +345 -0
  176. package/test/hybrid-client.test.ts +239 -0
  177. package/test/hybrid-errors.test.ts +557 -0
  178. package/test/hybrid-interactive.test.ts +455 -0
  179. package/test/hybrid.golden.test.ts +349 -0
  180. package/test/hybrid.test.ts +479 -0
  181. package/test/integration-auto.test.ts +159 -0
  182. package/test/integration.fakeserver.test.ts +440 -0
  183. package/test/media-gate.test.ts +215 -0
  184. package/test/message-album.test.ts +145 -0
  185. package/test/message-builders.test.ts +401 -0
  186. package/test/message-media.test.ts +303 -0
  187. package/test/message.fakeserver.test.ts +284 -0
  188. package/test/message.golden.test.ts +254 -0
  189. package/test/serializer.test.ts +448 -0
  190. package/tsconfig.json +26 -0
  191. package/tsconfig.test.json +10 -0
package/README.md CHANGED
@@ -1,3 +1,1402 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # `@kyyinfinite/zapo-message`
4
+
5
+ **A practical message toolkit for ZapoJS.**
6
+
7
+ Build WhatsApp messages with a small, consistent API • use a typed config object or a fluent builder, backed by the same message pipeline.
8
+
9
+ [![npm version](https://img.shields.io/npm/v/%40kyyinfinite%2Fzapo-message?style=flat-square&logo=npm&color=cb3837)](https://www.npmjs.com/package/@kyyinfinite/zapo-message)
10
+ [![Node.js](https://img.shields.io/badge/Node.js-%E2%89%A520.9-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-supported-3178c6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
12
+ [![License: ISC](https://img.shields.io/badge/License-ISC-blue?style=flat-square)](LICENSE)
13
+
14
+ [Getting started](#-getting-started) · [API reference](#-api-reference) · [Payloads](#-message-payloads) · [Troubleshooting](#-troubleshooting) · [FAQ](#-faq)
15
+
16
+ </div>
17
+
18
+ ---
19
+
20
+ ## ✨ What it does
21
+
22
+ `@kyyinfinite/zapo-message` adds message builders to [ZapoJS](https://www.npmjs.com/package/zapo-js). It covers everyday messages, interactive messages, media, and AIRich responses without making you assemble protocol payloads by hand.
23
+
24
+ The package is designed around one simple idea: **one message type, two ways to call it, one implementation**.
25
+
26
+ - **Object API** • pass a typed configuration object and await the result.
27
+ - **Fluent API** • configure a builder step by step and call `.send()`.
28
+ - **Shared execution path** • both styles use the same builder, validation, payload construction, media resolution, and transport path.
29
+ - **ZapoJS integration** • import the package once and use the methods on `WaClient`.
30
+ - **Standalone factories** • use exported factories when you prefer not to patch a client prototype.
31
+
32
+ ```ts
33
+ import { createStore, WaClient } from "zapo-js";
34
+ import "@kyyinfinite/zapo-message";
35
+
36
+ const client = new WaClient({
37
+ store: createStore({}),
38
+ sessionId: "my-bot",
39
+ });
40
+
41
+ await client.connect();
42
+
43
+ const jid = "628123456789@s.whatsapp.net";
44
+
45
+ await client.text(jid, { body: "Hello from Zapo Message" });
46
+ await client.text().to(jid).body("Same message, fluent style").send();
47
+ ```
48
+
49
+ ## 📦 Installation
50
+
51
+ ```bash
52
+ npm install @kyyinfinite/zapo-message zapo-js
53
+ ```
54
+
55
+ Optional image processing support:
56
+
57
+ ```bash
58
+ npm install sharp
59
+ ```
60
+
61
+ ### Requirements
62
+
63
+ | Requirement | Version / notes |
64
+ | --- | --- |
65
+ | Node.js | `>=20.9.0` |
66
+ | ZapoJS | Peer dependency `>=1.11.0 <2.0.0` |
67
+ | TypeScript | Supported through published declaration files |
68
+ | `sharp` | Optional peer dependency; used for image processing and automatic thumbnail generation |
69
+
70
+ `file-type` is installed as a regular dependency and is used to detect media types from file contents.
71
+
72
+ ## 🚀 Getting started
73
+
74
+ ### 1. Import the integration
75
+
76
+ ```ts
77
+ import { createStore, WaClient } from "zapo-js";
78
+ import "@kyyinfinite/zapo-message";
79
+
80
+ const client = new WaClient({
81
+ store: createStore({}),
82
+ sessionId: "my-bot",
83
+ });
84
+
85
+ await client.connect();
86
+ ```
87
+
88
+ The package installs its methods on the `WaClient` prototype when the root package is imported. The integration skips names that already exist on the prototype and uses a marker to avoid installing the same methods twice.
89
+
90
+ ### 2. Send a message
91
+
92
+ ```ts
93
+ const jid = "628123456789@s.whatsapp.net";
94
+
95
+ await client.text(jid, { body: "Hello!" });
96
+ ```
97
+
98
+ Or use a builder:
99
+
100
+ ```ts
101
+ await client
102
+ .text()
103
+ .to(jid)
104
+ .body("Hello!")
105
+ .send();
106
+ ```
107
+
108
+ ### 3. Handle incoming messages
109
+
110
+ ```ts
111
+ client.on("message", async (event) => {
112
+ const jid = event.key.remoteJid;
113
+ if (!jid) return;
114
+
115
+ if (event.message?.conversation === "ping") {
116
+ await client.text(jid, { body: "pong" });
117
+ }
118
+ });
119
+ ```
120
+
121
+ Connect the client according to your application's lifecycle and disconnect it when the process is shutting down.
122
+
123
+ ## 🔀 The hybrid API
124
+
125
+ Every integrated method has a builder form. Most methods also have a config-object form that sends immediately.
126
+
127
+ ### Object API
128
+
129
+ ```ts
130
+ await client.text(jid, { body: "Hello" });
131
+
132
+ await client.button(jid, {
133
+ body: "Choose an action",
134
+ buttons: [
135
+ { type: "quick_reply", text: "Open menu", id: "menu" },
136
+ { type: "cta_url", text: "Website", url: "https://example.com" },
137
+ ],
138
+ });
139
+ ```
140
+
141
+ ### Fluent API
142
+
143
+ ```ts
144
+ await client.text().to(jid).body("Hello").send();
145
+
146
+ await client
147
+ .button()
148
+ .to(jid)
149
+ .body("Choose an action")
150
+ .quick_reply("Open menu", "menu")
151
+ .cta_url("Website", "https://example.com")
152
+ .send();
153
+ ```
154
+
155
+ ### How targets are resolved
156
+
157
+ A builder can receive its destination in either of these ways:
158
+
159
+ ```ts
160
+ await client.text().body("Hello").send(jid);
161
+
162
+ await client.text().to(jid).body("Hello").send();
163
+
164
+ await client.text().defaultTo(jid).body("Hello").send();
165
+ ```
166
+
167
+ `.to(jid)` is an alias for `.defaultTo(jid)`. A destination passed to `.send(jid)` takes precedence over the builder's default destination.
168
+
169
+ The client is bound automatically when a builder is created through `client.method()`. Standalone factories can bind the client explicitly; see [Standalone factories](#standalone-factories).
170
+
171
+ ### Send options
172
+
173
+ The object API accepts a third argument for send options. The fluent API accepts the same options as the second argument to `.send()`.
174
+
175
+ ```ts
176
+ await client.text(
177
+ jid,
178
+ { body: "Replying to your message" },
179
+ { quote: incomingEvent },
180
+ );
181
+
182
+ await client
183
+ .text()
184
+ .body("Replying to your message")
185
+ .send(jid, { quote: incomingEvent });
186
+ ```
187
+
188
+ `MessageSendOptions` currently exposes:
189
+
190
+ | Option | Type | Purpose |
191
+ | --- | --- | --- |
192
+ | `quote` | `unknown` | Message reference to quote; interpreted by ZapoJS transport |
193
+ | `mentions` | `readonly string[]` | Mention JIDs |
194
+ | `contextInfo` | `Record<string, unknown>` | Additional message context |
195
+ | `forward` | `boolean \| { score?: number }` | Forwarding metadata where supported |
196
+ | `id` | `string` | Message ID option passed to the transport |
197
+ | `expirationSeconds` | `number` | Expiration option passed to the transport |
198
+ | `additionalAttributes` | `Readonly<Record<string, string>>` | Additional transport attributes |
199
+ | `viewOnce` | `boolean` | View-once option passed to the transport |
200
+ | `messageSecret` | `Uint8Array` | Message secret passed to the transport |
201
+ | `ackTimeoutMs` | `number` | Acknowledgement timeout passed to the transport |
202
+ | `maxAttempts` | `number` | Maximum send attempts passed to the transport |
203
+ | `retryDelayMs` | `number` | Retry delay passed to the transport |
204
+
205
+ The package forwards these options to `client.message.send()`. The exact effect of transport-level options depends on the installed ZapoJS version.
206
+
207
+ > **Reaction exception:** `reaction()` accepts a config object without a JID because the target chat can be resolved from `config.target`. You can still pass a JID explicitly when needed.
208
+
209
+ ## 📚 API reference
210
+
211
+ All methods below are installed on `WaClient` by the root import. The same factories are exported from the package root.
212
+
213
+ | Method | Object API | Fluent builder | Message payload family |
214
+ | --- | --- | --- | --- |
215
+ | `text` | `text(jid, config, options?)` | `text()` | `conversation` |
216
+ | `button` | `button(jid, config, options?)` | `button()` | `interactiveMessage` |
217
+ | `legacyButton` | `legacyButton(jid, config, options?)` | `legacyButton()` | `buttonsMessage` |
218
+ | `listMessage` | `listMessage(jid, config, options?)` | `listMessage()` | `listMessage` or native-flow fallback |
219
+ | `airich` | `airich(jid, config, options?)` | `airich(options?)` | `botForwardedMessage` / `richResponseMessage` |
220
+ | `linkPreview` | `linkPreview(jid, config, options?)` | `linkPreview()` | `extendedTextMessage` |
221
+ | `media` | `media(jid, config, options?)` | `media()` | image, video, audio, or document message |
222
+ | `image` | `image(jid, config, options?)` | `image()` | image message |
223
+ | `video` | `video(jid, config, options?)` | `video()` | video message |
224
+ | `audio` | `audio(jid, config, options?)` | `audio()` | audio message |
225
+ | `document` | `document(jid, config, options?)` | `document()` | document message |
226
+ | `sticker` | `sticker(jid, config, options?)` | `sticker()` | sticker message |
227
+ | `contact` | `contact(jid, config, options?)` | `contact()` | `contactMessage` |
228
+ | `poll` | `poll(jid, config, options?)` | `poll()` | ZapoJS poll input |
229
+ | `album` | `album(jid, config, options?)` | `album()` | album message followed by media messages |
230
+ | `reaction` | `reaction(config, options?)` or `reaction(jid, config, options?)` | `reaction()` | ZapoJS reaction input |
231
+ | `forward` | `forward(jid, config, options?)` | `forward()` | original message with forward options |
232
+ | `location` | `location(jid, config, options?)` | `location()` | `locationMessage` |
233
+
234
+ ### Text
235
+
236
+ **Config**
237
+
238
+ ```ts
239
+ interface TextConfig {
240
+ body: string;
241
+ }
242
+ ```
243
+
244
+ ```ts
245
+ await client.text(jid, { body: "Hello there" });
246
+ await client.text().body("Hello there").send(jid);
247
+ ```
248
+
249
+ **Built payload**
250
+
251
+ ```ts
252
+ { conversation: "Hello there" }
253
+ ```
254
+
255
+ ### Native flow buttons
256
+
257
+ Use `button()` for interactive native-flow messages.
258
+
259
+ **Config shape**
260
+
261
+ ```ts
262
+ interface ButtonConfig {
263
+ title?: string;
264
+ subtitle?: string;
265
+ body: string;
266
+ footer?: string;
267
+ header?: InteractiveHeaderConfig;
268
+ buttons?: readonly ButtonItemConfig[];
269
+ bottomSheet?: {
270
+ limit?: number;
271
+ listTitle?: string;
272
+ buttonTitle?: string;
273
+ };
274
+ limitedTimeOffer?: {
275
+ text?: string;
276
+ url?: string;
277
+ copyCode?: string;
278
+ expiresIn?: number;
279
+ };
280
+ }
281
+
282
+ type ButtonItemConfig =
283
+ | { type: "quick_reply"; text: string; id: string }
284
+ | { type: "cta_url"; text: string; url: string }
285
+ | { type: "cta_copy"; text: string; copyCode: string }
286
+ | { type: "cta_call"; text: string; phoneNumber: string }
287
+ | { type: "send_location"; text?: string }
288
+ | {
289
+ type: "single_select";
290
+ title: string;
291
+ sections: readonly NativeSection[];
292
+ };
293
+ ```
294
+
295
+ `InteractiveHeaderConfig` supports:
296
+
297
+ - `{ type: "image", source, ...imageOptions }`
298
+ - `{ type: "video", source, ...videoOptions }`
299
+ - `{ type: "document", source, ...documentOptions }`
300
+ - `{ type: "location", latitude, longitude, name?, address?, thumbnail? }`
301
+ - `{ type: "thumbnail", jpegThumbnail }`
302
+
303
+ **Object API**
304
+
305
+ ```ts
306
+ await client.button(jid, {
307
+ title: "Account",
308
+ subtitle: "Manage your profile",
309
+ body: "What would you like to do?",
310
+ footer: "Example bot",
311
+ buttons: [
312
+ { type: "quick_reply", text: "My profile", id: "profile" },
313
+ { type: "cta_url", text: "Open website", url: "https://example.com" },
314
+ { type: "cta_copy", text: "Copy code", copyCode: "WELCOME" },
315
+ { type: "cta_call", text: "Call support", phoneNumber: "+628123456789" },
316
+ { type: "send_location", text: "Share location" },
317
+ {
318
+ type: "single_select",
319
+ title: "More options",
320
+ sections: [
321
+ {
322
+ title: "Account",
323
+ rows: [{ id: "settings", title: "Settings" }],
324
+ },
325
+ ],
326
+ },
327
+ ],
328
+ });
329
+ ```
330
+
331
+ **Fluent API**
332
+
333
+ ```ts
334
+ await client
335
+ .button()
336
+ .to(jid)
337
+ .title("Account")
338
+ .subtitle("Manage your profile")
339
+ .body("What would you like to do?")
340
+ .quick_reply("My profile", "profile")
341
+ .cta_url("Open website", "https://example.com")
342
+ .cta_copy("Copy code", "WELCOME")
343
+ .cta_call("Call support", "+628123456789")
344
+ .send_location("Share location")
345
+ .single_select("More options", [
346
+ { title: "Account", rows: [{ id: "settings", title: "Settings" }] },
347
+ ])
348
+ .footer("Example bot")
349
+ .send();
350
+ ```
351
+
352
+ The fluent button builder also supports these header and layout methods:
353
+
354
+ | Method | Purpose |
355
+ | --- | --- |
356
+ | `.image(source, options?)` | Image header |
357
+ | `.video(source, options?)` | Video header |
358
+ | `.document(source, options?)` | Document header |
359
+ | `.location({ latitude, longitude, name?, address?, thumbnail? })` | Location header |
360
+ | `.thumb(bytes?)` | Location thumbnail |
361
+ | `.headerThumbnail(jpegBytes)` | JPEG header thumbnail |
362
+ | `.bottom_sheet(options?)` | Native-flow bottom-sheet parameters |
363
+ | `.limited_time_offer(options?)` | Limited-time offer metadata |
364
+
365
+ `bottom_sheet()` accepts `limit`, `listTitle`, and `buttonTitle`. `limited_time_offer()` accepts `text`, `url`, `copyCode`, and `expiresIn` (seconds). A button header can contain one content type at a time; media, location, and thumbnail header methods are mutually exclusive where enforced by the builder.
366
+
367
+ **Built payload family**
368
+
369
+ ```ts
370
+ {
371
+ interactiveMessage: {
372
+ body: { text: "..." },
373
+ nativeFlowMessage: {
374
+ buttons: [
375
+ {
376
+ name: "quick_reply",
377
+ buttonParamsJson: "{\"display_text\":\"Open\",\"id\":\"open\"}"
378
+ }
379
+ ],
380
+ messageVersion: 1
381
+ },
382
+ footer: { text: "..." }
383
+ }
384
+ }
385
+ ```
386
+
387
+ Each native-flow button is encoded into `buttonParamsJson`. The package owns this encoding; pass the documented config rather than constructing the JSON string yourself.
388
+
389
+ ### Legacy buttons
390
+
391
+ Use `legacyButton()` when you specifically need the older `buttonsMessage` payload format.
392
+
393
+ **Config**
394
+
395
+ ```ts
396
+ interface LegacyButtonConfig {
397
+ title?: string;
398
+ body: string;
399
+ footer?: string;
400
+ header?: LegacyButtonHeaderConfig;
401
+ buttons: readonly { id: string; text: string }[];
402
+ }
403
+ ```
404
+
405
+ ```ts
406
+ await client.legacyButton(jid, {
407
+ title: "Quick menu",
408
+ body: "Choose one",
409
+ footer: "Example bot",
410
+ buttons: [
411
+ { id: "help", text: "Help" },
412
+ { id: "about", text: "About" },
413
+ ],
414
+ });
415
+
416
+ await client
417
+ .legacyButton()
418
+ .to(jid)
419
+ .body("Choose one")
420
+ .button("help", "Help")
421
+ .button("about", "About")
422
+ .send();
423
+ ```
424
+
425
+ **Built payload family**
426
+
427
+ ```ts
428
+ {
429
+ buttonsMessage: {
430
+ contentText: "Choose one",
431
+ buttons: [
432
+ {
433
+ buttonId: "help",
434
+ buttonText: { displayText: "Help" },
435
+ type: "RESPONSE"
436
+ }
437
+ ],
438
+ headerType: "...",
439
+ footerText: "Example bot"
440
+ }
441
+ }
442
+ ```
443
+
444
+ The implementation allows up to three legacy buttons and validates button IDs. Keep IDs unique and within the limits enforced by the library.
445
+
446
+ ### List messages
447
+
448
+ **Config**
449
+
450
+ ```ts
451
+ interface ListRowInput {
452
+ id: string;
453
+ title: string;
454
+ description?: string;
455
+ header?: string;
456
+ }
457
+
458
+ interface ListMessageConfig {
459
+ title?: string;
460
+ body: string;
461
+ footer?: string;
462
+ buttonText: string;
463
+ sections: readonly {
464
+ title?: string;
465
+ rows: readonly ListRowInput[];
466
+ }[];
467
+ fallback?: "auto" | "native" | "never";
468
+ inGroup?: boolean;
469
+ }
470
+ ```
471
+
472
+ ```ts
473
+ await client.listMessage(jid, {
474
+ title: "Main menu",
475
+ body: "Choose a category",
476
+ footer: "Example bot",
477
+ buttonText: "Browse",
478
+ sections: [
479
+ {
480
+ title: "General",
481
+ rows: [
482
+ { id: "profile", title: "Profile", description: "Your account" },
483
+ { id: "settings", title: "Settings" },
484
+ ],
485
+ },
486
+ ],
487
+ });
488
+ ```
489
+
490
+ ```ts
491
+ await client
492
+ .listMessage()
493
+ .to(jid)
494
+ .title("Main menu")
495
+ .body("Choose a category")
496
+ .buttonText("Browse")
497
+ .section("General", [
498
+ { id: "profile", title: "Profile", description: "Your account" },
499
+ { id: "settings", title: "Settings" },
500
+ ])
501
+ .send();
502
+ ```
503
+
504
+ **Built payload family**
505
+
506
+ ```ts
507
+ {
508
+ listMessage: {
509
+ title: "Main menu",
510
+ description: "Choose a category",
511
+ buttonText: "Browse",
512
+ listType: "...",
513
+ sections: [{ title: "General", rows: [{ rowId: "profile", title: "Profile" }] }],
514
+ footerText: "Example bot"
515
+ }
516
+ }
517
+ ```
518
+
519
+ The builder supports `fallback("auto" | "native" | "never")` and `inGroup(boolean)`. In automatic mode, the implementation can convert a list to a native-flow `single_select` for group delivery. Choose `native` to force that path or `never` to disable the fallback.
520
+
521
+ ### AIRich
522
+
523
+ AIRich builds rich-response messages from typed sections. The builder also supports node operations and a two-step placeholder/edit send flow.
524
+
525
+ **Config section types**
526
+
527
+ | `type` | Required fields | Optional fields |
528
+ | --- | --- | --- |
529
+ | `text` | `text` | `hyperlink`, `citation`, `latex`, `id` |
530
+ | `code` | `language`, `code` | `id` |
531
+ | `table` | `rows: string[][]` | `hyperlink`, `citation`, `latex`, `id` |
532
+ | `metadata` | `text` | `id` |
533
+ | `tip` | `text` | `id` |
534
+ | `suggest` | `items: string \| readonly string[]` | `scroll`, `layout`, `id` |
535
+ | `source` | `sources` | `layout`, `id` |
536
+ | `image` | `url` | `width`, `height`, `status`, `updateText`, `id` |
537
+ | `video` | `url` | `mimeType`, `fileLength`, `duration`, `status`, `id` |
538
+ | `footerAction` | `items` | `layout`, `id` |
539
+ | `widget` | `items` | `layout`, `id` |
540
+ | `product` | `items` | `layout`, `id` |
541
+ | `post` | `items` | `layout`, `id` |
542
+ | `reels` | `items` | `layout`, `id` |
543
+ | `html` | `html` | `trustedSources`, `id` |
544
+ | `raw` | `section` | `submessage`, `id` |
545
+
546
+ **Config API**
547
+
548
+ ```ts
549
+ await client.airich(jid, {
550
+ sections: [
551
+ { type: "text", text: "Order summary" },
552
+ { type: "code", language: "javascript", code: "const total = 25000" },
553
+ {
554
+ type: "table",
555
+ rows: [
556
+ ["Item", "Qty"],
557
+ ["Coffee", "2"],
558
+ ],
559
+ },
560
+ { type: "tip", text: "Your order is ready to review." },
561
+ { type: "suggest", items: ["Track order", "Contact support"] },
562
+ ],
563
+ footer: "Example bot",
564
+ });
565
+ ```
566
+
567
+ **Fluent API**
568
+
569
+ ```ts
570
+ await client
571
+ .airich()
572
+ .text("Order summary")
573
+ .code("javascript", "const total = 25000")
574
+ .table([
575
+ ["Item", "Qty"],
576
+ ["Coffee", "2"],
577
+ ])
578
+ .tip("Your order is ready to review.")
579
+ .suggest(["Track order", "Contact support"])
580
+ .footer("Example bot")
581
+ .send(jid);
582
+ ```
583
+
584
+ Additional fluent methods include `metadata`, `source`, `image`, `video`, `footerAction`, `widget`, `product`, `post`, `reels`, `html`, `raw`, `replace`, `insert`, `insertAt`, `remove`, `clear`, `context`, and `quote`. Node IDs can be supplied through the supported method options and used by node operations.
585
+
586
+ `AIRichSendOptions` extends `MessageSendOptions` with:
587
+
588
+ | Option | Type | Description |
589
+ | --- | --- | --- |
590
+ | `twoStep` | `boolean` | Controls placeholder-then-edit sending |
591
+ | `submessages` | `boolean` | Controls submessage generation |
592
+
593
+ The builder exposes `build()`, `buildPlaceholder()`, `buildEdit()`, `edit(jid, id?)`, `ids()`, `has()`, `pendingEdit(jid)`, `size`, and `lastId` for advanced workflows. `airich({ botJid })` accepts the optional bot JID used in AIRich forwarding context. Two-step sending is enabled by default; set `twoStep: false` to send the complete rich response directly. See the exported TypeScript declarations for the full node and primitive item shapes.
594
+
595
+ **Payload family**
596
+
597
+ ```ts
598
+ {
599
+ botForwardedMessage: {
600
+ message: {
601
+ richResponseMessage: {
602
+ messageType: "...",
603
+ submessages: <rich-response submessages>,
604
+ unifiedResponse: { data: new Uint8Array() },
605
+ contextInfo: {}
606
+ }
607
+ }
608
+ }
609
+ }
610
+ ```
611
+
612
+ AIRich's unified response is encoded by the library. Use `decodeUnifiedResponse()` when you need to inspect encoded unified-response data.
613
+
614
+ #### AIRich primitive inputs
615
+
616
+ The richer primitive builders accept these input shapes:
617
+
618
+ | Method | Input fields |
619
+ | --- | --- |
620
+ | `source()` | A URL string, `[icon, url, title?, subtitle?]`, or `{ favicon?, icon?, url?, title?, subtitle? }` |
621
+ | `image()` | URL plus `{ width?, height?, status?, updateText? }` |
622
+ | `video()` | URL plus `{ mimeType?, fileLength?, duration?, status? }` |
623
+ | `footerAction()` | One or more `{ text?, cta_text?, type?, cta_type?, url?, cta_url? }` objects |
624
+ | `widget()` | `{ title?, header?, sections?, actions?, body? }`; actions accept `{ label?, state?, kind?, tool_call_id?, id?, toast? }` |
625
+ | `product()` | `{ title?, brand?, price?, sale_price?, product_url?, url?, image_url?, image?, icon_url?, icon? }` |
626
+ | `post()` | `{ title?, subtitle?, username?, profile_picture_url?, profile_url?, profile?, is_verified?, verified?, thumbnail_url?, thumbnail?, post_caption?, caption?, likes_count?, like?, comments_count?, comment?, shares_count?, share?, post_url?, url?, post_deeplink?, deeplink?, source_app?, source?, footer_label?, footer?, footer_icon?, icon?, orientation?, post_type? }` |
627
+ | `reels()` | `{ videoUrl?, url?, thumbnailUrl?, thumbnail?, username?, profileIconUrl?, profile?, reels_title?, title?, likes_count?, like?, shares_count?, share?, view_count?, view?, reel_source?, source?, is_verified?, verified? }` |
628
+ | `html()` | HTML string plus `{ trustedSources? }` in the config API |
629
+
630
+ For array-based primitives, the default layout is generally `HScroll`; a single item defaults to `Single`. `source()` defaults to `Single`. You can override the layout using the relevant `layout` option. These rich primitives are marked experimental by the package; their rendering depends on WhatsApp's support for the corresponding protocol primitive.
631
+
632
+ `AIRichConfig.context` is filtered to the supported context fields: `mentionedJid`, `groupMentions`, `statusAttributions`, `expiration`, `ephemeralSettingTimestamp`, and `disappearingMode`. Builder-controlled quote and forwarding fields cannot be overwritten through `context()`.
633
+
634
+ ### Link previews
635
+
636
+ **Config**
637
+
638
+ ```ts
639
+ interface LinkPreviewConfig {
640
+ body: string;
641
+ url?: string;
642
+ title?: string;
643
+ description?: string;
644
+ thumbnail?: Uint8Array;
645
+ kind?: "image" | "video";
646
+ }
647
+ ```
648
+
649
+ ```ts
650
+ await client.linkPreview(jid, {
651
+ body: "Read the guide at https://example.com/docs",
652
+ title: "Documentation",
653
+ description: "Getting started guide",
654
+ kind: "image",
655
+ });
656
+ ```
657
+
658
+ The selected URL must appear in `body`. If `url` is omitted, the builder uses the first HTTP(S) URL it finds in the text.
659
+
660
+ **Built payload**
661
+
662
+ ```ts
663
+ {
664
+ extendedTextMessage: {
665
+ text: "Read the guide at https://example.com/docs",
666
+ matchedText: "https://example.com/docs",
667
+ previewType: "...",
668
+ title: "Documentation",
669
+ description: "Getting started guide",
670
+ jpegThumbnail: new Uint8Array()
671
+ }
672
+ }
673
+ ```
674
+
675
+ ### Media
676
+
677
+ `media()` accepts one media item. Use `album()` when you need multiple images and/or videos in one album sequence.
678
+
679
+ **Supported sources**
680
+
681
+ - `Buffer`
682
+ - `Uint8Array`
683
+ - A local file path
684
+ - A Node.js `Readable` stream
685
+
686
+ **Config types**
687
+
688
+ ```ts
689
+ import type { Readable } from "node:stream";
690
+
691
+ type MediaConfig =
692
+ | { type: "image"; source: Buffer | Uint8Array | string | Readable; mimetype?: string; width?: number; height?: number; caption?: string; thumbnail?: Buffer | Uint8Array | false }
693
+ | { type: "video"; source: Buffer | Uint8Array | string | Readable; mimetype?: string; seconds?: number; width?: number; height?: number; thumbnail?: Buffer | Uint8Array | false }
694
+ | { type: "audio"; source: Buffer | Uint8Array | string | Readable; mimetype?: string; seconds?: number; ptt?: boolean; waveform?: Uint8Array }
695
+ | { type: "document"; source: Buffer | Uint8Array | string | Readable; mimetype?: string; fileName?: string; title?: string; thumbnail?: Buffer | Uint8Array | false };
696
+ ```
697
+
698
+ **Object API**
699
+
700
+ ```ts
701
+ await client.media(jid, {
702
+ type: "image",
703
+ source: "./assets/photo.jpg",
704
+ caption: "A photo",
705
+ });
706
+
707
+ await client.media(jid, {
708
+ type: "document",
709
+ source: pdfBuffer,
710
+ fileName: "report.pdf",
711
+ mimetype: "application/pdf",
712
+ });
713
+ ```
714
+
715
+ **Fluent API**
716
+
717
+ ```ts
718
+ await client.media().image(photoBuffer, { caption: "A photo" }).send(jid);
719
+ await client.media().video(videoPath, { seconds: 18 }).send(jid);
720
+ await client.media().audio(audioBuffer, { ptt: true }).send(jid);
721
+ await client.media().document(pdfBuffer, { fileName: "report.pdf" }).send(jid);
722
+ ```
723
+
724
+ Convenience methods share the same media engine:
725
+
726
+ ```ts
727
+ await client.image(jid, { source: photoBuffer, caption: "A photo" });
728
+ await client.video(jid, { source: videoPath, seconds: 18 });
729
+ await client.audio(jid, { source: audioBuffer, ptt: true });
730
+ await client.document(jid, { source: pdfBuffer, fileName: "report.pdf" });
731
+ ```
732
+
733
+ **Built payload families**
734
+
735
+ The media resolver creates one of these message fields after resolving and uploading the source:
736
+
737
+ ```ts
738
+ imageMessage: <uploaded image metadata>
739
+ videoMessage: <uploaded video metadata>
740
+ audioMessage: <uploaded audio metadata>
741
+ documentMessage: <uploaded document metadata>
742
+ ```
743
+
744
+ The actual media payload includes upload metadata returned by ZapoJS. Do not construct these fields manually. MIME detection is attempted from the source; provide `mimetype` when detection is not possible.
745
+
746
+ ### Stickers
747
+
748
+ Sticker sources must contain WebP data.
749
+
750
+ **Config**
751
+
752
+ ```ts
753
+ interface StickerConfig {
754
+ source: Buffer | Uint8Array | string | Readable;
755
+ mimetype?: string;
756
+ isAnimated?: boolean;
757
+ pngThumbnail?: Uint8Array | false;
758
+ width?: number;
759
+ height?: number;
760
+ stickerSentTs?: number;
761
+ }
762
+ ```
763
+
764
+ ```ts
765
+ await client.sticker(jid, { source: "./assets/sticker.webp" });
766
+ await client.sticker().source(stickerBuffer).send(jid);
767
+ ```
768
+
769
+ **Built payload family**
770
+
771
+ ```ts
772
+ stickerMessage: <uploaded WebP metadata>
773
+ ```
774
+
775
+ The library inspects WebP container data to determine image dimensions and animation metadata. It does not convert arbitrary image formats into WebP for you.
776
+
777
+ ### Polls
778
+
779
+ **Config**
780
+
781
+ ```ts
782
+ interface PollConfig {
783
+ question: string;
784
+ options: readonly string[];
785
+ selectableCount?: number;
786
+ allowAddOption?: boolean;
787
+ hideParticipantName?: boolean;
788
+ }
789
+ ```
790
+
791
+ ```ts
792
+ await client.poll(jid, {
793
+ question: "Which option do you prefer?",
794
+ options: ["Option A", "Option B", "Option C"],
795
+ selectableCount: 1,
796
+ });
797
+
798
+ await client
799
+ .poll()
800
+ .question("Choose two")
801
+ .options(["A", "B", "C"])
802
+ .selectableCount(2)
803
+ .allowAddOption()
804
+ .hideParticipantName()
805
+ .send(jid);
806
+ ```
807
+
808
+ **Input passed to ZapoJS**
809
+
810
+ ```ts
811
+ {
812
+ type: "poll",
813
+ name: "Which option do you prefer?",
814
+ options: ["Option A", "Option B", "Option C"],
815
+ selectableCount: 1,
816
+ }
817
+ ```
818
+
819
+ ZapoJS is responsible for selecting the appropriate poll protocol variant. The library validates that the question is non-empty, that there are 1–12 options, and that `selectableCount` does not exceed the number of options.
820
+
821
+ ### Contacts
822
+
823
+ **Config**
824
+
825
+ ```ts
826
+ interface ContactConfig {
827
+ name?: string;
828
+ phone?: string;
829
+ organization?: string;
830
+ email?: string;
831
+ url?: string;
832
+ note?: string;
833
+ vcard?: string;
834
+ }
835
+ ```
836
+
837
+ Provide either a `vcard` or a `name` with the contact details you want to include.
838
+
839
+ ```ts
840
+ await client.contact(jid, {
841
+ name: "Taylor Smith",
842
+ phone: "+628123456789",
843
+ organization: "Example Studio",
844
+ email: "taylor@example.com",
845
+ url: "https://example.com",
846
+ note: "Project contact",
847
+ });
848
+
849
+ await client
850
+ .contact()
851
+ .name("Taylor Smith")
852
+ .phone("+628123456789")
853
+ .organization("Example Studio")
854
+ .email("taylor@example.com")
855
+ .send(jid);
856
+ ```
857
+
858
+ A raw vCard can also be supplied:
859
+
860
+ ```ts
861
+ await client.contact().vcard(
862
+ "BEGIN:VCARD\nVERSION:3.0\nFN:Taylor Smith\nEND:VCARD",
863
+ ).send(jid);
864
+ ```
865
+
866
+ **Built payload**
867
+
868
+ ```ts
869
+ {
870
+ contactMessage: {
871
+ displayName: "Taylor Smith",
872
+ vcard: "BEGIN:VCARD\\nVERSION:3.0\\n..."
873
+ }
874
+ }
875
+ ```
876
+
877
+ ### Locations
878
+
879
+ **Config**
880
+
881
+ ```ts
882
+ interface LocationConfig {
883
+ latitude: number;
884
+ longitude: number;
885
+ name?: string;
886
+ address?: string;
887
+ thumbnail?: Buffer | Uint8Array;
888
+ }
889
+ ```
890
+
891
+ ```ts
892
+ await client.location(jid, {
893
+ latitude: -6.2,
894
+ longitude: 106.8,
895
+ name: "Jakarta",
896
+ address: "Indonesia",
897
+ });
898
+
899
+ await client
900
+ .location()
901
+ .to(jid)
902
+ .coordinates(-6.2, 106.8)
903
+ .name("Jakarta")
904
+ .address("Indonesia")
905
+ .send();
906
+ ```
907
+
908
+ **Built payload**
909
+
910
+ ```ts
911
+ {
912
+ locationMessage: {
913
+ degreesLatitude: -6.2,
914
+ degreesLongitude: 106.8,
915
+ name: "Jakarta",
916
+ address: "Indonesia"
917
+ }
918
+ }
919
+ ```
920
+
921
+ Latitude must be between `-90` and `90`; longitude must be between `-180` and `180`. This standalone location message is different from a location header on a button and from the `send_location` button, which requests the recipient's location.
922
+
923
+ ### Reactions
924
+
925
+ A reaction needs a message reference with a message ID. The chat JID is read from the reference when available.
926
+
927
+ ```ts
928
+ await client.reaction({ target: incomingEvent, emoji: "🔥" });
929
+
930
+ await client
931
+ .reaction()
932
+ .target(incomingEvent)
933
+ .emoji("🔥")
934
+ .send();
935
+ ```
936
+
937
+ Pass an empty string to remove your reaction:
938
+
939
+ ```ts
940
+ await client.reaction({ target: incomingEvent, emoji: "" });
941
+ ```
942
+
943
+ **Input passed to ZapoJS**
944
+
945
+ ```ts
946
+ {
947
+ type: "reaction",
948
+ target: incomingEvent,
949
+ emoji: "🔥"
950
+ }
951
+ ```
952
+
953
+ If the target does not contain `key.id` (or a supported direct `id`) the builder rejects it.
954
+
955
+ ### Forwarding messages
956
+
957
+ The source must be an incoming event or an object with a `message` field containing a protocol message.
958
+
959
+ ```ts
960
+ await client.forward(jid, { message: incomingEvent });
961
+
962
+ await client
963
+ .forward()
964
+ .message(incomingEvent)
965
+ .send(jid);
966
+ ```
967
+
968
+ The builder forwards the original message and carries forward the source forwarding score when it can read it. Otherwise it uses the default forward option. You can override the `forward` send option if your transport supports it.
969
+
970
+ ### Albums
971
+
972
+ Albums support images and videos.
973
+
974
+ ```ts
975
+ await client.album(jid, {
976
+ media: [
977
+ { type: "image", source: firstPhoto },
978
+ { type: "image", source: secondPhoto },
979
+ { type: "video", source: shortVideo },
980
+ ],
981
+ });
982
+
983
+ await client
984
+ .album()
985
+ .image(firstPhoto)
986
+ .image(secondPhoto)
987
+ .video(shortVideo)
988
+ .send(jid);
989
+ ```
990
+
991
+ **Album payload sequence**
992
+
993
+ 1. The library sends an `albumMessage` containing the expected image and video counts.
994
+ 2. It reads the returned album message ID.
995
+ 3. It sends each resolved media item as a separate message, quoting the album message ID.
996
+
997
+ The album operation therefore consists of multiple sends. If the initial album send does not return a message ID, the operation fails with a `PROTOCOL_SEND` error at the `album_id` stage.
998
+
999
+ ### Fluent builder methods
1000
+
1001
+ The following methods are implemented by the respective builders. Optional arguments are omitted here only where the method accepts a default.
1002
+
1003
+ | Builder | Fluent methods |
1004
+ | --- | --- |
1005
+ | `TextBuilder` | `body(text)` |
1006
+ | `Button` | `title(text)`, `subtitle(text)`, `body(text)`, `footer(text)`, `quick_reply(text, id)`, `cta_url(text, url)`, `cta_copy(text, code)`, `cta_call(text, phone)`, `send_location(text?)`, `single_select(title, sections)`, `image(source, options?)`, `video(source, options?)`, `document(source, options?)`, `location(options)`, `thumb(bytes?)`, `headerThumbnail(bytes)`, `bottom_sheet(options?)`, `limited_time_offer(options?)` |
1007
+ | `LegacyButton` | `title(text)`, `body(text)`, `footer(text)`, `button(id, text)`, `image(source, options?)`, `video(source, options?)`, `document(source, options?)`, `location(options)`, `thumb(bytes?)` |
1008
+ | `ListMessage` | `title(text)`, `body(text)`, `footer(text)`, `buttonText(text)`, `section(title, rows)`, `fallback(mode)`, `inGroup(flag)` |
1009
+ | `AIRich` | `text(text, options?)`, `code(language, code, options?)`, `table(rows, options?)`, `metadata(text, options?)`, `tip(text, options?)`, `suggest(items, options?)`, `source(sources, options?)`, `image(url, options?)`, `video(url, options?)`, `footerAction(items, options?)`, `widget(items, options?)`, `product(items, options?)`, `post(items, options?)`, `reels(items, options?)`, `html(html, options?)`, `raw(section, submessage?, options?)`, `replace(target, section, submessage?, options?)`, `insert(target, section, submessage?, options?)`, `insertAt(index, section, submessage?, options?)`, `remove(target)`, `clear()`, `loadPayload(payload)`, `context(info)`, `quote(message)`, `footer(text)` |
1010
+ | `LinkPreviewBuilder` | `body(text)`, `url(url)`, `title(text)`, `description(text)`, `thumbnail(bytes)`, `kind("image" | "video")` |
1011
+ | `MediaBuilder` | `image(source, options?)`, `video(source, options?)`, `audio(source, options?)`, `document(source, options?)`, `caption(text)`, `kind()`, `slot()` |
1012
+ | `StickerBuilder` | `source(source, options?)`, `slot()` |
1013
+ | `PollBuilder` | `question(text)`, `options(values)`, `selectableCount(count)`, `allowAddOption(flag?)`, `hideParticipantName(flag?)` |
1014
+ | `ContactBuilder` | `name(name)`, `vcard(value)`, `phone(phone)`, `organization(name)`, `email(email)`, `url(url)`, `note(note)` |
1015
+ | `LocationBuilder` | `coordinates(latitude, longitude)`, `name(name)`, `address(address)`, `thumbnail(bytes)` |
1016
+ | `ReactionBuilder` | `target(message)`, `emoji(emoji)` |
1017
+ | `ForwardBuilder` | `message(source)` |
1018
+ | `AlbumBuilder` | `image(source, options?)`, `video(source, options?)`, `count()` |
1019
+
1020
+ Every builder inherits `use(client)`, `to(jid)`, `defaultTo(jid)`, `defaultQuote(reference)`, `build()`, and `send(jid?, options?)` from `BaseBuilder`, except where a specialized builder overrides the send or build lifecycle. `build()` may be asynchronous for builders that resolve media or protocol data.
1021
+
1022
+ ## 🧰 Additional utilities
1023
+
1024
+ ### Standalone factories
1025
+
1026
+ The root package exports factories for use without `WaClient` prototype methods:
1027
+
1028
+ ```ts
1029
+ import {
1030
+ text,
1031
+ button,
1032
+ legacyButton,
1033
+ listMessage,
1034
+ airich,
1035
+ messageKit,
1036
+ } from "@kyyinfinite/zapo-message";
1037
+
1038
+ const textBuilder = text(client).body("Hello");
1039
+ await textBuilder.send(jid);
1040
+
1041
+ await button(client).body("Choose").quick_reply("OK", "ok").send(jid);
1042
+
1043
+ const kit = messageKit(client);
1044
+ await kit.button().body("From the kit").send(jid);
1045
+ ```
1046
+
1047
+ `messageKit(client)` exposes `button`, `legacyButton`, `listMessage`, and `airich` factories. Other message factories are imported directly from the package root.
1048
+
1049
+ ### Manual installation
1050
+
1051
+ For a compatible custom client that implements `client.message.send`, install the methods on that client instance:
1052
+
1053
+ ```ts
1054
+ import { installZapoMessage } from "@kyyinfinite/zapo-message";
1055
+
1056
+ installZapoMessage(customClient);
1057
+ await customClient.text().body("Hello").send(jid);
1058
+ ```
1059
+
1060
+ `installZapoMessage()` checks for a callable `message.send` method and returns the client. This does not make an arbitrary transport fully ZapoJS-compatible; message content and options still need to be supported by the transport.
1061
+
1062
+ ### Serialization and interactive replies
1063
+
1064
+ ```ts
1065
+ import {
1066
+ mSerialize,
1067
+ qSerialize,
1068
+ extractText,
1069
+ } from "@kyyinfinite/zapo-message/serialize.js";
1070
+ import { extractInteractiveResponse } from "@kyyinfinite/zapo-message/interactive.js";
1071
+
1072
+ const message = mSerialize(incomingEvent, client);
1073
+ console.log(message.text);
1074
+ console.log(message.interactive?.id);
1075
+
1076
+ await message.reply("Thanks for your message");
1077
+ await message.react("👍");
1078
+
1079
+ const quoted = message.q;
1080
+ if (quoted) {
1081
+ console.log(quoted.text);
1082
+ await quoted.reply("Replying to the quoted message");
1083
+ }
1084
+
1085
+ const selected = extractInteractiveResponse(incomingEvent.message);
1086
+ console.log(selected?.id, selected?.displayText, selected?.flowName);
1087
+ ```
1088
+
1089
+ `mSerialize()` returns a message wrapper with `content`, `text`, `interactive`, `q`, `reply()`, `react()`, and `download()`. The `q` property is available when the message contains a quoted message. `qSerialize()` serializes the quoted wrapper from an `MSerialized` value.
1090
+
1091
+ `extractInteractiveResponse()` recognizes button, list, template-button, and supported native-flow responses. Its result includes the selected `id`, optional display text, flow name, response content type, and context info.
1092
+
1093
+ ### Media downloads
1094
+
1095
+ ```ts
1096
+ const message = mSerialize(incomingEvent, client);
1097
+ const bytes = await message.download("buffer");
1098
+ const stream = await message.download("stream");
1099
+ ```
1100
+
1101
+ The serialized message wrapper exposes `download("buffer")` and `download("stream")`. A quoted wrapper (`message.q`) exposes `download("bytes")` and `download("stream")`. The client must expose the media download capabilities required by the selected operation (`message.download` and/or `message.downloadBytes`).
1102
+
1103
+ ### Shared media queue
1104
+
1105
+ Media resolution and upload use a shared admission-controlled queue.
1106
+
1107
+ ```ts
1108
+ import {
1109
+ configureSharedMediaQueue,
1110
+ getSharedMediaQueue,
1111
+ resetSharedMediaQueue,
1112
+ } from "@kyyinfinite/zapo-message/media-gate.js";
1113
+
1114
+ configureSharedMediaQueue({
1115
+ concurrency: 4,
1116
+ capacity: 50,
1117
+ timeoutMs: 30_000,
1118
+ maxBytes: 100 * 1024 * 1024,
1119
+ });
1120
+
1121
+ const queue = getSharedMediaQueue();
1122
+ console.log(queue.snapshot());
1123
+
1124
+ resetSharedMediaQueue();
1125
+ ```
1126
+
1127
+ The queue options include `concurrency`, `capacity`, `timeoutMs`, `maxBytes`, and an optional concurrency `controller`. Use `configureSharedMediaQueue()` when you need to adjust shared media processing limits. `resetSharedMediaQueue()` clears the shared instance so it is recreated with defaults on the next access.
1128
+
1129
+ ### Reply branding
1130
+
1131
+ ```ts
1132
+ import {
1133
+ setReplyBranding,
1134
+ resetReplyBranding,
1135
+ } from "@kyyinfinite/zapo-message/branding.js";
1136
+
1137
+ setReplyBranding((text, options) => ({
1138
+ ...options,
1139
+ additionalAttributes: { source: "my-bot" },
1140
+ }));
1141
+
1142
+ resetReplyBranding();
1143
+ ```
1144
+
1145
+ The branding provider is applied by the serializer's reply helper. It does not rewrite every message sent through the client.
1146
+
1147
+ ### Status formatting
1148
+
1149
+ ```ts
1150
+ import { toBoldSans, formatStatus } from "@kyyinfinite/zapo-message/status.js";
1151
+
1152
+ const heading = toBoldSans("System status");
1153
+ const status = formatStatus("ok", "Connected");
1154
+ ```
1155
+
1156
+ `formatStatus()` accepts `"ok"`, `"warn"`, or `"fail"`.
1157
+
1158
+ ## 🧾 Message payloads at a glance
1159
+
1160
+ The following table describes the top-level content shape built by the package before it is passed to `client.message.send()`. Media fields contain protocol metadata produced after upload; AIRich and interactive messages contain nested protocol structures.
1161
+
1162
+ | API | Top-level payload / transport input |
1163
+ | --- | --- |
1164
+ | `text` | `{ conversation: string }` |
1165
+ | `button` | `{ interactiveMessage: { body, nativeFlowMessage, header?, footer? } }` |
1166
+ | `legacyButton` | `{ buttonsMessage: { contentText, buttons, headerType, ... } }` |
1167
+ | `listMessage` | `{ listMessage: { title, description, buttonText, listType, sections, ... } }` or native-flow fallback |
1168
+ | `linkPreview` | `{ extendedTextMessage: { text, matchedText, previewType, ... } }` |
1169
+ | `media` / `image` / `video` / `audio` / `document` | One of `{ imageMessage }`, `{ videoMessage }`, `{ audioMessage }`, `{ documentMessage }` |
1170
+ | `sticker` | `{ stickerMessage }` |
1171
+ | `contact` | `{ contactMessage: { displayName, vcard } }` |
1172
+ | `poll` | `{ type: "poll", name, options, ... }` input understood by ZapoJS |
1173
+ | `location` | `{ locationMessage: { degreesLatitude, degreesLongitude, ... } }` |
1174
+ | `reaction` | `{ type: "reaction", target, emoji }` input understood by ZapoJS |
1175
+ | `forward` | Original protocol message plus forward send options |
1176
+ | `album` | Album marker followed by individually uploaded media messages |
1177
+ | `airich` | `{ botForwardedMessage: { message: { richResponseMessage } } }` |
1178
+
1179
+ These are payload families, not a promise that every nested protobuf field is stable across ZapoJS versions. The package deliberately delegates transport-specific behavior to `client.message.send()` and media upload to `client.message.upload()`.
1180
+
1181
+ ## ⚠️ Validation and errors
1182
+
1183
+ The root package exports these error classes:
1184
+
1185
+ | Error class | Code | Typical cause |
1186
+ | --- | --- | --- |
1187
+ | `MessageError` | `MESSAGE_ERROR` by default | General builder or send lifecycle error |
1188
+ | `ValidationError` | `VALIDATION` | Invalid or missing config value |
1189
+ | `ItemNotFoundError` | `ITEM_NOT_FOUND` | AIRich node ID or index was not found |
1190
+ | `DuplicateIdError` | `DUPLICATE_ID` | Duplicate ID in a structure that requires unique IDs |
1191
+ | `InvalidTargetError` | `INVALID_TARGET` | Invalid message target |
1192
+ | `ProtocolSendError` | `PROTOCOL_SEND` | Placeholder edit or album send protocol step failed |
1193
+ | `MediaError` | `MEDIA` | Media read, detection, processing, or upload failed |
1194
+
1195
+ Example:
1196
+
1197
+ ```ts
1198
+ import {
1199
+ MessageError,
1200
+ ValidationError,
1201
+ MediaError,
1202
+ } from "@kyyinfinite/zapo-message";
1203
+
1204
+ try {
1205
+ await client.text(jid, { body: "" });
1206
+ } catch (error) {
1207
+ if (error instanceof ValidationError) {
1208
+ console.error("Invalid message config:", error.message);
1209
+ } else if (error instanceof MediaError) {
1210
+ console.error("Media operation failed:", error.message);
1211
+ } else if (error instanceof MessageError) {
1212
+ console.error(error.code, error.message);
1213
+ } else {
1214
+ throw error;
1215
+ }
1216
+ }
1217
+ ```
1218
+
1219
+ Errors expose a `code` property. Some errors also include structured metadata such as `cause`, `kind`, `stage`, `placeholderId`, `id`, or `availableIds`.
1220
+
1221
+ ## 🛠 Troubleshooting
1222
+
1223
+ ### `client.text is not a function`
1224
+
1225
+ - Make sure the root package import runs before you call the method:
1226
+
1227
+ ```ts
1228
+ import "@kyyinfinite/zapo-message";
1229
+ ```
1230
+
1231
+ - Confirm that the client is a `WaClient` from the same resolved ZapoJS installation used by the package.
1232
+ - If you use a custom client, call `installZapoMessage(client)` and ensure it has a callable `message.send` method.
1233
+ - Check whether your bundler or runtime is loading a different copy of ZapoJS.
1234
+
1235
+ ### `NO_CLIENT`
1236
+
1237
+ The builder has no client bound to it. Create it through `client.text()` or pass a client to the standalone factory:
1238
+
1239
+ ```ts
1240
+ await text(client).body("Hello").send(jid);
1241
+ ```
1242
+
1243
+ ### `NO_TARGET`
1244
+
1245
+ No destination was supplied. Pass a JID to `.send(jid)`, set `.to(jid)` / `.defaultTo(jid)`, or use a message reference that contains a chat JID where the API supports target inference.
1246
+
1247
+ ### `VALIDATION` or `DUPLICATE_ID`
1248
+
1249
+ Check required fields, field types, URL formats, phone formats, numeric ranges, and uniqueness constraints. Button and list IDs must be unique where the builder validates them. For AIRich operations, confirm that the referenced node ID exists before calling `replace`, `insert`, or `remove`.
1250
+
1251
+ ### Media type cannot be detected
1252
+
1253
+ Some streams and unusual file sources do not provide enough information for automatic MIME detection. Set `mimetype` explicitly in the media options:
1254
+
1255
+ ```ts
1256
+ await client.document(jid, {
1257
+ source: fileBuffer,
1258
+ fileName: "report.bin",
1259
+ mimetype: "application/octet-stream",
1260
+ });
1261
+ ```
1262
+
1263
+ ### Document requires a filename
1264
+
1265
+ A buffer or stream does not carry a reliable display filename. Set `fileName` explicitly:
1266
+
1267
+ ```ts
1268
+ await client.document(jid, {
1269
+ source: pdfBuffer,
1270
+ fileName: "report.pdf",
1271
+ mimetype: "application/pdf",
1272
+ });
1273
+ ```
1274
+
1275
+ ### `sharp` is unavailable or thumbnail generation fails
1276
+
1277
+ Install the optional dependency when you need automatic image processing:
1278
+
1279
+ ```bash
1280
+ npm install sharp
1281
+ ```
1282
+
1283
+ Alternatively, supply a suitable thumbnail or the dimensions required by the feature. Some thumbnail paths require JPEG input; others generate a JPEG thumbnail through Sharp.
1284
+
1285
+ ### Sticker rejected as an invalid image
1286
+
1287
+ Sticker input must be WebP. Convert the image to WebP before passing it to `sticker()`; the library inspects WebP data but does not convert arbitrary formats into stickers.
1288
+
1289
+ ### Reaction has no target chat
1290
+
1291
+ The target reference must include a message ID. To infer the chat automatically, it should also include `key.remoteJid`. Otherwise, pass the chat JID to the reaction send call:
1292
+
1293
+ ```ts
1294
+ await client.reaction(jid, {
1295
+ target: messageKey,
1296
+ emoji: "🔥",
1297
+ });
1298
+ ```
1299
+
1300
+ ### Album send fails with `PROTOCOL_SEND`
1301
+
1302
+ Album delivery requires the initial album marker send to return a non-empty message ID. If your custom transport does not return the same result shape as ZapoJS, the follow-up media messages cannot quote the album marker.
1303
+
1304
+ ### AIRich placeholder was sent but the edit failed
1305
+
1306
+ A two-step AIRich send can fail after the placeholder is already delivered. Inspect the `ProtocolSendError` fields, especially `stage` and `placeholderId`, before retrying. Sending a new response blindly may leave the original placeholder visible.
1307
+
1308
+ ### Poll display differs between WhatsApp clients
1309
+
1310
+ Poll rendering is ultimately handled by the installed ZapoJS version and the recipient's WhatsApp client. Keep poll options within the validated range and test the desired selection behavior against the clients you support.
1311
+
1312
+ ## ❓ FAQ
1313
+
1314
+ <details>
1315
+ <summary><strong>Do I have to use the fluent API?</strong></summary>
1316
+
1317
+ No. Use the object API when the full message configuration is already available. Use the fluent API when building the message step by step. Both use the same underlying builders.
1318
+
1319
+ </details>
1320
+
1321
+ <details>
1322
+ <summary><strong>Can I mix object and fluent APIs in one project?</strong></summary>
1323
+
1324
+ Yes. They are two entry points to the same message implementations. You can choose the style per message.
1325
+
1326
+ </details>
1327
+
1328
+ <details>
1329
+ <summary><strong>Does importing the package modify ZapoJS?</strong></summary>
1330
+
1331
+ The root import installs non-enumerable methods on the `WaClient` prototype. Existing method names are not overwritten, and installation is guarded against repeated execution. If you do not want prototype integration, use the exported factories instead.
1332
+
1333
+ </details>
1334
+
1335
+ <details>
1336
+ <summary><strong>Can I use a custom client?</strong></summary>
1337
+
1338
+ Yes, if it implements the expected `message.send()` interface and supports the payloads and options you use. Call `installZapoMessage()` to add the convenience methods to a client instance, or pass the client directly to a standalone factory.
1339
+
1340
+ </details>
1341
+
1342
+ <details>
1343
+ <summary><strong>Can I send several media items with `media()`?</strong></summary>
1344
+
1345
+ No. A `MediaBuilder` accepts one media kind and one source. Use `album()` for a sequence of images and videos.
1346
+
1347
+ </details>
1348
+
1349
+ <details>
1350
+ <summary><strong>Can `location()` request the recipient's location?</strong></summary>
1351
+
1352
+ No. `location()` sends a location message. Use the native-flow button item `{ type: "send_location" }` when you want to add a button that asks the recipient to share their location.
1353
+
1354
+ </details>
1355
+
1356
+ <details>
1357
+ <summary><strong>Does `linkPreview()` fetch the URL?</strong></summary>
1358
+
1359
+ No. It builds an explicit preview payload from the supplied text and metadata. Provide a thumbnail when you need one; the selected URL must appear in the message body.
1360
+
1361
+ </details>
1362
+
1363
+ <details>
1364
+ <summary><strong>Does the library convert images into WebP stickers?</strong></summary>
1365
+
1366
+ No. Sticker sources must already contain WebP data. Convert the source before calling the sticker API.
1367
+
1368
+ </details>
1369
+
1370
+ <details>
1371
+ <summary><strong>Are all AIRich primitives guaranteed to render on every WhatsApp client?</strong></summary>
1372
+
1373
+ No. Some AIRich primitive types are marked experimental in the package. Their rendering depends on WhatsApp client and protocol support. Test them with the client versions you intend to support.
1374
+
1375
+ </details>
1376
+
1377
+ <details>
1378
+ <summary><strong>Why does AIRich sometimes send a placeholder first?</strong></summary>
1379
+
1380
+ AIRich supports a two-step placeholder/edit transport flow. The `twoStep` send option controls that behavior. A failed edit may happen after the placeholder has already been sent; inspect the protocol error before retrying.
1381
+
1382
+ </details>
1383
+
1384
+ <details>
1385
+ <summary><strong>Where can I find every TypeScript type?</strong></summary>
1386
+
1387
+ The package publishes declaration files and exports the public config, option, builder, payload, and error types from its root entry point. Import the type you need directly from `@kyyinfinite/zapo-message`.
1388
+
1389
+ </details>
1390
+
1391
+
1392
+ ## 📄 License
1393
+
1394
+ ISC. See [LICENSE](LICENSE).
1395
+
1396
+ ---
1397
+
1398
+ <div align="center">
1399
+
1400
+ Made for developers building on ZapoJS.
1401
+
1402
+ </div>