@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,40 @@
1
+ export declare const DISPLAY_TEXT_MAX = 200;
2
+ export declare const BUTTON_ID_MAX = 256;
3
+ export declare const SELECT_TITLE_MAX = 100;
4
+ export declare const COPY_CODE_MAX = 50;
5
+ export declare const ROW_DESCRIPTION_MAX = 200;
6
+ export declare const LEGACY_BUTTON_LIMIT = 3;
7
+ export declare const LIST_SECTION_LIMIT = 10;
8
+ export declare const LIST_ROWS_PER_SECTION_LIMIT = 100;
9
+ export interface AssertTextOptions {
10
+ max?: number;
11
+ required?: boolean;
12
+ }
13
+ export declare function assertText(value: unknown, label: string, options: {
14
+ max?: number;
15
+ required: false;
16
+ }): string | undefined;
17
+ export declare function assertText(value: unknown, label: string, options?: {
18
+ max?: number;
19
+ required?: boolean;
20
+ }): string;
21
+ export declare const assertId: (value: unknown, label?: string) => string;
22
+ export declare const assertUniqueId: (ids: Set<string>, id: string) => string;
23
+ export declare const assertUrl: (value: unknown, label?: string) => string;
24
+ export declare const assertPhoneNumber: (value: unknown, label?: string) => string;
25
+ export interface AssertPositiveIntOptions {
26
+ min?: number;
27
+ }
28
+ export declare const assertPositiveInt: (value: unknown, label: string, { min }?: AssertPositiveIntOptions) => number;
29
+ export interface NativeSectionRow {
30
+ id: string;
31
+ title: string;
32
+ description?: string;
33
+ header?: string;
34
+ }
35
+ export interface NativeSection {
36
+ title?: string;
37
+ rows: NativeSectionRow[];
38
+ }
39
+ export declare const validateNativeSections: (sections: unknown, label?: string) => NativeSection[];
40
+ export declare const stringifyParams: (params: unknown, label?: string) => string;
@@ -0,0 +1,135 @@
1
+ import { ValidationError, DuplicateIdError } from "../core/errors.js";
2
+ export const DISPLAY_TEXT_MAX = 200;
3
+ export const BUTTON_ID_MAX = 256;
4
+ export const SELECT_TITLE_MAX = 100;
5
+ export const COPY_CODE_MAX = 50;
6
+ export const ROW_DESCRIPTION_MAX = 200;
7
+ export const LEGACY_BUTTON_LIMIT = 3;
8
+ export const LIST_SECTION_LIMIT = 10;
9
+ export const LIST_ROWS_PER_SECTION_LIMIT = 100;
10
+ export function assertText(value, label, { max = DISPLAY_TEXT_MAX, required = true } = {}) {
11
+ if (value === undefined || value === null || value === "") {
12
+ if (required)
13
+ throw new ValidationError(`${label} wajib diisi (string non-kosong)`);
14
+ return undefined;
15
+ }
16
+ if (typeof value !== "string")
17
+ throw new ValidationError(`${label} harus string, diterima ${typeof value}`);
18
+ if (required && value.trim() === "")
19
+ throw new ValidationError(`${label} wajib diisi (string non-kosong)`);
20
+ if (value.length > max)
21
+ throw new ValidationError(`${label} melebihi batas ${max} karakter (${value.length})`);
22
+ return value;
23
+ }
24
+ export const assertId = (value, label = "id") => {
25
+ if (value === undefined ||
26
+ value === null ||
27
+ typeof value !== "string" ||
28
+ value === "") {
29
+ throw new ValidationError(`${label} wajib diisi (string non-kosong)`);
30
+ }
31
+ if (value.length > BUTTON_ID_MAX) {
32
+ throw new ValidationError(`${label} melebihi batas ${BUTTON_ID_MAX} karakter (${value.length})`);
33
+ }
34
+ return value;
35
+ };
36
+ export const assertUniqueId = (ids, id) => {
37
+ if (ids.has(id))
38
+ throw new DuplicateIdError(id);
39
+ ids.add(id);
40
+ return id;
41
+ };
42
+ export const assertUrl = (value, label = "url") => {
43
+ if (value === undefined ||
44
+ value === null ||
45
+ typeof value !== "string" ||
46
+ value.trim() === "") {
47
+ throw new ValidationError(`${label} wajib diisi (string URL)`);
48
+ }
49
+ let parsed;
50
+ try {
51
+ parsed = new URL(value);
52
+ }
53
+ catch {
54
+ throw new ValidationError(`${label} bukan URL valid: "${value}"`);
55
+ }
56
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
57
+ throw new ValidationError(`${label} harus http/https, diterima "${parsed.protocol}"`);
58
+ }
59
+ return value;
60
+ };
61
+ export const assertPhoneNumber = (value, label = "nomor telepon") => {
62
+ if (value === undefined ||
63
+ value === null ||
64
+ typeof value !== "string" ||
65
+ value.trim() === "") {
66
+ throw new ValidationError(`${label} wajib diisi (string nomor)`);
67
+ }
68
+ if (!/^\+?[1-9]\d{6,14}$/.test(value)) {
69
+ throw new ValidationError(`${label} tidak valid (format E.164, 7-15 digit): "${value}"`);
70
+ }
71
+ return value;
72
+ };
73
+ export const assertPositiveInt = (value, label, { min = 1 } = {}) => {
74
+ if (typeof value !== "number" ||
75
+ !Number.isFinite(value) ||
76
+ value < min ||
77
+ !Number.isInteger(value)) {
78
+ throw new ValidationError(`${label} harus integer >= ${min}, diterima ${value}`);
79
+ }
80
+ return value;
81
+ };
82
+ export const validateNativeSections = (sections, label = "sections") => {
83
+ if (!Array.isArray(sections) || sections.length === 0) {
84
+ throw new ValidationError(`${label} harus array berisi minimal satu section`);
85
+ }
86
+ if (sections.length > LIST_SECTION_LIMIT) {
87
+ throw new ValidationError(`${label} melebihi batas ${LIST_SECTION_LIMIT} section (${sections.length})`);
88
+ }
89
+ const rowIds = new Set();
90
+ sections.forEach((section, sectionIndex) => {
91
+ if (!section || typeof section !== "object" || Array.isArray(section)) {
92
+ throw new ValidationError(`${label}[${sectionIndex}] harus object section`);
93
+ }
94
+ const record = section;
95
+ assertText(record.title, `${label}[${sectionIndex}].title`, {
96
+ max: SELECT_TITLE_MAX,
97
+ required: false,
98
+ });
99
+ if (!Array.isArray(record.rows) || record.rows.length === 0) {
100
+ throw new ValidationError(`${label}[${sectionIndex}].rows harus array berisi minimal satu row`);
101
+ }
102
+ if (record.rows.length > LIST_ROWS_PER_SECTION_LIMIT) {
103
+ throw new ValidationError(`${label}[${sectionIndex}].rows melebihi batas ${LIST_ROWS_PER_SECTION_LIMIT} row (${record.rows.length})`);
104
+ }
105
+ record.rows.forEach((row, rowIndex) => {
106
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
107
+ throw new ValidationError(`${label}[${sectionIndex}].rows[${rowIndex}] harus object row`);
108
+ }
109
+ const rowRecord = row;
110
+ const rowId = assertId(rowRecord.id, `${label}[${sectionIndex}].rows[${rowIndex}].id`);
111
+ assertText(rowRecord.title, `${label}[${sectionIndex}].rows[${rowIndex}].title`);
112
+ assertText(rowRecord.description, `${label}[${sectionIndex}].rows[${rowIndex}].description`, { max: ROW_DESCRIPTION_MAX, required: false });
113
+ assertText(rowRecord.header, `${label}[${sectionIndex}].rows[${rowIndex}].header`, { required: false });
114
+ if (rowIds.has(rowId))
115
+ throw new DuplicateIdError(rowId);
116
+ rowIds.add(rowId);
117
+ });
118
+ });
119
+ return sections;
120
+ };
121
+ export const stringifyParams = (params, label = "buttonParamsJson") => {
122
+ let json;
123
+ try {
124
+ json = JSON.stringify(params);
125
+ }
126
+ catch (error) {
127
+ throw new ValidationError(`${label} gagal diserialisasi ke JSON`, {
128
+ cause: error,
129
+ });
130
+ }
131
+ if (json === undefined) {
132
+ throw new ValidationError(`${label} menghasilkan undefined — parameter mengandung nilai yang tidak bisa diserialisasi`);
133
+ }
134
+ return json;
135
+ };
package/dist/btn.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { Button, LegacyButton, ListMessage, button, legacyButton, listMessage, } from "./btn/builders.js";
package/dist/btn.js ADDED
@@ -0,0 +1 @@
1
+ export { Button, LegacyButton, ListMessage, button, legacyButton, listMessage, } from "./btn/builders.js";
@@ -0,0 +1,20 @@
1
+ import type { BaseBuilder } from "./base-builder.js";
2
+ import type { ZapoMessageContent } from "../zapo-client.js";
3
+ import type { MessageSendResult } from "../zapo-client.js";
4
+ export interface MessageSendOptions {
5
+ quote?: unknown;
6
+ mentions?: readonly string[];
7
+ contextInfo?: Record<string, unknown>;
8
+ forward?: boolean | {
9
+ score?: number;
10
+ };
11
+ id?: string;
12
+ expirationSeconds?: number;
13
+ additionalAttributes?: Readonly<Record<string, string>>;
14
+ viewOnce?: boolean;
15
+ messageSecret?: Uint8Array;
16
+ ackTimeoutMs?: number;
17
+ maxAttempts?: number;
18
+ retryDelayMs?: number;
19
+ }
20
+ export declare const sendConfigured: <TBuild extends ZapoMessageContent>(builder: BaseBuilder<TBuild>, jid: string | undefined, options: MessageSendOptions | undefined) => Promise<MessageSendResult>;
@@ -0,0 +1 @@
1
+ export const sendConfigured = async (builder, jid, options) => (await builder.send(jid, (options ?? {})));
@@ -0,0 +1,20 @@
1
+ import type { ZapoClient, ZapoMessageContent } from "../zapo-client.js";
2
+ import type { BuilderMessagePayload } from "../payloads.js";
3
+ export declare const isClient: (value: unknown) => value is ZapoClient;
4
+ export type SendResolutionArg = ZapoClient | Record<string, unknown>;
5
+ export declare class BaseBuilder<TBuild extends ZapoMessageContent = BuilderMessagePayload> {
6
+ #private;
7
+ constructor(client?: ZapoClient);
8
+ use(client: ZapoClient): this;
9
+ get client(): ZapoClient | undefined;
10
+ defaultTo(jid: string | undefined): this;
11
+ to(jid: string | undefined): this;
12
+ defaultQuote(ref: unknown): this;
13
+ protected _defaultTarget(): string | undefined;
14
+ build(): TBuild | Promise<TBuild>;
15
+ protected _resolve(arg?: SendResolutionArg): {
16
+ client: ZapoClient;
17
+ options: Record<string, unknown>;
18
+ };
19
+ send(jid?: string, arg?: SendResolutionArg): Promise<unknown>;
20
+ }
@@ -0,0 +1,67 @@
1
+ import { MessageError } from "./errors.js";
2
+ export const isClient = (value) => typeof value?.message?.send === "function";
3
+ export class BaseBuilder {
4
+ #client;
5
+ #defaultJid;
6
+ #defaultQuote;
7
+ constructor(client) {
8
+ if (client !== undefined)
9
+ this.use(client);
10
+ }
11
+ use(client) {
12
+ if (!isClient(client))
13
+ throw new TypeError("client harus WaClient zapo-js (punya client.message.send)");
14
+ this.#client = client;
15
+ return this;
16
+ }
17
+ get client() {
18
+ return this.#client;
19
+ }
20
+ defaultTo(jid) {
21
+ if (jid !== undefined && (typeof jid !== "string" || !jid)) {
22
+ throw new TypeError("defaultTo() butuh jid string");
23
+ }
24
+ this.#defaultJid = jid;
25
+ return this;
26
+ }
27
+ to(jid) {
28
+ return this.defaultTo(jid);
29
+ }
30
+ defaultQuote(ref) {
31
+ this.#defaultQuote = ref;
32
+ return this;
33
+ }
34
+ _defaultTarget() {
35
+ return this.#defaultJid;
36
+ }
37
+ build() {
38
+ throw new MessageError(`${this.constructor.name}.build() belum diimplementasi`, "NOT_IMPLEMENTED");
39
+ }
40
+ _resolve(arg) {
41
+ const resolved = isClient(arg)
42
+ ? { client: arg }
43
+ : (arg ?? {});
44
+ const { client: resolvedClient, ...options } = resolved;
45
+ const client = resolvedClient === undefined
46
+ ? this.#client
47
+ : resolvedClient;
48
+ if (!client)
49
+ throw new MessageError("client belum diset", "NO_CLIENT");
50
+ return { client, options };
51
+ }
52
+ async send(jid, arg) {
53
+ const { client, options } = this._resolve(arg);
54
+ const target = typeof jid === "string" && jid ? jid : this.#defaultJid;
55
+ if (!target) {
56
+ throw new MessageError("tujuan tidak diketahui. panggil send(jid), .defaultTo(jid), atau buat lewat ctx.button()/ctx.list()", "NO_TARGET");
57
+ }
58
+ const merged = this.#defaultQuote !== undefined && options.quote === undefined
59
+ ? { quote: this.#defaultQuote, ...options }
60
+ : options;
61
+ const content = await this.build();
62
+ const send = client.message.send.bind(client.message);
63
+ return Object.keys(merged).length
64
+ ? send(target, content, merged)
65
+ : send(target, content);
66
+ }
67
+ }
@@ -0,0 +1,30 @@
1
+ export interface MessageErrorMeta {
2
+ [key: string]: unknown;
3
+ }
4
+ export declare class MessageError extends Error {
5
+ code: string;
6
+ constructor(message: string, code?: string, meta?: MessageErrorMeta);
7
+ }
8
+ export declare class ValidationError extends MessageError {
9
+ constructor(message: string, meta?: MessageErrorMeta);
10
+ }
11
+ export declare class ItemNotFoundError extends MessageError {
12
+ readonly id: string | number;
13
+ readonly availableIds: string[];
14
+ constructor(id: string | number, availableIds?: string[]);
15
+ }
16
+ export declare class DuplicateIdError extends MessageError {
17
+ readonly id: string;
18
+ constructor(id: string);
19
+ }
20
+ export declare class MediaError extends MessageError {
21
+ constructor(message: string, meta?: MessageErrorMeta);
22
+ }
23
+ export declare class InvalidTargetError extends MessageError {
24
+ constructor(message: string, meta?: MessageErrorMeta);
25
+ }
26
+ export declare class ProtocolSendError extends MessageError {
27
+ readonly stage: string;
28
+ readonly placeholderId: string | undefined;
29
+ constructor(stage: string, meta?: MessageErrorMeta);
30
+ }
@@ -0,0 +1,61 @@
1
+ export class MessageError extends Error {
2
+ code;
3
+ constructor(message, code = "MESSAGE_ERROR", meta = {}) {
4
+ super(message);
5
+ this.name = new.target.name;
6
+ this.code = code;
7
+ Object.assign(this, meta);
8
+ }
9
+ }
10
+ export class ValidationError extends MessageError {
11
+ constructor(message, meta = {}) {
12
+ super(message, "VALIDATION", meta);
13
+ }
14
+ }
15
+ export class ItemNotFoundError extends MessageError {
16
+ constructor(id, availableIds = []) {
17
+ const hint = availableIds.length
18
+ ? ` (tersedia: ${availableIds.join(", ")})`
19
+ : " (belum ada item yang punya id)";
20
+ super(`item "${id}" ga ketemu${hint}`, "ITEM_NOT_FOUND", {
21
+ id,
22
+ availableIds,
23
+ });
24
+ }
25
+ }
26
+ export class DuplicateIdError extends MessageError {
27
+ constructor(id) {
28
+ super(`id "${id}" udah dipake`, "DUPLICATE_ID", { id });
29
+ }
30
+ }
31
+ export class MediaError extends MessageError {
32
+ constructor(message, meta = {}) {
33
+ super(message, "MEDIA", meta);
34
+ if (meta.cause !== undefined)
35
+ this.cause = meta.cause;
36
+ else if (meta.originalError !== undefined)
37
+ this.cause = meta.originalError;
38
+ }
39
+ }
40
+ export class InvalidTargetError extends MessageError {
41
+ constructor(message, meta = {}) {
42
+ super(message, "INVALID_TARGET", meta);
43
+ }
44
+ }
45
+ export class ProtocolSendError extends MessageError {
46
+ constructor(stage, meta = {}) {
47
+ const detail = stage === "edit"
48
+ ? `edit AIRich gagal setelah placeholder terkirim (placeholderId: ${meta.placeholderId})`
49
+ : stage === "validate_id"
50
+ ? "transport Zapo tidak mengembalikan ID pesan yang valid; edit dibatalkan"
51
+ : stage === "album_id"
52
+ ? "pengiriman album gagal — id pesan album tidak tersedia dari hasil send"
53
+ : "pengiriman placeholder AIRich gagal";
54
+ super(detail, "PROTOCOL_SEND", { stage, ...meta });
55
+ this.stage = stage;
56
+ if (meta.cause !== undefined)
57
+ this.cause = meta.cause;
58
+ if (meta.placeholderId !== undefined)
59
+ this.placeholderId = meta.placeholderId;
60
+ }
61
+ }
@@ -0,0 +1,24 @@
1
+ import { type LimitedStream } from "./media-gate.js";
2
+ import type { ZapoDownloadCapableClient } from "./zapo-client.js";
3
+ interface ThumbnailMediaRecord {
4
+ mediaKey?: Uint8Array;
5
+ thumbnailDirectPath?: string;
6
+ thumbnailEncSha256?: Uint8Array;
7
+ thumbnailSha256?: Uint8Array;
8
+ }
9
+ declare const downloadThumbnail: (mode: "bytes" | "stream", etm: ThumbnailMediaRecord) => Promise<unknown>;
10
+ export interface DownloadReceiver {
11
+ content?: string | undefined;
12
+ message?: Record<string, unknown> | undefined;
13
+ client: ZapoDownloadCapableClient;
14
+ }
15
+ declare function mDownload(this: DownloadReceiver, dataType: "buffer" | "stream"): Promise<unknown>;
16
+ export interface QuotedDownloadReceiver {
17
+ content?: string | undefined;
18
+ message?: Record<string, unknown> | undefined;
19
+ key?: Record<string, unknown>;
20
+ client: ZapoDownloadCapableClient;
21
+ }
22
+ declare function qDownload(this: QuotedDownloadReceiver, dataType: "bytes" | "stream"): Promise<unknown>;
23
+ export { mDownload, qDownload, downloadThumbnail };
24
+ export type { LimitedStream };
@@ -0,0 +1,123 @@
1
+ import { WaMediaTransferClient } from "zapo-js";
2
+ import { Readable } from "node:stream";
3
+ import { getSharedMediaQueue, limitStreamBytes, } from "./media-gate.js";
4
+ const waMediaTransfer = new WaMediaTransferClient();
5
+ const throughMediaGate = async (label, mode, work) => {
6
+ const queue = getSharedMediaQueue();
7
+ return queue.run(async ({ signal, maxBytes, noteBytes }) => {
8
+ const result = await work();
9
+ if (mode === "buffer") {
10
+ const bytes = result instanceof Uint8Array
11
+ ? result
12
+ : new Uint8Array((result ?? []));
13
+ noteBytes(bytes.byteLength);
14
+ if (bytes.byteLength > maxBytes) {
15
+ queue.markOversized();
16
+ throw new Error(`media melebihi batas ukuran (${bytes.byteLength} > ${maxBytes} byte)`);
17
+ }
18
+ if (signal.aborted) {
19
+ throw new Error(`media job dibatalkan (signal)`);
20
+ }
21
+ return Buffer.from(bytes);
22
+ }
23
+ if (signal.aborted) {
24
+ throw new Error(`media job dibatalkan (signal)`);
25
+ }
26
+ const stream = result;
27
+ if (stream && typeof stream.pipe === "function") {
28
+ return limitStreamBytes(stream, maxBytes, () => queue.markOversized());
29
+ }
30
+ return stream;
31
+ }, { label: `wa-media:${label}` });
32
+ };
33
+ const thumbnailRequest = (etm) => ({
34
+ mediaType: "thumbnail-link",
35
+ mediaKey: etm.mediaKey,
36
+ directPath: etm.thumbnailDirectPath,
37
+ fileEncSha256: etm.thumbnailEncSha256,
38
+ fileSha256: etm.thumbnailSha256,
39
+ });
40
+ const downloadThumbnail = async (mode, etm) => {
41
+ if (mode === "bytes") {
42
+ return throughMediaGate("thumbnail", "buffer", async () => {
43
+ try {
44
+ return await waMediaTransfer.downloadAndDecrypt(thumbnailRequest(etm));
45
+ }
46
+ catch (error) {
47
+ if (error.message === "media MAC mismatch") {
48
+ return await waMediaTransfer.downloadAndDecrypt({
49
+ ...thumbnailRequest(etm),
50
+ mediaType: "image",
51
+ });
52
+ }
53
+ throw error;
54
+ }
55
+ });
56
+ }
57
+ return throughMediaGate("thumbnail", "stream", async () => {
58
+ try {
59
+ const { plaintext } = await waMediaTransfer.downloadAndDecryptStream(thumbnailRequest(etm));
60
+ return plaintext;
61
+ }
62
+ catch (error) {
63
+ if (error.message === "media MAC mismatch") {
64
+ const { plaintext } = await waMediaTransfer.downloadAndDecryptStream({
65
+ ...thumbnailRequest(etm),
66
+ mediaType: "image",
67
+ });
68
+ return plaintext;
69
+ }
70
+ throw error;
71
+ }
72
+ });
73
+ };
74
+ async function mDownload(dataType) {
75
+ const etm = this?.message
76
+ ?.extendedTextMessage;
77
+ if (this?.content === "extendedTextMessage" && etm?.mediaKey) {
78
+ if (dataType === "buffer") {
79
+ return throughMediaGate("m-etm", "buffer", async () => {
80
+ const bytes = await waMediaTransfer.downloadAndDecrypt(thumbnailRequest(etm));
81
+ return Buffer.from(bytes);
82
+ });
83
+ }
84
+ return downloadThumbnail("stream", etm);
85
+ }
86
+ if (dataType === "buffer") {
87
+ return throughMediaGate("m-message", "buffer", async () => {
88
+ const bytes = await this.client.message.downloadBytes(this);
89
+ return Buffer.from(bytes);
90
+ });
91
+ }
92
+ return throughMediaGate("m-message", "stream", async () => this.client.message.download(this));
93
+ }
94
+ async function qDownload(dataType) {
95
+ const isExtendedText = this?.content === "extendedTextMessage";
96
+ const etm = this?.message
97
+ ?.extendedTextMessage;
98
+ if (isExtendedText && etm?.mediaKey) {
99
+ return downloadThumbnail(dataType === "bytes" ? "bytes" : "stream", etm);
100
+ }
101
+ if (isExtendedText && etm?.jpegThumbnail) {
102
+ const bytes = etm.jpegThumbnail;
103
+ return dataType === "bytes" ? Buffer.from(bytes) : Readable.from([bytes]);
104
+ }
105
+ if (isExtendedText) {
106
+ const message = this.message;
107
+ if (dataType === "bytes") {
108
+ return throughMediaGate("q-etm", "buffer", async () => this.client.message.downloadBytes(message));
109
+ }
110
+ return throughMediaGate("q-etm", "stream", async () => this.client.message.download(message));
111
+ }
112
+ if (this?.content === "groupStatusMessageV2") {
113
+ const groupStatusMessageV2 = this.message
114
+ .groupStatusMessageV2;
115
+ return this.client.message.download(groupStatusMessageV2.message);
116
+ }
117
+ const message = this.message;
118
+ if (dataType === "bytes") {
119
+ return throughMediaGate("q-message", "buffer", async () => this.client.message.downloadBytes(message));
120
+ }
121
+ return throughMediaGate("q-message", "stream", async () => this.client.message.download(message));
122
+ }
123
+ export { mDownload, qDownload, downloadThumbnail };
@@ -0,0 +1,38 @@
1
+ import "./integration/auto.js";
2
+ import type { ZapoClient } from "./zapo-client.js";
3
+ import type { AIRichConstructorOptions } from "./airich/airich.js";
4
+ export { BaseBuilder, isClient } from "./core/base-builder.js";
5
+ export type { SendResolutionArg } from "./core/base-builder.js";
6
+ export type { MessageSendOptions } from "./core/async-send.js";
7
+ export { MessageError, ValidationError, ItemNotFoundError, DuplicateIdError, InvalidTargetError, ProtocolSendError, MediaError, } from "./core/errors.js";
8
+ export { Button, LegacyButton, ListMessage, button, legacyButton, listMessage, } from "./btn.js";
9
+ export type { ImageHeaderOptions, VideoHeaderOptions, DocumentHeaderOptions, LocationHeaderOptions, ListRowInput, ListFallbackMode, ButtonConfig, LegacyButtonConfig, ListMessageConfig, ListSectionConfig, InteractiveHeaderConfig, LegacyButtonHeaderConfig, ButtonItemConfig, BottomSheetConfig, LimitedTimeOfferConfig, } from "./btn/builders.js";
10
+ export type { NativeSection, NativeSectionRow } from "./btn/validators.js";
11
+ export { AIRich, airich, parseInline, toTable, tokenizeCode, } from "./airich/index.js";
12
+ export type { AIRichConstructorOptions, AIRichConfig, AIRichSectionConfig, AIRichSendOptions, RawNodeOptions, InsertNodeOptions, QuotableMessage, RichTarget, } from "./airich/index.js";
13
+ export type { InlineEntity, ParsedInline, ParseInlineOptions, } from "./airich/index.js";
14
+ export type { TokenizeResult, CodeBlockToken, UnifiedCodeToken, } from "./airich/index.js";
15
+ export { encodeUnifiedResponse, decodeUnifiedResponse, stringifyEscaped, } from "./airich/encode.js";
16
+ export { buildRichResponse, wrapBotForwarded, buildPlaceholderContent, buildEditContent, layout, ZWSP, } from "./airich/protocol.js";
17
+ export type { UnifiedResponseSection, UnifiedViewModel, RichResponseInput, PlaceholderInput, EditInput, } from "./airich/protocol.js";
18
+ export { forwardInfo, buildContextInfo, filterContextInfo, ALLOWED_CONTEXT_FIELDS, BUILDER_CONTROLLED_CONTEXT_FIELDS, } from "./airich/context.js";
19
+ export type { QuoteInfo, AllowedContextInfo } from "./airich/context.js";
20
+ export { sendViaZapo, sendPlaceholderThenEdit, sendAttributes, isZapoClient, } from "./airich/transport.js";
21
+ export { EXPERIMENTAL_PRIMITIVES } from "./airich/primitives.js";
22
+ export type { SourceInput, FooterActionItem, WidgetItem, ProductItem, PostItem, ReelsItem, } from "./airich/primitives.js";
23
+ export type { ButtonBuildResult, LegacyButtonBuildResult, ListBuildResult, WrapBotForwardedResult, PlaceholderBuildResult, EditBuildResult, MediaSlotResolution, } from "./payloads.js";
24
+ export type { ZapoClient, ZapoSendOptions, ZapoMessageContent, ZapoMessageCoordinator, ZapoAuthLike, ZapoDownloadCapableClient, ZapoReactionContent, ZapoPollContent, MessageSendResult, } from "./zapo-client.js";
25
+ export type { TextBuildResult, LinkPreviewBuildResult, ExtendedTextMessagePayload, ContactBuildResult, ContactMessagePayload, AlbumBuildResult, AlbumMessagePayload, LocationBuildResult, LocationMessagePayload, MediaBuildResult, MediaMessageKind, } from "./payloads.js";
26
+ export { mediaSlotToMessage } from "./payloads.js";
27
+ export { TextBuilder, text, LinkPreviewBuilder, linkPreview, ReactionBuilder, reaction, ForwardBuilder, forward, ContactBuilder, contact, PollBuilder, poll, MediaBuilder, media, image, video, audio, document, StickerBuilder, sticker, AlbumBuilder, album, LocationBuilder, location, probeWebp, buildVcard, targetKeyOf, targetChatJidOf, targetIdOf, } from "./message/index.js";
28
+ export type { TextConfig, LinkPreviewConfig, ReactionConfig, ForwardConfig, ContactConfig, PollConfig, MediaConfig, MediaImageConfig, MediaVideoConfig, MediaAudioConfig, MediaDocumentConfig, ImageMediaOptions, VideoMediaOptions, AudioMediaOptions, DocumentMediaOptions, ImageMessageConfig, VideoMessageConfig, AudioMessageConfig, DocumentMessageConfig, StickerConfig, StickerMediaOptions, AlbumConfig, AlbumMediaItem, LocationConfig, LinkPreviewKind, AlbumChild, WebpInfo, VcardInput, MessageKeyLike, MessageTargetLike, } from "./message/index.js";
29
+ export { installZapoMessage, installOnPrototype, autoInstallStatus, } from "./integration/auto.js";
30
+ export { zapoMessageMethods, ZAPO_MESSAGE_METHOD_NAMES, } from "./integration/methods.js";
31
+ export type { ZapoMessageMethodName } from "./integration/methods.js";
32
+ export type { ZapoMessageClientMethods } from "./integration/augment.js";
33
+ export declare const messageKit: (client?: ZapoClient) => {
34
+ button: () => import("./btn.js").Button;
35
+ legacyButton: () => import("./btn.js").LegacyButton;
36
+ listMessage: () => import("./btn.js").ListMessage;
37
+ airich: (options?: AIRichConstructorOptions) => import("./airich/airich.js").AIRich;
38
+ };
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ import "./integration/auto.js";
2
+ import { button, legacyButton, listMessage } from "./btn.js";
3
+ import { airich } from "./airich/index.js";
4
+ export { BaseBuilder, isClient } from "./core/base-builder.js";
5
+ export { MessageError, ValidationError, ItemNotFoundError, DuplicateIdError, InvalidTargetError, ProtocolSendError, MediaError, } from "./core/errors.js";
6
+ export { Button, LegacyButton, ListMessage, button, legacyButton, listMessage, } from "./btn.js";
7
+ export { AIRich, airich, parseInline, toTable, tokenizeCode, } from "./airich/index.js";
8
+ export { encodeUnifiedResponse, decodeUnifiedResponse, stringifyEscaped, } from "./airich/encode.js";
9
+ export { buildRichResponse, wrapBotForwarded, buildPlaceholderContent, buildEditContent, layout, ZWSP, } from "./airich/protocol.js";
10
+ export { forwardInfo, buildContextInfo, filterContextInfo, ALLOWED_CONTEXT_FIELDS, BUILDER_CONTROLLED_CONTEXT_FIELDS, } from "./airich/context.js";
11
+ export { sendViaZapo, sendPlaceholderThenEdit, sendAttributes, isZapoClient, } from "./airich/transport.js";
12
+ export { EXPERIMENTAL_PRIMITIVES } from "./airich/primitives.js";
13
+ export { mediaSlotToMessage } from "./payloads.js";
14
+ export { TextBuilder, text, LinkPreviewBuilder, linkPreview, ReactionBuilder, reaction, ForwardBuilder, forward, ContactBuilder, contact, PollBuilder, poll, MediaBuilder, media, image, video, audio, document, StickerBuilder, sticker, AlbumBuilder, album, LocationBuilder, location, probeWebp, buildVcard, targetKeyOf, targetChatJidOf, targetIdOf, } from "./message/index.js";
15
+ export { installZapoMessage, installOnPrototype, autoInstallStatus, } from "./integration/auto.js";
16
+ export { zapoMessageMethods, ZAPO_MESSAGE_METHOD_NAMES, } from "./integration/methods.js";
17
+ export const messageKit = (client) => ({
18
+ button: () => button(client),
19
+ legacyButton: () => legacyButton(client),
20
+ listMessage: () => listMessage(client),
21
+ airich: (options) => airich(client, options),
22
+ });