@kodelyth/zalo 2026.5.39 → 2026.5.42

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 (97) hide show
  1. package/README.md +50 -0
  2. package/api.ts +8 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +5 -0
  5. package/dist/actions.runtime-C61oPfyd.js +5 -0
  6. package/dist/api.js +5 -0
  7. package/dist/channel-D8ylaEdN.js +367 -0
  8. package/dist/channel-plugin-api.js +2 -0
  9. package/dist/channel.runtime-sf-rx5n-.js +105 -0
  10. package/dist/contract-api.js +3 -0
  11. package/dist/group-access-DTQVR6Nd.js +15 -0
  12. package/dist/index.js +22 -0
  13. package/dist/monitor-CQ1bjGih.js +825 -0
  14. package/dist/monitor.webhook-CDxUxa9l.js +175 -0
  15. package/dist/runtime-api-CxXTp1Q2.js +23 -0
  16. package/dist/runtime-api.js +2 -0
  17. package/dist/secret-contract-CRFukr2n.js +87 -0
  18. package/dist/secret-contract-api.js +2 -0
  19. package/dist/send-CGAqdfSA.js +270 -0
  20. package/dist/setup-api.js +30 -0
  21. package/dist/setup-core-Dr75wK6l.js +287 -0
  22. package/dist/setup-entry.js +15 -0
  23. package/dist/setup-surface-C8zxrnzG.js +216 -0
  24. package/dist/test-api.js +2 -0
  25. package/index.test.ts +15 -0
  26. package/index.ts +20 -0
  27. package/klaw.plugin.json +2 -509
  28. package/package.json +4 -4
  29. package/runtime-api.test.ts +10 -0
  30. package/runtime-api.ts +71 -0
  31. package/secret-contract-api.ts +5 -0
  32. package/setup-api.ts +34 -0
  33. package/setup-entry.ts +13 -0
  34. package/src/accounts.test.ts +95 -0
  35. package/src/accounts.ts +65 -0
  36. package/src/actions.runtime.ts +5 -0
  37. package/src/actions.test.ts +32 -0
  38. package/src/actions.ts +62 -0
  39. package/src/api.test.ts +166 -0
  40. package/src/api.ts +265 -0
  41. package/src/approval-auth.test.ts +17 -0
  42. package/src/approval-auth.ts +25 -0
  43. package/src/channel.directory.test.ts +56 -0
  44. package/src/channel.runtime.ts +89 -0
  45. package/src/channel.startup.test.ts +121 -0
  46. package/src/channel.ts +309 -0
  47. package/src/config-schema.test.ts +30 -0
  48. package/src/config-schema.ts +29 -0
  49. package/src/group-access.ts +23 -0
  50. package/src/monitor-durable.test.ts +49 -0
  51. package/src/monitor-durable.ts +38 -0
  52. package/src/monitor.group-policy.test.ts +213 -0
  53. package/src/monitor.image.polling.test.ts +113 -0
  54. package/src/monitor.lifecycle.test.ts +194 -0
  55. package/src/monitor.pairing.lifecycle.test.ts +139 -0
  56. package/src/monitor.polling.media-reply.test.ts +433 -0
  57. package/src/monitor.reply-once.lifecycle.test.ts +178 -0
  58. package/src/monitor.ts +1009 -0
  59. package/src/monitor.types.ts +4 -0
  60. package/src/monitor.webhook.test.ts +808 -0
  61. package/src/monitor.webhook.ts +278 -0
  62. package/src/outbound-media.test.ts +186 -0
  63. package/src/outbound-media.ts +236 -0
  64. package/src/outbound-payload.contract.test.ts +143 -0
  65. package/src/probe.ts +45 -0
  66. package/src/proxy.ts +18 -0
  67. package/src/runtime-api.ts +71 -0
  68. package/src/runtime-support.ts +82 -0
  69. package/src/runtime.ts +9 -0
  70. package/src/secret-contract.ts +109 -0
  71. package/src/secret-input.ts +5 -0
  72. package/src/send.test.ts +150 -0
  73. package/src/send.ts +207 -0
  74. package/src/session-route.ts +32 -0
  75. package/src/setup-allow-from.ts +97 -0
  76. package/src/setup-core.ts +152 -0
  77. package/src/setup-status.test.ts +33 -0
  78. package/src/setup-surface.test.ts +193 -0
  79. package/src/setup-surface.ts +294 -0
  80. package/src/status-issues.test.ts +17 -0
  81. package/src/status-issues.ts +34 -0
  82. package/src/test-support/lifecycle-test-support.ts +456 -0
  83. package/src/test-support/monitor-mocks-test-support.ts +209 -0
  84. package/src/token.test.ts +92 -0
  85. package/src/token.ts +79 -0
  86. package/src/types.ts +50 -0
  87. package/test-api.ts +1 -0
  88. package/tsconfig.json +16 -0
  89. package/api.js +0 -7
  90. package/channel-plugin-api.js +0 -7
  91. package/contract-api.js +0 -7
  92. package/index.js +0 -7
  93. package/runtime-api.js +0 -7
  94. package/secret-contract-api.js +0 -7
  95. package/setup-api.js +0 -7
  96. package/setup-entry.js +0 -7
  97. package/test-api.js +0 -7
