@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
@@ -0,0 +1,646 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { Readable } from "node:stream";
7
+ import sharp from "sharp";
8
+ import { proto } from "zapo-js";
9
+ import type { WaMediaUploadResult } from "zapo-js";
10
+
11
+ import { button, legacyButton } from "@kyyinfinite/zapo-message";
12
+ import { ValidationError, MediaError } from "@kyyinfinite/zapo-message";
13
+ import {
14
+ configureSharedMediaQueue,
15
+ resetSharedMediaQueue,
16
+ } from "@kyyinfinite/zapo-message/media-gate.js";
17
+ import { asClient, first } from "./helpers.js";
18
+
19
+ const makeJpeg = async ({
20
+ width = 900,
21
+ height = 700,
22
+ }: { width?: number; height?: number } = {}) =>
23
+ sharp({ create: { width, height, channels: 3, background: "#3090ff" } })
24
+ .jpeg({ quality: 88 })
25
+ .toBuffer();
26
+
27
+ const makePng = async ({
28
+ width = 500,
29
+ height = 500,
30
+ }: { width?: number; height?: number } = {}) =>
31
+ sharp({ create: { width, height, channels: 3, background: "#9030ff" } })
32
+ .png()
33
+ .toBuffer();
34
+
35
+ const countStreamBytes = (stream: Readable): Promise<number> =>
36
+ new Promise((resolve, reject) => {
37
+ let total = 0;
38
+ stream.on("data", (chunk: Buffer) => {
39
+ total += chunk.length;
40
+ });
41
+ stream.once("end", () => resolve(total));
42
+ stream.once("error", reject);
43
+ });
44
+
45
+ interface UploadClientOptions {
46
+ uploadResult?: Partial<WaMediaUploadResult>;
47
+ uploadCounters?: { source: unknown; options: Record<string, unknown> }[];
48
+ uploadImpl?: (
49
+ source: unknown,
50
+ options: Record<string, unknown>,
51
+ ) => Promise<WaMediaUploadResult>;
52
+ }
53
+
54
+ const makeUploadClient = ({
55
+ uploadResult = {},
56
+ uploadCounters,
57
+ uploadImpl,
58
+ }: UploadClientOptions = {}) => {
59
+ const uploads: { source: unknown; options: Record<string, unknown> }[] = [];
60
+ const sends: { jid?: unknown; content?: unknown; options?: unknown }[] = [];
61
+ const client = {
62
+ message: {
63
+ async upload(
64
+ source: unknown,
65
+ options: Record<string, unknown>,
66
+ ): Promise<WaMediaUploadResult> {
67
+ uploads.push({ source, options });
68
+ if (uploadCounters) uploadCounters.push({ source, options });
69
+ if (uploadImpl) return uploadImpl(source, options);
70
+ const bytes =
71
+ source instanceof Uint8Array
72
+ ? source.byteLength
73
+ : await countStreamBytes(source as Readable);
74
+ return {
75
+ url: "https://mmg.whatsapp.net/v/t62.7118-24/fake-upload",
76
+ directPath: "/v/t62.7118-24/fake-upload",
77
+ mediaKey: new Uint8Array(32).fill(1),
78
+ fileSha256: new Uint8Array(32).fill(2),
79
+ fileEncSha256: new Uint8Array(32).fill(3),
80
+ fileLength: bytes,
81
+ mediaKeyTimestamp: 1730000000,
82
+ ...uploadResult,
83
+ };
84
+ },
85
+ async send(jid: unknown, content: unknown, options: unknown) {
86
+ sends.push({ jid, content, options });
87
+ return { id: "FAKEID", attempts: 1, ack: {} };
88
+ },
89
+ },
90
+ };
91
+ return { client: asClient(client), uploads, sends };
92
+ };
93
+
94
+ test("header: image attachment — UploadResult masuk payload dengan benar", async () => {
95
+ const jpeg = await makeJpeg();
96
+ const { client, uploads } = makeUploadClient();
97
+ const result = await button(client)
98
+ .body("halo")
99
+ .image(jpeg)
100
+ .quick_reply("QR", "qr1")
101
+ .build();
102
+
103
+ const header = result.interactiveMessage.header as Record<string, unknown>;
104
+ assert.equal(header.hasMediaAttachment, true);
105
+ const image = header.imageMessage as Record<string, unknown>;
106
+ assert.equal(image.url, "https://mmg.whatsapp.net/v/t62.7118-24/fake-upload");
107
+ assert.equal(image.directPath, "/v/t62.7118-24/fake-upload");
108
+ assert.deepEqual([...(image.mediaKey as Uint8Array)], new Array(32).fill(1));
109
+ assert.deepEqual(
110
+ [...(image.fileSha256 as Uint8Array)],
111
+ new Array(32).fill(2),
112
+ );
113
+ assert.deepEqual(
114
+ [...(image.fileEncSha256 as Uint8Array)],
115
+ new Array(32).fill(3),
116
+ );
117
+ assert.equal(image.fileLength, jpeg.byteLength);
118
+ assert.equal(image.mediaKeyTimestamp, 1730000000);
119
+ assert.equal(image.mimetype, "image/jpeg");
120
+
121
+ const firstUpload = uploads[0] as {
122
+ options: Record<string, unknown>;
123
+ source: Uint8Array;
124
+ };
125
+ assert.equal(uploads.length, 1);
126
+ assert.equal(firstUpload.options.type, "image");
127
+ assert.equal(firstUpload.options.mimetype, "image/jpeg");
128
+ assert.deepEqual([...firstUpload.source.subarray(0, 2)], [0xff, 0xd8]);
129
+ });
130
+
131
+ test("header: image otomatis dapat jpegThumbnail via Sharp", async () => {
132
+ const jpeg = await makeJpeg({ width: 1200, height: 800 });
133
+ const { client } = makeUploadClient();
134
+ const result = await button(client)
135
+ .image(jpeg)
136
+ .quick_reply("QR", "qr1")
137
+ .build();
138
+
139
+ const image = (result.interactiveMessage.header as Record<string, unknown>)
140
+ .imageMessage as Record<string, unknown>;
141
+ assert.ok(image.jpegThumbnail);
142
+ assert.equal((image.jpegThumbnail as Uint8Array)[0], 0xff);
143
+ assert.equal((image.jpegThumbnail as Uint8Array)[1], 0xd8);
144
+
145
+ const metadata = await sharp(image.jpegThumbnail as Buffer).metadata();
146
+ assert.equal(metadata.format, "jpeg");
147
+ assert.ok(
148
+ metadata.width !== undefined &&
149
+ metadata.width <= 240 &&
150
+ metadata.height !== undefined &&
151
+ metadata.height <= 240,
152
+ );
153
+ assert.equal((metadata.width as number) / (metadata.height as number), 3 / 2);
154
+ });
155
+
156
+ test("header: image thumbnail eksplisit diprioritaskan daripada otomatis", async () => {
157
+ const jpeg = await makeJpeg({ width: 1200, height: 800 });
158
+ const explicit = await makeJpeg({ width: 64, height: 64 });
159
+ const { client } = makeUploadClient();
160
+ const result = await button(client)
161
+ .image(jpeg, { thumbnail: explicit })
162
+ .quick_reply("QR", "qr1")
163
+ .build();
164
+
165
+ const thumbnail = (
166
+ (result.interactiveMessage.header as Record<string, unknown>)
167
+ .imageMessage as Record<string, unknown>
168
+ ).jpegThumbnail as Uint8Array;
169
+ assert.equal(thumbnail.byteLength, explicit.byteLength);
170
+ assert.deepEqual([...thumbnail], [...explicit]);
171
+ });
172
+
173
+ test("header: image { thumbnail: false } menonaktifkan thumbnail otomatis", async () => {
174
+ const jpeg = await makeJpeg();
175
+ const { client } = makeUploadClient();
176
+ const result = await button(client)
177
+ .image(jpeg, { thumbnail: false })
178
+ .quick_reply("QR", "qr1")
179
+ .build();
180
+ assert.equal(
181
+ (
182
+ (result.interactiveMessage.header as Record<string, unknown>)
183
+ .imageMessage as Record<string, unknown>
184
+ ).jpegThumbnail,
185
+ undefined,
186
+ );
187
+ });
188
+
189
+ test("header: headerThumbnail pasang JPEG tanpa upload attachment", async () => {
190
+ const jpeg = await makeJpeg({ width: 100, height: 100 });
191
+ const { client, uploads } = makeUploadClient();
192
+ const result = await button(client)
193
+ .title("Judul")
194
+ .headerThumbnail(jpeg)
195
+ .quick_reply("QR", "qr1")
196
+ .build();
197
+
198
+ const header = result.interactiveMessage.header as Record<string, unknown>;
199
+ assert.equal(header.hasMediaAttachment, false);
200
+ assert.deepEqual([...(header.jpegThumbnail as Uint8Array)], [...jpeg]);
201
+ assert.equal(header.imageMessage, undefined);
202
+ assert.equal(header.title, "Judul");
203
+ assert.equal(uploads.length, 0);
204
+ });
205
+
206
+ test("header: headerThumbnail menolak PNG dan bytes acak dengan pesan jelas", async () => {
207
+ const png = await makePng({ width: 50, height: 50 });
208
+ const { client } = makeUploadClient();
209
+ await assert.rejects(
210
+ async () => button(client).headerThumbnail(png).build(),
211
+ (error: Error) =>
212
+ error instanceof ValidationError &&
213
+ /harus JPEG valid/.test(error.message),
214
+ );
215
+ await assert.rejects(
216
+ async () =>
217
+ button(client).headerThumbnail(Buffer.from("bukan bytes gambar")).build(),
218
+ ValidationError,
219
+ );
220
+ });
221
+
222
+ test("header: video attachment dengan mimetype eksplisit dan streamingSidecar", async () => {
223
+ const { client, uploads } = makeUploadClient({
224
+ uploadResult: { streamingSidecar: new Uint8Array(16).fill(9) },
225
+ });
226
+ const stream = Readable.from([Buffer.alloc(2048, 5)]);
227
+ const result = await button(client)
228
+ .video(stream, {
229
+ mimetype: "video/mp4",
230
+ seconds: 30,
231
+ width: 640,
232
+ height: 360,
233
+ })
234
+ .quick_reply("QR", "qr1")
235
+ .build();
236
+
237
+ const video = (result.interactiveMessage.header as Record<string, unknown>)
238
+ .videoMessage as Record<string, unknown>;
239
+ assert.equal(
240
+ (result.interactiveMessage.header as Record<string, unknown>)
241
+ .hasMediaAttachment,
242
+ true,
243
+ );
244
+ assert.equal(video.mimetype, "video/mp4");
245
+ assert.equal(video.seconds, 30);
246
+ assert.equal(video.width, 640);
247
+ assert.equal(video.height, 360);
248
+ assert.equal(video.fileLength, 2048);
249
+ assert.deepEqual(
250
+ [...(video.streamingSidecar as Uint8Array)],
251
+ new Array(16).fill(9),
252
+ );
253
+ assert.equal(
254
+ (uploads[0] as { options: Record<string, unknown> }).options.type,
255
+ "video",
256
+ );
257
+ });
258
+
259
+ test("header: video stream tanpa mimetype eksplisit → error jelas", async () => {
260
+ const { client } = makeUploadClient();
261
+ await assert.rejects(
262
+ async () =>
263
+ button(client)
264
+ .video(Readable.from([Buffer.alloc(10)]))
265
+ .quick_reply("QR", "qr1")
266
+ .build(),
267
+ (error: Error) =>
268
+ error instanceof ValidationError &&
269
+ /mimetype.*tidak diketahui/.test(error.message),
270
+ );
271
+ });
272
+
273
+ test("header: document attachment — fileName, mimetype, thumbnail eksplisit", async (t) => {
274
+ const dir = await mkdtemp(join(tmpdir(), "zapo-message-btn-doc-"));
275
+ t.after(() => rm(dir, { recursive: true, force: true }));
276
+ const file = join(dir, "laporan.pdf");
277
+ await writeFile(file, Buffer.from("%PDF-1.4 fake pdf bytes"));
278
+
279
+ const pdfThumb = await makeJpeg({ width: 80, height: 110 });
280
+ const { client, uploads } = makeUploadClient();
281
+ const result = await button(client)
282
+ .document(file, {
283
+ fileName: "Laporan-2026.pdf",
284
+ title: "Laporan",
285
+ thumbnail: pdfThumb,
286
+ })
287
+ .quick_reply("QR", "qr1")
288
+ .build();
289
+
290
+ const doc = (result.interactiveMessage.header as Record<string, unknown>)
291
+ .documentMessage as Record<string, unknown>;
292
+ assert.equal(doc.fileName, "Laporan-2026.pdf");
293
+ assert.equal(doc.title, "Laporan");
294
+ assert.equal(doc.mimetype, "application/pdf");
295
+ assert.deepEqual([...(doc.jpegThumbnail as Uint8Array)], [...pdfThumb]);
296
+ assert.equal(doc.fileLength, 23);
297
+ assert.equal(
298
+ (uploads[0] as { options: Record<string, unknown> }).options.type,
299
+ "document",
300
+ );
301
+ });
302
+
303
+ test("header: document tanpa fileName → error jelas", async () => {
304
+ const { client } = makeUploadClient();
305
+ await assert.rejects(
306
+ async () =>
307
+ button(client)
308
+ .document(Buffer.from("%PDF-1.4"), { mimetype: "application/pdf" })
309
+ .quick_reply("QR", "qr1")
310
+ .build(),
311
+ (error: Error) =>
312
+ error instanceof ValidationError && /fileName/.test(error.message),
313
+ );
314
+ });
315
+
316
+ test("header: title + image bisa bersama; title + thumbnail bisa", async () => {
317
+ const jpeg = await makeJpeg();
318
+ const { client } = makeUploadClient();
319
+
320
+ const withImage = await button(client)
321
+ .title("Judul")
322
+ .subtitle("Sub")
323
+ .image(jpeg)
324
+ .quick_reply("QR", "qr1")
325
+ .build();
326
+ assert.equal(
327
+ (withImage.interactiveMessage.header as Record<string, unknown>).title,
328
+ "Judul",
329
+ );
330
+ assert.equal(
331
+ (withImage.interactiveMessage.header as Record<string, unknown>).subtitle,
332
+ "Sub",
333
+ );
334
+ assert.ok(
335
+ (withImage.interactiveMessage.header as Record<string, unknown>)
336
+ .imageMessage,
337
+ );
338
+
339
+ const thumb = await makeJpeg({ width: 40, height: 40 });
340
+ const withThumb = await button(client)
341
+ .title("Judul")
342
+ .headerThumbnail(thumb)
343
+ .quick_reply("QR", "qr2")
344
+ .build();
345
+ assert.equal(
346
+ (withThumb.interactiveMessage.header as Record<string, unknown>).title,
347
+ "Judul",
348
+ );
349
+ assert.ok(
350
+ (withThumb.interactiveMessage.header as Record<string, unknown>)
351
+ .jpegThumbnail,
352
+ );
353
+ });
354
+
355
+ test("header: konflik location vs media ditolak", async () => {
356
+ const jpeg = await makeJpeg();
357
+ const { client } = makeUploadClient();
358
+
359
+ await assert.rejects(
360
+ async () =>
361
+ button(client)
362
+ .location({ latitude: -6.2, longitude: 106.8 })
363
+ .image(jpeg)
364
+ .build(),
365
+ (error: Error) =>
366
+ error instanceof ValidationError &&
367
+ /satu jenis konten/.test(error.message),
368
+ );
369
+ await assert.rejects(
370
+ async () =>
371
+ button(client)
372
+ .image(jpeg)
373
+ .location({ latitude: -6.2, longitude: 106.8 })
374
+ .build(),
375
+ ValidationError,
376
+ );
377
+ });
378
+
379
+ test("header: konflik headerThumbnail vs media dan vs location ditolak", async () => {
380
+ const jpeg = await makeJpeg();
381
+ const { client } = makeUploadClient();
382
+
383
+ await assert.rejects(
384
+ async () => button(client).headerThumbnail(jpeg).image(jpeg).build(),
385
+ /thumbnail gambar header pakai/,
386
+ );
387
+ await assert.rejects(
388
+ async () =>
389
+ button(client)
390
+ .location({ latitude: -6.2, longitude: 106.8 })
391
+ .headerThumbnail(jpeg)
392
+ .build(),
393
+ /location/,
394
+ );
395
+ await assert.rejects(
396
+ async () => button(client).headerThumbnail(jpeg).thumb(jpeg).build(),
397
+ /\.thumb\(\) khusus thumbnail location/,
398
+ );
399
+ });
400
+
401
+ test("header: upload gagal → error asli dipertahankan, tanpa payload setengah jadi", async () => {
402
+ const jpeg = await makeJpeg();
403
+ const originalError = new Error("CDN 503 overloaded");
404
+ const { client } = makeUploadClient({
405
+ uploadImpl: async () => {
406
+ throw originalError;
407
+ },
408
+ });
409
+
410
+ await assert.rejects(
411
+ async () => button(client).image(jpeg).quick_reply("QR", "qr1").build(),
412
+ (error: Error & { cause?: unknown }) =>
413
+ error instanceof MediaError &&
414
+ /upload media header.*gagal/.test(error.message) &&
415
+ error.cause === originalError,
416
+ );
417
+ });
418
+
419
+ test("header: uploader hasil tidak valid → error jelas", async () => {
420
+ const jpeg = await makeJpeg();
421
+ const { client } = makeUploadClient({
422
+ uploadImpl: async () =>
423
+ ({ directPath: "/x" }) as unknown as WaMediaUploadResult,
424
+ });
425
+ await assert.rejects(
426
+ async () => button(client).image(jpeg).quick_reply("QR", "qr1").build(),
427
+ (error: Error) =>
428
+ error instanceof MediaError &&
429
+ /UploadResult\.url wajib ada/.test(error.message),
430
+ );
431
+ });
432
+
433
+ test("header: mimetype tidak cocok dengan jenis header → error", async () => {
434
+ const jpeg = await makeJpeg();
435
+ const { client } = makeUploadClient();
436
+ await assert.rejects(
437
+ async () =>
438
+ button(client)
439
+ .image(jpeg, { mimetype: "video/mp4" })
440
+ .quick_reply("QR", "qr1")
441
+ .build(),
442
+ /tidak cocok untuk header image/,
443
+ );
444
+ });
445
+
446
+ test("header: image sumber bukan gambar (junk) → ValidationError mimetype tidak diketahui", async () => {
447
+ const { client } = makeUploadClient();
448
+ await assert.rejects(
449
+ async () =>
450
+ button(client)
451
+ .image(Buffer.from("junk junk junk"))
452
+ .quick_reply("QR", "qr1")
453
+ .build(),
454
+ (error: Error) =>
455
+ error instanceof ValidationError &&
456
+ /mimetype.*tidak diketahui/.test(error.message),
457
+ );
458
+ });
459
+
460
+ test("header: image empty source → ValidationError", async () => {
461
+ const { client } = makeUploadClient();
462
+ await assert.rejects(
463
+ async () =>
464
+ button(client).image(Buffer.alloc(0)).quick_reply("QR", "qr1").build(),
465
+ /thumbnail kosong|sumber/,
466
+ );
467
+ });
468
+
469
+ test("header: Readable image → thumbnail dibuat sebelum upload, stream dikonsumsi sekali", async () => {
470
+ const jpeg = await makeJpeg({ width: 400, height: 300 });
471
+ let reads = 0;
472
+ const counting = Readable.from(
473
+ (async function* () {
474
+ reads++;
475
+ yield jpeg;
476
+ })(),
477
+ );
478
+ const { client, uploads } = makeUploadClient();
479
+ const result = await button(client)
480
+ .image(counting)
481
+ .quick_reply("QR", "qr1")
482
+ .build();
483
+
484
+ assert.equal(reads, 1);
485
+ const image = (result.interactiveMessage.header as Record<string, unknown>)
486
+ .imageMessage as Record<string, unknown>;
487
+ assert.ok(image.jpegThumbnail);
488
+ assert.equal(image.mimetype, "image/jpeg");
489
+ const uploadedBytes = (uploads[0] as { source: Uint8Array }).source;
490
+ assert.equal(uploadedBytes.byteLength, jpeg.byteLength);
491
+ });
492
+
493
+ test("header: file path image → satu upload, thumbnail dari bytes yang sama", async (t) => {
494
+ const dir = await mkdtemp(join(tmpdir(), "zapo-message-btn-path-"));
495
+ t.after(() => rm(dir, { recursive: true, force: true }));
496
+ const file = join(dir, "foto.jpg");
497
+ await writeFile(file, await makeJpeg({ width: 600, height: 600 }));
498
+
499
+ const { client, uploads } = makeUploadClient();
500
+ const result = await button(client)
501
+ .image(file)
502
+ .quick_reply("QR", "qr1")
503
+ .build();
504
+
505
+ assert.equal(uploads.length, 1);
506
+ const image = (result.interactiveMessage.header as Record<string, unknown>)
507
+ .imageMessage as Record<string, unknown>;
508
+ assert.equal(image.mimetype, "image/jpeg");
509
+ assert.ok(image.jpegThumbnail);
510
+ assert.equal(image.width, 600);
511
+ assert.equal(image.height, 600);
512
+ });
513
+
514
+ test("header: payload round-trip protobuf — image header", async () => {
515
+ const jpeg = await makeJpeg({ width: 800, height: 600 });
516
+ const { client } = makeUploadClient();
517
+ const result = await button(client)
518
+ .title("Judul")
519
+ .body("Deskripsi panjang")
520
+ .footer("Footer")
521
+ .image(jpeg)
522
+ .quick_reply("QR", "qr1")
523
+ .cta_url("Buka", "https://example.com")
524
+ .single_select("Pilih", [
525
+ { title: "S", rows: [{ id: "r1", title: "Row", description: "desc" }] },
526
+ ])
527
+ .bottom_sheet({ limit: 2, listTitle: "L", buttonTitle: "B" })
528
+ .build();
529
+
530
+ const wire = proto.Message.encode(result).finish();
531
+ const decoded = proto.Message.decode(wire);
532
+ const decodedInteractive = decoded.interactiveMessage as NonNullable<
533
+ typeof decoded.interactiveMessage
534
+ >;
535
+
536
+ const header = decodedInteractive.header;
537
+ assert.equal(header?.hasMediaAttachment, true);
538
+ assert.equal(header?.title, "Judul");
539
+ assert.equal(header?.imageMessage?.mimetype, "image/jpeg");
540
+ assert.equal(Number(header?.imageMessage?.fileLength), jpeg.byteLength);
541
+ assert.ok((header?.imageMessage?.jpegThumbnail as Uint8Array).length > 0);
542
+ assert.deepEqual(
543
+ [...(header?.imageMessage?.mediaKey as Uint8Array)],
544
+ new Array(32).fill(1),
545
+ );
546
+
547
+ const flow = decodedInteractive.nativeFlowMessage as NonNullable<
548
+ typeof decodedInteractive.nativeFlowMessage
549
+ >;
550
+ assert.equal(flow?.messageVersion, 1);
551
+ assert.equal((flow?.buttons ?? []).length, 3);
552
+ assert.equal((flow?.buttons ?? [])[0]?.name, "quick_reply");
553
+ assert.deepEqual(
554
+ JSON.parse(
555
+ ((flow?.buttons ?? [])[0] as { buttonParamsJson?: string })
556
+ ?.buttonParamsJson ?? "{}",
557
+ ),
558
+ { display_text: "QR", id: "qr1" },
559
+ );
560
+ const flowButtons = (flow?.buttons ?? []) as {
561
+ name?: string;
562
+ buttonParamsJson?: string;
563
+ }[];
564
+ assert.equal(flowButtons[1]?.name, "cta_url");
565
+ assert.equal(flowButtons[2]?.name, "single_select");
566
+ const sections = JSON.parse(
567
+ flowButtons[2]?.buttonParamsJson ?? "{}",
568
+ ).sections;
569
+ assert.equal(sections[0].rows[0].id, "r1");
570
+
571
+ const params = JSON.parse(flow?.messageParamsJson ?? "{}");
572
+ assert.deepEqual(params.bottom_sheet, {
573
+ in_thread_buttons_limit: 2,
574
+ list_title: "L",
575
+ button_title: "B",
576
+ });
577
+
578
+ assert.equal(decodedInteractive.body?.text, "Deskripsi panjang");
579
+ assert.equal(decodedInteractive.footer?.text, "Footer");
580
+ });
581
+
582
+ test("header: payload round-trip protobuf — thumbnail-only header", async () => {
583
+ const jpeg = await makeJpeg({ width: 90, height: 90 });
584
+ const { client } = makeUploadClient();
585
+ const result = await button(client)
586
+ .title("Judul")
587
+ .headerThumbnail(jpeg)
588
+ .quick_reply("QR", "qr1")
589
+ .build();
590
+
591
+ const wire = proto.Message.encode(result).finish();
592
+ const decoded = proto.Message.decode(wire);
593
+ const header = (
594
+ decoded.interactiveMessage as NonNullable<typeof decoded.interactiveMessage>
595
+ ).header;
596
+ assert.ok(header?.hasMediaAttachment !== true);
597
+ assert.ok(!header?.imageMessage);
598
+ assert.ok(!header?.videoMessage);
599
+ assert.ok(!header?.documentMessage);
600
+ assert.ok(!header?.locationMessage);
601
+ assert.equal((header?.jpegThumbnail as Uint8Array).length, jpeg.byteLength);
602
+ });
603
+
604
+ test("header: upload lewat media gate (admission control)", async () => {
605
+ const gateCalls: unknown[] = [];
606
+ const queue = configureSharedMediaQueue({
607
+ concurrency: 1,
608
+ timeoutMs: 10_000,
609
+ });
610
+ const originalRun = queue.run.bind(queue);
611
+ (queue as unknown as { run: unknown }).run = (
612
+ fn: unknown,
613
+ opts?: { label?: string },
614
+ ) => {
615
+ gateCalls.push(opts?.label);
616
+ return originalRun(fn as never, opts);
617
+ };
618
+
619
+ try {
620
+ const jpeg = await makeJpeg();
621
+ const { client } = makeUploadClient();
622
+ await button(client).image(jpeg).quick_reply("QR", "qr1").build();
623
+ assert.equal(gateCalls.length, 1);
624
+ assert.equal(gateCalls[0], "btn-media:header image");
625
+ } finally {
626
+ resetSharedMediaQueue();
627
+ }
628
+ });
629
+
630
+ test("header: oversize melampaui maxBytes gate → ditolak jelas", async () => {
631
+ configureSharedMediaQueue({
632
+ concurrency: 1,
633
+ maxBytes: 64,
634
+ timeoutMs: 10_000,
635
+ });
636
+ try {
637
+ const jpeg = await makeJpeg({ width: 400, height: 400 });
638
+ const { client } = makeUploadClient();
639
+ await assert.rejects(
640
+ async () => button(client).image(jpeg).quick_reply("QR", "qr1").build(),
641
+ (error: Error) => /melebihi batas ukuran/.test(error.message),
642
+ );
643
+ } finally {
644
+ resetSharedMediaQueue();
645
+ }
646
+ });