@@ -0,0 +1,95 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ listEnabledZaloAccounts,
4
+ listZaloAccountIds,
5
+ resolveDefaultZaloAccountId,
6
+ resolveZaloAccount,
7
+ } from "./accounts.js";
8
+
9
+ describe("resolveZaloAccount", () => {
10
+ it("resolves account config when account key casing differs from normalized id", () => {
11
+ const resolved = resolveZaloAccount({
12
+ cfg: {
13
+ channels: {
14
+ zalo: {
15
+ webhookUrl: "https://top.example.com",
16
+ accounts: {
17
+ Work: {
18
+ name: "Work",
19
+ webhookUrl: "https://work.example.com",
20
+ },
21
+ },
22
+ },
23
+ },
24
+ },
25
+ accountId: "work",
26
+ });
27
+
28
+ expect(resolved.accountId).toBe("work");
29
+ expect(resolved.name).toBe("Work");
30
+ expect(resolved.config.webhookUrl).toBe("https://work.example.com");
31
+ });
32
+
33
+ it("falls back to top-level config for named accounts without overrides", () => {
34
+ const resolved = resolveZaloAccount({
35
+ cfg: {
36
+ channels: {
37
+ zalo: {
38
+ enabled: true,
39
+ webhookUrl: "https://top.example.com",
40
+ accounts: {
41
+ work: {},
42
+ },
43
+ },
44
+ },
45
+ },
46
+ accountId: "work",
47
+ });
48
+
49
+ expect(resolved.accountId).toBe("work");
50
+ expect(resolved.enabled).toBe(true);
51
+ expect(resolved.config.webhookUrl).toBe("https://top.example.com");
52
+ });
53
+
54
+ it("uses configured defaultAccount when accountId is omitted", () => {
55
+ const resolved = resolveZaloAccount({
56
+ cfg: {
57
+ channels: {
58
+ zalo: {
59
+ defaultAccount: "work",
60
+ accounts: {
61
+ work: {
62
+ name: "Work",
63
+ botToken: "work-token",
64
+ },
65
+ },
66
+ },
67
+ },
68
+ },
69
+ });
70
+
71
+ expect(resolved.accountId).toBe("work");
72
+ expect(resolved.name).toBe("Work");
73
+ expect(resolved.token).toBe("work-token");
74
+ });
75
+
76
+ it("keeps the implicit default account when named accounts are added to top-level credentials", () => {
77
+ const cfg = {
78
+ channels: {
79
+ zalo: {
80
+ botToken: "default-token",
81
+ accounts: {
82
+ work: {
83
+ enabled: false,
84
+ botToken: "work-token",
85
+ },
86
+ },
87
+ },
88
+ },
89
+ };
90
+
91
+ expect(listZaloAccountIds(cfg)).toEqual(["default", "work"]);
92
+ expect(resolveDefaultZaloAccountId(cfg)).toBe("default");
93
+ expect(listEnabledZaloAccounts(cfg).map((account) => account.accountId)).toEqual(["default"]);
94
+ });
95
+ });
@@ -0,0 +1,65 @@
1
+ import {
2
+ createAccountListHelpers,
3
+ resolveMergedAccountConfig,
4
+ } from "klaw/plugin-sdk/account-helpers";
5
+ import { normalizeAccountId } from "klaw/plugin-sdk/account-id";
6
+ import type { KlawConfig } from "klaw/plugin-sdk/config-contracts";
7
+ import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
8
+ import { resolveZaloToken } from "./token.js";
9
+ import type { ResolvedZaloAccount, ZaloAccountConfig, ZaloConfig } from "./types.js";
10
+
11
+ export type { ResolvedZaloAccount };
12
+
13
+ const { listAccountIds: listZaloAccountIds, resolveDefaultAccountId: resolveDefaultZaloAccountId } =
14
+ createAccountListHelpers("zalo", {
15
+ implicitDefaultAccount: {
16
+ channelKeys: ["botToken", "tokenFile"],
17
+ envVars: ["ZALO_BOT_TOKEN"],
18
+ },
19
+ });
20
+ export { listZaloAccountIds, resolveDefaultZaloAccountId };
21
+
22
+ function mergeZaloAccountConfig(cfg: KlawConfig, accountId: string): ZaloAccountConfig {
23
+ return resolveMergedAccountConfig<ZaloAccountConfig>({
24
+ channelConfig: cfg.channels?.zalo as ZaloAccountConfig | undefined,
25
+ accounts: (cfg.channels?.zalo as ZaloConfig | undefined)?.accounts as
26
+ | Record<string, Partial<ZaloAccountConfig>>
27
+ | undefined,
28
+ accountId,
29
+ omitKeys: ["defaultAccount"],
30
+ });
31
+ }
32
+
33
+ export function resolveZaloAccount(params: {
34
+ cfg: KlawConfig;
35
+ accountId?: string | null;
36
+ allowUnresolvedSecretRef?: boolean;
37
+ }): ResolvedZaloAccount {
38
+ const accountId = normalizeAccountId(
39
+ params.accountId ?? (params.cfg.channels?.zalo as ZaloConfig | undefined)?.defaultAccount,
40
+ );
41
+ const baseEnabled = (params.cfg.channels?.zalo as ZaloConfig | undefined)?.enabled !== false;
42
+ const merged = mergeZaloAccountConfig(params.cfg, accountId);
43
+ const accountEnabled = merged.enabled !== false;
44
+ const enabled = baseEnabled && accountEnabled;
45
+ const tokenResolution = resolveZaloToken(
46
+ params.cfg.channels?.zalo as ZaloConfig | undefined,
47
+ accountId,
48
+ { allowUnresolvedSecretRef: params.allowUnresolvedSecretRef },
49
+ );
50
+
51
+ return {
52
+ accountId,
53
+ name: normalizeOptionalString(merged.name),
54
+ enabled,
55
+ token: tokenResolution.token,
56
+ tokenSource: tokenResolution.source,
57
+ config: merged,
58
+ };
59
+ }
60
+
61
+ export function listEnabledZaloAccounts(cfg: KlawConfig): ResolvedZaloAccount[] {
62
+ return listZaloAccountIds(cfg)
63
+ .map((accountId) => resolveZaloAccount({ cfg, accountId }))
64
+ .filter((account) => account.enabled);
65
+ }
@@ -0,0 +1,5 @@
1
+ import { sendMessageZalo as sendMessageZaloImpl } from "./send.js";
2
+
3
+ export const zaloActionsRuntime = {
4
+ sendMessageZalo: sendMessageZaloImpl,
5
+ };
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { zaloMessageActions } from "./actions.js";
3
+ import type { KlawConfig } from "./runtime-api.js";
4
+
5
+ describe("zaloMessageActions.describeMessageTool", () => {
6
+ it("honors the selected Zalo account during discovery", () => {
7
+ const cfg: KlawConfig = {
8
+ channels: {
9
+ zalo: {
10
+ enabled: true,
11
+ botToken: "root-token",
12
+ accounts: {
13
+ default: {
14
+ enabled: false,
15
+ botToken: "default-token",
16
+ },
17
+ work: {
18
+ enabled: true,
19
+ botToken: "work-token",
20
+ },
21
+ },
22
+ },
23
+ },
24
+ };
25
+
26
+ expect(zaloMessageActions.describeMessageTool?.({ cfg, accountId: "default" })).toBeNull();
27
+ expect(zaloMessageActions.describeMessageTool?.({ cfg, accountId: "work" })).toEqual({
28
+ actions: ["send"],
29
+ capabilities: [],
30
+ });
31
+ });
32
+ });
package/src/actions.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { jsonResult, readStringParam } from "klaw/plugin-sdk/channel-actions";
2
+ import type {
3
+ ChannelMessageActionAdapter,
4
+ ChannelMessageActionName,
5
+ } from "klaw/plugin-sdk/channel-contract";
6
+ import type { KlawConfig } from "klaw/plugin-sdk/config-contracts";
7
+ import { createLazyRuntimeNamedExport } from "klaw/plugin-sdk/lazy-runtime";
8
+ import { extractToolSend } from "klaw/plugin-sdk/tool-send";
9
+ import { listEnabledZaloAccounts, resolveZaloAccount } from "./accounts.js";
10
+
11
+ const loadZaloActionsRuntime = createLazyRuntimeNamedExport(
12
+ () => import("./actions.runtime.js"),
13
+ "zaloActionsRuntime",
14
+ );
15
+
16
+ const providerId = "zalo";
17
+
18
+ function listEnabledAccounts(cfg: KlawConfig, accountId?: string | null) {
19
+ return (
20
+ accountId ? [resolveZaloAccount({ cfg, accountId })] : listEnabledZaloAccounts(cfg)
21
+ ).filter((account) => account.enabled && account.tokenSource !== "none");
22
+ }
23
+
24
+ export const zaloMessageActions: ChannelMessageActionAdapter = {
25
+ describeMessageTool: ({ cfg, accountId }) => {
26
+ const accounts = listEnabledAccounts(cfg, accountId);
27
+ if (accounts.length === 0) {
28
+ return null;
29
+ }
30
+ const actions = new Set<ChannelMessageActionName>(["send"]);
31
+ return { actions: Array.from(actions), capabilities: [] };
32
+ },
33
+ extractToolSend: ({ args }) => extractToolSend(args, "sendMessage"),
34
+ handleAction: async ({ action, params, cfg, accountId }) => {
35
+ if (action === "send") {
36
+ const to = readStringParam(params, "to", { required: true });
37
+ const content = readStringParam(params, "message", {
38
+ required: true,
39
+ allowEmpty: true,
40
+ });
41
+ const mediaUrl = readStringParam(params, "media", { trim: false });
42
+
43
+ const { sendMessageZalo } = await loadZaloActionsRuntime();
44
+ const result = await sendMessageZalo(to ?? "", content ?? "", {
45
+ accountId: accountId ?? undefined,
46
+ mediaUrl: mediaUrl ?? undefined,
47
+ cfg: cfg,
48
+ });
49
+
50
+ if (!result.ok) {
51
+ return jsonResult({
52
+ ok: false,
53
+ error: result.error ?? "Failed to send Zalo message",
54
+ });
55
+ }
56
+
57
+ return jsonResult({ ok: true, to, messageId: result.messageId });
58
+ }
59
+
60
+ throw new Error(`Action ${action} is not supported for provider ${providerId}.`);
61
+ },
62
+ };
@@ -0,0 +1,166 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const resolvePinnedHostnameWithPolicyMock = vi.fn();
4
+
5
+ vi.mock("klaw/plugin-sdk/ssrf-runtime", () => ({
6
+ resolvePinnedHostnameWithPolicy: (...args: unknown[]) =>
7
+ resolvePinnedHostnameWithPolicyMock(...args),
8
+ }));
9
+
10
+ import { deleteWebhook, getWebhookInfo, sendChatAction, sendPhoto, type ZaloFetch } from "./api.js";
11
+
12
+ function createOkFetcher() {
13
+ return vi.fn<ZaloFetch>(async () => new Response(JSON.stringify({ ok: true, result: {} })));
14
+ }
15
+
16
+ function requireFirstFetchCall(fetcher: ReturnType<typeof createOkFetcher>, label: string) {
17
+ const [call] = fetcher.mock.calls;
18
+ if (!call) {
19
+ throw new Error(`expected ${label}`);
20
+ }
21
+ return call;
22
+ }
23
+
24
+ async function expectPostJsonRequest(run: (token: string, fetcher: ZaloFetch) => Promise<unknown>) {
25
+ const fetcher = createOkFetcher();
26
+ await run("test-token", fetcher);
27
+ expect(fetcher).toHaveBeenCalledTimes(1);
28
+ const [, init] = requireFirstFetchCall(fetcher, "Zalo request");
29
+ if (!init) {
30
+ throw new Error("expected Zalo request init");
31
+ }
32
+ expect(init.method).toBe("POST");
33
+ expect(init.headers).toEqual({ "Content-Type": "application/json" });
34
+ }
35
+
36
+ describe("Zalo API request methods", () => {
37
+ beforeEach(() => {
38
+ resolvePinnedHostnameWithPolicyMock.mockReset();
39
+ resolvePinnedHostnameWithPolicyMock.mockResolvedValue({
40
+ hostname: "example.com",
41
+ addresses: ["93.184.216.34"],
42
+ lookup: vi.fn(),
43
+ });
44
+ });
45
+
46
+ it("uses POST for getWebhookInfo", async () => {
47
+ await expectPostJsonRequest(getWebhookInfo);
48
+ });
49
+
50
+ it("keeps POST for deleteWebhook", async () => {
51
+ await expectPostJsonRequest(deleteWebhook);
52
+ });
53
+
54
+ it("aborts sendChatAction when the typing timeout elapses", async () => {
55
+ vi.useFakeTimers();
56
+ try {
57
+ const fetcher = vi.fn<ZaloFetch>(
58
+ (_, init) =>
59
+ new Promise<Response>((_, reject) => {
60
+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), {
61
+ once: true,
62
+ });
63
+ }),
64
+ );
65
+
66
+ const promise = sendChatAction(
67
+ "test-token",
68
+ {
69
+ chat_id: "chat-123",
70
+ action: "typing",
71
+ },
72
+ fetcher,
73
+ 25,
74
+ );
75
+ const rejected = expect(promise).rejects.toThrow("aborted");
76
+
77
+ await vi.advanceTimersByTimeAsync(25);
78
+
79
+ await rejected;
80
+ const [, init] = requireFirstFetchCall(fetcher, "Zalo chat action request");
81
+ if (!init) {
82
+ throw new Error("expected Zalo chat action request init");
83
+ }
84
+ if (!init.signal) {
85
+ throw new Error("expected Zalo chat action abort signal");
86
+ }
87
+ expect(init.signal.aborted).toBe(true);
88
+ } finally {
89
+ vi.useRealTimers();
90
+ }
91
+ });
92
+
93
+ it("validates outbound photo URLs against the SSRF guard before posting", async () => {
94
+ const fetcher = createOkFetcher();
95
+
96
+ await sendPhoto(
97
+ "test-token",
98
+ {
99
+ chat_id: "chat-123",
100
+ photo: "https://example.com/image.png",
101
+ },
102
+ fetcher,
103
+ );
104
+
105
+ expect(resolvePinnedHostnameWithPolicyMock).toHaveBeenCalledWith("example.com", {
106
+ policy: {},
107
+ });
108
+ expect(fetcher).toHaveBeenCalledTimes(1);
109
+ });
110
+
111
+ it("blocks private-network photo URLs before they reach the Zalo API", async () => {
112
+ const fetcher = createOkFetcher();
113
+ resolvePinnedHostnameWithPolicyMock.mockRejectedValueOnce(
114
+ new Error("Blocked hostname or private/internal/special-use IP address"),
115
+ );
116
+
117
+ await expect(
118
+ sendPhoto(
119
+ "test-token",
120
+ {
121
+ chat_id: "chat-123",
122
+ photo: "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
123
+ },
124
+ fetcher,
125
+ ),
126
+ ).rejects.toThrow("Blocked hostname or private/internal/special-use IP address");
127
+
128
+ expect(fetcher).not.toHaveBeenCalled();
129
+ });
130
+
131
+ it("rejects non-http photo URLs", async () => {
132
+ const fetcher = createOkFetcher();
133
+
134
+ await expect(
135
+ sendPhoto(
136
+ "test-token",
137
+ {
138
+ chat_id: "chat-123",
139
+ photo: "file:///etc/passwd",
140
+ },
141
+ fetcher,
142
+ ),
143
+ ).rejects.toThrow("Zalo photo URL must use HTTP or HTTPS");
144
+
145
+ expect(resolvePinnedHostnameWithPolicyMock).not.toHaveBeenCalled();
146
+ expect(fetcher).not.toHaveBeenCalled();
147
+ });
148
+
149
+ it("rejects non-URL strings", async () => {
150
+ const fetcher = createOkFetcher();
151
+
152
+ await expect(
153
+ sendPhoto(
154
+ "test-token",
155
+ {
156
+ chat_id: "chat-123",
157
+ photo: "not a url",
158
+ },
159
+ fetcher,
160
+ ),
161
+ ).rejects.toThrow("Zalo photo URL must be an absolute HTTP or HTTPS URL");
162
+
163
+ expect(resolvePinnedHostnameWithPolicyMock).not.toHaveBeenCalled();
164
+ expect(fetcher).not.toHaveBeenCalled();
165
+ });
166
+ });
package/src/api.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Zalo Bot API client
3
+ * @see https://bot.zaloplatforms.com/docs
4
+ */
5
+
6
+ import { resolvePinnedHostnameWithPolicy, type SsrFPolicy } from "klaw/plugin-sdk/ssrf-runtime";
7
+
8
+ const ZALO_API_BASE = "https://bot-api.zaloplatforms.com";
9
+ const ZALO_MEDIA_SSRF_POLICY: SsrFPolicy = {};
10
+
11
+ export type ZaloFetch = (input: string, init?: RequestInit) => Promise<Response>;
12
+
13
+ export type ZaloApiResponse<T = unknown> = {
14
+ ok: boolean;
15
+ result?: T;
16
+ error_code?: number;
17
+ description?: string;
18
+ };
19
+
20
+ export type ZaloBotInfo = {
21
+ id: string;
22
+ name: string;
23
+ avatar?: string;
24
+ };
25
+
26
+ export type ZaloMessage = {
27
+ message_id: string;
28
+ from: {
29
+ id: string;
30
+ name?: string;
31
+ display_name?: string;
32
+ avatar?: string;
33
+ is_bot?: boolean;
34
+ };
35
+ chat: {
36
+ id: string;
37
+ chat_type: "PRIVATE" | "GROUP";
38
+ };
39
+ date: number;
40
+ text?: string;
41
+ photo_url?: string;
42
+ caption?: string;
43
+ sticker?: string;
44
+ message_type?: string;
45
+ };
46
+
47
+ export type ZaloUpdate = {
48
+ event_name:
49
+ | "message.text.received"
50
+ | "message.image.received"
51
+ | "message.sticker.received"
52
+ | "message.unsupported.received";
53
+ message?: ZaloMessage;
54
+ };
55
+
56
+ export type ZaloSendMessageParams = {
57
+ chat_id: string;
58
+ text: string;
59
+ };
60
+
61
+ export type ZaloSendPhotoParams = {
62
+ chat_id: string;
63
+ photo: string;
64
+ caption?: string;
65
+ };
66
+
67
+ export type ZaloSendChatActionParams = {
68
+ chat_id: string;
69
+ action: "typing" | "upload_photo";
70
+ };
71
+
72
+ export type ZaloSetWebhookParams = {
73
+ url: string;
74
+ secret_token: string;
75
+ };
76
+
77
+ export type ZaloWebhookInfo = {
78
+ url?: string;
79
+ updated_at?: number;
80
+ has_custom_certificate?: boolean;
81
+ };
82
+
83
+ export type ZaloGetUpdatesParams = {
84
+ /** Timeout in seconds (passed as string to API) */
85
+ timeout?: number;
86
+ };
87
+
88
+ export class ZaloApiError extends Error {
89
+ constructor(
90
+ message: string,
91
+ public readonly errorCode?: number,
92
+ public readonly description?: string,
93
+ ) {
94
+ super(message);
95
+ this.name = "ZaloApiError";
96
+ }
97
+
98
+ /** True if this is a long-polling timeout (no updates available) */
99
+ get isPollingTimeout(): boolean {
100
+ return this.errorCode === 408;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Call the Zalo Bot API
106
+ */
107
+ export async function callZaloApi<T = unknown>(
108
+ method: string,
109
+ token: string,
110
+ body?: Record<string, unknown>,
111
+ options?: { timeoutMs?: number; fetch?: ZaloFetch },
112
+ ): Promise<ZaloApiResponse<T>> {
113
+ const url = `${ZALO_API_BASE}/bot${token}/${method}`;
114
+ const controller = new AbortController();
115
+ const timeoutId = options?.timeoutMs
116
+ ? setTimeout(() => controller.abort(), options.timeoutMs)
117
+ : undefined;
118
+ const fetcher = options?.fetch ?? fetch;
119
+
120
+ try {
121
+ const response = await fetcher(url, {
122
+ method: "POST",
123
+ headers: {
124
+ "Content-Type": "application/json",
125
+ },
126
+ body: body ? JSON.stringify(body) : undefined,
127
+ signal: controller.signal,
128
+ });
129
+
130
+ const data = (await response.json()) as ZaloApiResponse<T>;
131
+
132
+ if (!data.ok) {
133
+ throw new ZaloApiError(
134
+ data.description ?? `Zalo API error: ${method}`,
135
+ data.error_code,
136
+ data.description,
137
+ );
138
+ }
139
+
140
+ return data;
141
+ } finally {
142
+ if (timeoutId) {
143
+ clearTimeout(timeoutId);
144
+ }
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Validate bot token and get bot info
150
+ */
151
+ export async function getMe(
152
+ token: string,
153
+ timeoutMs?: number,
154
+ fetcher?: ZaloFetch,
155
+ ): Promise<ZaloApiResponse<ZaloBotInfo>> {
156
+ return callZaloApi<ZaloBotInfo>("getMe", token, undefined, { timeoutMs, fetch: fetcher });
157
+ }
158
+
159
+ /**
160
+ * Send a text message
161
+ */
162
+ export async function sendMessage(
163
+ token: string,
164
+ params: ZaloSendMessageParams,
165
+ fetcher?: ZaloFetch,
166
+ ): Promise<ZaloApiResponse<ZaloMessage>> {
167
+ return callZaloApi<ZaloMessage>("sendMessage", token, params, { fetch: fetcher });
168
+ }
169
+
170
+ /**
171
+ * Send a photo message
172
+ */
173
+ export async function sendPhoto(
174
+ token: string,
175
+ params: ZaloSendPhotoParams,
176
+ fetcher?: ZaloFetch,
177
+ ): Promise<ZaloApiResponse<ZaloMessage>> {
178
+ const photoUrl = params.photo.trim();
179
+ let parsedPhotoUrl: URL;
180
+ try {
181
+ parsedPhotoUrl = new URL(photoUrl);
182
+ } catch {
183
+ throw new Error("Zalo photo URL must be an absolute HTTP or HTTPS URL");
184
+ }
185
+
186
+ if (parsedPhotoUrl.protocol !== "http:" && parsedPhotoUrl.protocol !== "https:") {
187
+ throw new Error("Zalo photo URL must use HTTP or HTTPS");
188
+ }
189
+
190
+ await resolvePinnedHostnameWithPolicy(parsedPhotoUrl.hostname, {
191
+ policy: ZALO_MEDIA_SSRF_POLICY,
192
+ });
193
+
194
+ return callZaloApi<ZaloMessage>(
195
+ "sendPhoto",
196
+ token,
197
+ { ...params, photo: parsedPhotoUrl.href },
198
+ { fetch: fetcher },
199
+ );
200
+ }
201
+
202
+ /**
203
+ * Send a temporary chat action such as typing.
204
+ */
205
+ export async function sendChatAction(
206
+ token: string,
207
+ params: ZaloSendChatActionParams,
208
+ fetcher?: ZaloFetch,
209
+ timeoutMs?: number,
210
+ ): Promise<ZaloApiResponse<boolean>> {
211
+ return callZaloApi<boolean>("sendChatAction", token, params, {
212
+ timeoutMs,
213
+ fetch: fetcher,
214
+ });
215
+ }
216
+
217
+ /**
218
+ * Get updates using long polling (dev/testing only)
219
+ * Note: Zalo returns a single update per call, not an array like Telegram
220
+ */
221
+ export async function getUpdates(
222
+ token: string,
223
+ params?: ZaloGetUpdatesParams,
224
+ fetcher?: ZaloFetch,
225
+ ): Promise<ZaloApiResponse<ZaloUpdate>> {
226
+ const pollTimeoutSec = params?.timeout ?? 30;
227
+ const timeoutMs = (pollTimeoutSec + 5) * 1000;
228
+ const body = { timeout: String(pollTimeoutSec) };
229
+ return callZaloApi<ZaloUpdate>("getUpdates", token, body, { timeoutMs, fetch: fetcher });
230
+ }
231
+
232
+ /**
233
+ * Set webhook URL for receiving updates
234
+ */
235
+ export async function setWebhook(
236
+ token: string,
237
+ params: ZaloSetWebhookParams,
238
+ fetcher?: ZaloFetch,
239
+ ): Promise<ZaloApiResponse<ZaloWebhookInfo>> {
240
+ return callZaloApi<ZaloWebhookInfo>("setWebhook", token, params, { fetch: fetcher });
241
+ }
242
+
243
+ /**
244
+ * Delete webhook configuration
245
+ */
246
+ export async function deleteWebhook(
247
+ token: string,
248
+ fetcher?: ZaloFetch,
249
+ timeoutMs?: number,
250
+ ): Promise<ZaloApiResponse<ZaloWebhookInfo>> {
251
+ return callZaloApi<ZaloWebhookInfo>("deleteWebhook", token, undefined, {
252
+ timeoutMs,
253
+ fetch: fetcher,
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Get current webhook info
259
+ */
260
+ export async function getWebhookInfo(
261
+ token: string,
262
+ fetcher?: ZaloFetch,
263
+ ): Promise<ZaloApiResponse<ZaloWebhookInfo>> {
264
+ return callZaloApi<ZaloWebhookInfo>("getWebhookInfo", token, undefined, { fetch: fetcher });
265
+ }