@kodelyth/feishu 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 (238) hide show
  1. package/api.ts +32 -0
  2. package/channel-entry.ts +20 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +16 -0
  5. package/dist/accounts-D0ow-lRb.js +429 -0
  6. package/dist/api.js +2308 -0
  7. package/dist/app-registration-DBSnysKJ.js +184 -0
  8. package/dist/audio-preflight.runtime-Dpjbn-7r.js +7 -0
  9. package/dist/channel-13WQvQ0u.js +2115 -0
  10. package/dist/channel-entry.js +22 -0
  11. package/dist/channel-plugin-api.js +2 -0
  12. package/dist/channel.runtime-JMJonrJ4.js +729 -0
  13. package/dist/client-D1pzbBGo.js +157 -0
  14. package/dist/contract-api.js +9 -0
  15. package/dist/conversation-id-_58ecqlx.js +139 -0
  16. package/dist/drive-CgHOluXx.js +883 -0
  17. package/dist/index.js +68 -0
  18. package/dist/monitor-oWptK0zL.js +60 -0
  19. package/dist/monitor.account-DHaWlslg.js +5207 -0
  20. package/dist/monitor.state-C211a4tX.js +100 -0
  21. package/dist/probe-CF4duEpK.js +149 -0
  22. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  23. package/dist/runtime-DSh5rL_d.js +8 -0
  24. package/dist/runtime-api.js +14 -0
  25. package/dist/secret-contract-NSee-WzN.js +119 -0
  26. package/dist/secret-contract-api.js +2 -0
  27. package/dist/security-audit-DWVC0vSK.js +11 -0
  28. package/dist/security-audit-shared-Dpcwxeft.js +38 -0
  29. package/dist/security-contract-api.js +2 -0
  30. package/dist/send-DfZuV4Fi.js +1212 -0
  31. package/dist/session-conversation-Duaukbnl.js +27 -0
  32. package/dist/session-key-api.js +2 -0
  33. package/dist/setup-api.js +2 -0
  34. package/dist/setup-entry.js +15 -0
  35. package/dist/subagent-hooks-Dtegs0kh.js +235 -0
  36. package/dist/subagent-hooks-api.js +23 -0
  37. package/dist/targets-DFskxX4p.js +48 -0
  38. package/dist/thread-bindings-DI7lVSOE.js +222 -0
  39. package/index.ts +82 -0
  40. package/klaw.plugin.json +47 -1712
  41. package/package.json +4 -4
  42. package/runtime-api.ts +52 -0
  43. package/secret-contract-api.ts +5 -0
  44. package/security-contract-api.ts +1 -0
  45. package/session-key-api.ts +1 -0
  46. package/setup-api.ts +3 -0
  47. package/setup-entry.test.ts +19 -0
  48. package/setup-entry.ts +13 -0
  49. package/src/accounts.test.ts +480 -0
  50. package/src/accounts.ts +333 -0
  51. package/src/agent-config.ts +21 -0
  52. package/src/app-registration.ts +331 -0
  53. package/src/approval-auth.test.ts +24 -0
  54. package/src/approval-auth.ts +25 -0
  55. package/src/async.test.ts +35 -0
  56. package/src/async.ts +104 -0
  57. package/src/audio-preflight.runtime.ts +9 -0
  58. package/src/bitable.test.ts +136 -0
  59. package/src/bitable.ts +762 -0
  60. package/src/bot-content.ts +485 -0
  61. package/src/bot-group-name.test.ts +116 -0
  62. package/src/bot-runtime-api.ts +12 -0
  63. package/src/bot-sender-name.ts +125 -0
  64. package/src/bot.broadcast.test.ts +523 -0
  65. package/src/bot.card-action.test.ts +552 -0
  66. package/src/bot.checkBotMentioned.test.ts +265 -0
  67. package/src/bot.helpers.test.ts +135 -0
  68. package/src/bot.stripBotMention.test.ts +126 -0
  69. package/src/bot.test.ts +3671 -0
  70. package/src/bot.ts +1703 -0
  71. package/src/card-action.ts +447 -0
  72. package/src/card-interaction.test.ts +131 -0
  73. package/src/card-interaction.ts +159 -0
  74. package/src/card-test-helpers.ts +54 -0
  75. package/src/card-ux-approval.ts +65 -0
  76. package/src/card-ux-launcher.test.ts +106 -0
  77. package/src/card-ux-launcher.ts +121 -0
  78. package/src/card-ux-shared.ts +33 -0
  79. package/src/channel-runtime-api.ts +16 -0
  80. package/src/channel.runtime.ts +47 -0
  81. package/src/channel.test.ts +1151 -0
  82. package/src/channel.ts +1423 -0
  83. package/src/chat-schema.ts +25 -0
  84. package/src/chat.test.ts +240 -0
  85. package/src/chat.ts +188 -0
  86. package/src/client-timeout.ts +42 -0
  87. package/src/client.test.ts +447 -0
  88. package/src/client.ts +262 -0
  89. package/src/comment-dispatcher-runtime-api.ts +6 -0
  90. package/src/comment-dispatcher.test.ts +185 -0
  91. package/src/comment-dispatcher.ts +107 -0
  92. package/src/comment-handler-runtime-api.ts +3 -0
  93. package/src/comment-handler.test.ts +592 -0
  94. package/src/comment-handler.ts +303 -0
  95. package/src/comment-reaction.test.ts +138 -0
  96. package/src/comment-reaction.ts +259 -0
  97. package/src/comment-shared.test.ts +183 -0
  98. package/src/comment-shared.ts +406 -0
  99. package/src/comment-target.ts +44 -0
  100. package/src/config-schema.test.ts +326 -0
  101. package/src/config-schema.ts +335 -0
  102. package/src/conversation-id.test.ts +18 -0
  103. package/src/conversation-id.ts +199 -0
  104. package/src/dedup-runtime-api.ts +1 -0
  105. package/src/dedup.ts +141 -0
  106. package/src/dedupe-key.ts +72 -0
  107. package/src/directory.static.ts +61 -0
  108. package/src/directory.test.ts +141 -0
  109. package/src/directory.ts +124 -0
  110. package/src/doc-schema.ts +182 -0
  111. package/src/docx-batch-insert.test.ts +116 -0
  112. package/src/docx-batch-insert.ts +223 -0
  113. package/src/docx-color-text.ts +154 -0
  114. package/src/docx-table-ops.test.ts +53 -0
  115. package/src/docx-table-ops.ts +316 -0
  116. package/src/docx-types.ts +38 -0
  117. package/src/docx.account-selection.test.ts +95 -0
  118. package/src/docx.test.ts +701 -0
  119. package/src/docx.ts +1596 -0
  120. package/src/drive-schema.ts +92 -0
  121. package/src/drive.test.ts +1237 -0
  122. package/src/drive.ts +829 -0
  123. package/src/dynamic-agent.test.ts +155 -0
  124. package/src/dynamic-agent.ts +143 -0
  125. package/src/event-types.ts +45 -0
  126. package/src/external-keys.test.ts +20 -0
  127. package/src/external-keys.ts +19 -0
  128. package/src/lifecycle.test-support.ts +220 -0
  129. package/src/media.test.ts +955 -0
  130. package/src/media.ts +1105 -0
  131. package/src/mention-target.types.ts +5 -0
  132. package/src/mention.ts +114 -0
  133. package/src/message-action-contract.ts +13 -0
  134. package/src/monitor-state-runtime-api.ts +7 -0
  135. package/src/monitor-transport-runtime-api.ts +10 -0
  136. package/src/monitor.account.ts +492 -0
  137. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  138. package/src/monitor.bot-identity.ts +86 -0
  139. package/src/monitor.bot-menu-handler.ts +165 -0
  140. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  141. package/src/monitor.bot-menu.test.ts +188 -0
  142. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  143. package/src/monitor.card-action.lifecycle.test-support.ts +421 -0
  144. package/src/monitor.cleanup.test.ts +383 -0
  145. package/src/monitor.comment-notice-handler.ts +105 -0
  146. package/src/monitor.comment.test.ts +967 -0
  147. package/src/monitor.comment.ts +1386 -0
  148. package/src/monitor.lifecycle.test.ts +4 -0
  149. package/src/monitor.message-handler.ts +350 -0
  150. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  151. package/src/monitor.reaction.test.ts +739 -0
  152. package/src/monitor.startup.test.ts +213 -0
  153. package/src/monitor.startup.ts +74 -0
  154. package/src/monitor.state.defaults.test.ts +46 -0
  155. package/src/monitor.state.ts +170 -0
  156. package/src/monitor.synthetic-error.ts +18 -0
  157. package/src/monitor.test-mocks.ts +46 -0
  158. package/src/monitor.transport.ts +451 -0
  159. package/src/monitor.ts +100 -0
  160. package/src/monitor.webhook-e2e.test.ts +279 -0
  161. package/src/monitor.webhook-security.test.ts +389 -0
  162. package/src/monitor.webhook.test-helpers.ts +116 -0
  163. package/src/outbound-runtime-api.ts +1 -0
  164. package/src/outbound.test.ts +1118 -0
  165. package/src/outbound.ts +785 -0
  166. package/src/perm-schema.ts +52 -0
  167. package/src/perm.ts +170 -0
  168. package/src/pins.ts +108 -0
  169. package/src/policy.test.ts +223 -0
  170. package/src/policy.ts +318 -0
  171. package/src/post.test.ts +105 -0
  172. package/src/post.ts +275 -0
  173. package/src/probe.test.ts +283 -0
  174. package/src/probe.ts +166 -0
  175. package/src/processing-claims.ts +59 -0
  176. package/src/qr-terminal.ts +1 -0
  177. package/src/reactions.ts +123 -0
  178. package/src/reasoning-preview.test.ts +113 -0
  179. package/src/reasoning-preview.ts +28 -0
  180. package/src/reply-dispatcher-runtime-api.ts +7 -0
  181. package/src/reply-dispatcher.test.ts +1513 -0
  182. package/src/reply-dispatcher.ts +748 -0
  183. package/src/runtime.ts +9 -0
  184. package/src/secret-contract.ts +145 -0
  185. package/src/secret-input.ts +1 -0
  186. package/src/security-audit-shared.ts +69 -0
  187. package/src/security-audit.test.ts +59 -0
  188. package/src/security-audit.ts +1 -0
  189. package/src/send-result.ts +80 -0
  190. package/src/send-target.test.ts +86 -0
  191. package/src/send-target.ts +35 -0
  192. package/src/send.reply-fallback.test.ts +417 -0
  193. package/src/send.test.ts +621 -0
  194. package/src/send.ts +861 -0
  195. package/src/sequential-key.test.ts +72 -0
  196. package/src/sequential-key.ts +25 -0
  197. package/src/sequential-queue.test.ts +165 -0
  198. package/src/sequential-queue.ts +86 -0
  199. package/src/session-conversation.ts +42 -0
  200. package/src/session-route.ts +48 -0
  201. package/src/setup-core.ts +51 -0
  202. package/src/setup-surface.test.ts +484 -0
  203. package/src/setup-surface.ts +618 -0
  204. package/src/streaming-card.test.ts +397 -0
  205. package/src/streaming-card.ts +571 -0
  206. package/src/subagent-hooks.test.ts +627 -0
  207. package/src/subagent-hooks.ts +413 -0
  208. package/src/targets.ts +97 -0
  209. package/src/test-support/lifecycle-test-support.ts +454 -0
  210. package/src/thread-bindings.test.ts +180 -0
  211. package/src/thread-bindings.ts +331 -0
  212. package/src/tool-account-routing.test.ts +250 -0
  213. package/src/tool-account.test.ts +44 -0
  214. package/src/tool-account.ts +93 -0
  215. package/src/tool-factory-test-harness.ts +79 -0
  216. package/src/tool-result.test.ts +32 -0
  217. package/src/tool-result.ts +16 -0
  218. package/src/tools-config.test.ts +21 -0
  219. package/src/tools-config.ts +22 -0
  220. package/src/types.ts +106 -0
  221. package/src/typing.test.ts +144 -0
  222. package/src/typing.ts +214 -0
  223. package/src/wiki-schema.ts +69 -0
  224. package/src/wiki.ts +270 -0
  225. package/subagent-hooks-api.ts +31 -0
  226. package/tsconfig.json +16 -0
  227. package/api.js +0 -7
  228. package/channel-entry.js +0 -7
  229. package/channel-plugin-api.js +0 -7
  230. package/contract-api.js +0 -7
  231. package/index.js +0 -7
  232. package/runtime-api.js +0 -7
  233. package/secret-contract-api.js +0 -7
  234. package/security-contract-api.js +0 -7
  235. package/session-key-api.js +0 -7
  236. package/setup-api.js +0 -7
  237. package/setup-entry.js +0 -7
  238. package/subagent-hooks-api.js +0 -7
@@ -0,0 +1,447 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { FeishuConfigSchema } from "./config-schema.js";
3
+ import type { ResolvedFeishuAccount } from "./types.js";
4
+
5
+ type CreateFeishuClient = typeof import("./client.js").createFeishuClient;
6
+ type CreateFeishuWSClient = typeof import("./client.js").createFeishuWSClient;
7
+ type ClearClientCache = typeof import("./client.js").clearClientCache;
8
+ type SetFeishuClientRuntimeForTest = typeof import("./client.js").setFeishuClientRuntimeForTest;
9
+
10
+ const clientCtorMock = vi.hoisted(() =>
11
+ vi.fn(function clientCtor() {
12
+ return { connected: true };
13
+ }),
14
+ );
15
+ const wsClientCtorMock = vi.hoisted(() =>
16
+ vi.fn(function wsClientCtor() {
17
+ return { connected: true };
18
+ }),
19
+ );
20
+ const proxyAgentCtorMock = vi.hoisted(() =>
21
+ vi.fn(function createAmbientNodeProxyAgent() {
22
+ return { proxied: true };
23
+ }),
24
+ );
25
+ const mockBaseHttpInstance = vi.hoisted(() => ({
26
+ request: vi.fn().mockResolvedValue({}),
27
+ get: vi.fn().mockResolvedValue({}),
28
+ post: vi.fn().mockResolvedValue({}),
29
+ put: vi.fn().mockResolvedValue({}),
30
+ patch: vi.fn().mockResolvedValue({}),
31
+ delete: vi.fn().mockResolvedValue({}),
32
+ head: vi.fn().mockResolvedValue({}),
33
+ options: vi.fn().mockResolvedValue({}),
34
+ }));
35
+ const proxyEnvKeys = ["https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY"] as const;
36
+ type ProxyEnvKey = (typeof proxyEnvKeys)[number];
37
+ const registerFeishuDocToolsMock = vi.hoisted(() => vi.fn());
38
+ const registerFeishuChatToolsMock = vi.hoisted(() => vi.fn());
39
+ const registerFeishuWikiToolsMock = vi.hoisted(() => vi.fn());
40
+ const registerFeishuDriveToolsMock = vi.hoisted(() => vi.fn());
41
+ const registerFeishuPermToolsMock = vi.hoisted(() => vi.fn());
42
+ const registerFeishuBitableToolsMock = vi.hoisted(() => vi.fn());
43
+ const feishuPluginMock = vi.hoisted(() => ({ id: "feishu-test-plugin" }));
44
+ const setFeishuRuntimeMock = vi.hoisted(() => vi.fn());
45
+ const registerFeishuSubagentHooksMock = vi.hoisted(() => vi.fn());
46
+
47
+ let createFeishuClient: CreateFeishuClient;
48
+ let createFeishuWSClient: CreateFeishuWSClient;
49
+ let clearClientCache: ClearClientCache;
50
+ let setFeishuClientRuntimeForTest: SetFeishuClientRuntimeForTest;
51
+ let FEISHU_HTTP_TIMEOUT_MS: number;
52
+ let FEISHU_HTTP_TIMEOUT_MAX_MS: number;
53
+ let FEISHU_HTTP_TIMEOUT_ENV_VAR: string;
54
+
55
+ let priorProxyEnv: Partial<Record<ProxyEnvKey, string | undefined>> = {};
56
+ let priorFeishuTimeoutEnv: string | undefined;
57
+
58
+ vi.mock("./channel.js", () => ({
59
+ feishuPlugin: feishuPluginMock,
60
+ }));
61
+
62
+ vi.mock("./docx.js", () => ({
63
+ registerFeishuDocTools: registerFeishuDocToolsMock,
64
+ }));
65
+
66
+ vi.mock("./chat.js", () => ({
67
+ registerFeishuChatTools: registerFeishuChatToolsMock,
68
+ }));
69
+
70
+ vi.mock("./wiki.js", () => ({
71
+ registerFeishuWikiTools: registerFeishuWikiToolsMock,
72
+ }));
73
+
74
+ vi.mock("./drive.js", () => ({
75
+ registerFeishuDriveTools: registerFeishuDriveToolsMock,
76
+ }));
77
+
78
+ vi.mock("./perm.js", () => ({
79
+ registerFeishuPermTools: registerFeishuPermToolsMock,
80
+ }));
81
+
82
+ vi.mock("./bitable.js", () => ({
83
+ registerFeishuBitableTools: registerFeishuBitableToolsMock,
84
+ }));
85
+
86
+ vi.mock("./runtime.js", () => ({
87
+ setFeishuRuntime: setFeishuRuntimeMock,
88
+ }));
89
+
90
+ vi.mock("./subagent-hooks.js", () => ({
91
+ registerFeishuSubagentHooks: registerFeishuSubagentHooksMock,
92
+ }));
93
+
94
+ const baseAccount: ResolvedFeishuAccount = {
95
+ accountId: "main",
96
+ selectionSource: "explicit",
97
+ enabled: true,
98
+ configured: true,
99
+ appId: "app_123",
100
+ appSecret: "secret_123", // pragma: allowlist secret
101
+ domain: "feishu",
102
+ config: FeishuConfigSchema.parse({}),
103
+ };
104
+
105
+ function isRecord(value: unknown): value is Record<string, unknown> {
106
+ return typeof value === "object" && value !== null;
107
+ }
108
+
109
+ type HttpInstanceLike = {
110
+ get: (url: string, options?: Record<string, unknown>) => Promise<unknown>;
111
+ post: (url: string, body?: unknown, options?: Record<string, unknown>) => Promise<unknown>;
112
+ };
113
+
114
+ function requireHttpInstance(value: unknown): HttpInstanceLike {
115
+ if (isRecord(value) && typeof value.get === "function" && typeof value.post === "function") {
116
+ return {
117
+ get: value.get as HttpInstanceLike["get"],
118
+ post: value.post as HttpInstanceLike["post"],
119
+ };
120
+ }
121
+ throw new Error("expected Feishu HTTP instance");
122
+ }
123
+
124
+ function readCallOptions(
125
+ mock: { mock: { calls: unknown[][] } },
126
+ index = -1,
127
+ ): Record<string, unknown> {
128
+ const call = index < 0 ? mock.mock.calls.at(index)?.[0] : mock.mock.calls[index]?.[0];
129
+ return isRecord(call) ? call : {};
130
+ }
131
+
132
+ function firstWsClientOptions(): {
133
+ agent?: unknown;
134
+ wsConfig?: unknown;
135
+ onError?: unknown;
136
+ onReady?: unknown;
137
+ onReconnected?: unknown;
138
+ onReconnecting?: unknown;
139
+ } {
140
+ const options = readCallOptions(wsClientCtorMock, 0);
141
+ return {
142
+ agent: options.agent,
143
+ wsConfig: options.wsConfig,
144
+ onError: options.onError,
145
+ onReady: options.onReady,
146
+ onReconnected: options.onReconnected,
147
+ onReconnecting: options.onReconnecting,
148
+ };
149
+ }
150
+
151
+ beforeAll(async () => {
152
+ vi.doMock("@larksuiteoapi/node-sdk", () => ({
153
+ AppType: { SelfBuild: "self" },
154
+ Domain: { Feishu: "https://open.feishu.cn", Lark: "https://open.larksuite.com" },
155
+ LoggerLevel: { info: "info" },
156
+ Client: clientCtorMock,
157
+ WSClient: wsClientCtorMock,
158
+ EventDispatcher: vi.fn(),
159
+ defaultHttpInstance: mockBaseHttpInstance,
160
+ }));
161
+ vi.doMock("@kodelyth/proxyline", () => ({
162
+ createAmbientNodeProxyAgent: proxyAgentCtorMock,
163
+ hasAmbientNodeProxyConfigured: vi.fn(() =>
164
+ Boolean(
165
+ process.env.HTTPS_PROXY ??
166
+ process.env.https_proxy ??
167
+ process.env.HTTP_PROXY ??
168
+ process.env.http_proxy,
169
+ ),
170
+ ),
171
+ }));
172
+
173
+ ({
174
+ createFeishuClient,
175
+ createFeishuWSClient,
176
+ clearClientCache,
177
+ setFeishuClientRuntimeForTest,
178
+ FEISHU_HTTP_TIMEOUT_MS,
179
+ FEISHU_HTTP_TIMEOUT_MAX_MS,
180
+ FEISHU_HTTP_TIMEOUT_ENV_VAR,
181
+ } = await import("./client.js"));
182
+ });
183
+
184
+ beforeEach(() => {
185
+ priorProxyEnv = {};
186
+ priorFeishuTimeoutEnv = process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
187
+ delete process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
188
+ for (const key of proxyEnvKeys) {
189
+ priorProxyEnv[key] = process.env[key];
190
+ delete process.env[key];
191
+ }
192
+ vi.clearAllMocks();
193
+ clearClientCache();
194
+ setFeishuClientRuntimeForTest({
195
+ sdk: {
196
+ AppType: { SelfBuild: "self" } as never,
197
+ Domain: {
198
+ Feishu: "https://open.feishu.cn",
199
+ Lark: "https://open.larksuite.com",
200
+ } as never,
201
+ LoggerLevel: { info: "info" } as never,
202
+ Client: clientCtorMock as never,
203
+ WSClient: wsClientCtorMock as never,
204
+ EventDispatcher: vi.fn() as never,
205
+ defaultHttpInstance: mockBaseHttpInstance as never,
206
+ },
207
+ });
208
+ });
209
+
210
+ afterEach(() => {
211
+ for (const key of proxyEnvKeys) {
212
+ const value = priorProxyEnv[key];
213
+ if (value === undefined) {
214
+ delete process.env[key];
215
+ } else {
216
+ process.env[key] = value;
217
+ }
218
+ }
219
+ if (priorFeishuTimeoutEnv === undefined) {
220
+ delete process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
221
+ } else {
222
+ process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = priorFeishuTimeoutEnv;
223
+ }
224
+ setFeishuClientRuntimeForTest();
225
+ });
226
+
227
+ afterAll(() => {
228
+ vi.doUnmock("./channel.js");
229
+ vi.doUnmock("./docx.js");
230
+ vi.doUnmock("./chat.js");
231
+ vi.doUnmock("./wiki.js");
232
+ vi.doUnmock("./drive.js");
233
+ vi.doUnmock("./perm.js");
234
+ vi.doUnmock("./bitable.js");
235
+ vi.doUnmock("./runtime.js");
236
+ vi.doUnmock("./subagent-hooks.js");
237
+ vi.doUnmock("@larksuiteoapi/node-sdk");
238
+ vi.doUnmock("@kodelyth/proxyline");
239
+ vi.resetModules();
240
+ });
241
+
242
+ describe("createFeishuClient HTTP timeout", () => {
243
+ const readLastClientHttpInstance = (): HttpInstanceLike =>
244
+ requireHttpInstance(readCallOptions(clientCtorMock).httpInstance);
245
+
246
+ const expectGetCallTimeout = async (timeout: number) => {
247
+ const httpInstance = readLastClientHttpInstance();
248
+ await httpInstance.get("https://example.com/api");
249
+ expect(mockBaseHttpInstance.get).toHaveBeenCalledWith("https://example.com/api", { timeout });
250
+ };
251
+
252
+ it("passes a custom httpInstance with default timeout to Lark.Client", () => {
253
+ createFeishuClient({ appId: "app_1", appSecret: "secret_1", accountId: "timeout-test" }); // pragma: allowlist secret
254
+
255
+ const httpInstance = readLastClientHttpInstance();
256
+ expect(typeof httpInstance.get).toBe("function");
257
+ expect(typeof httpInstance.post).toBe("function");
258
+ });
259
+
260
+ it("injects default timeout into HTTP request options", async () => {
261
+ createFeishuClient({ appId: "app_2", appSecret: "secret_2", accountId: "timeout-inject" }); // pragma: allowlist secret
262
+
263
+ const httpInstance = readLastClientHttpInstance();
264
+
265
+ await httpInstance.post(
266
+ "https://example.com/api",
267
+ { data: 1 },
268
+ { headers: { "X-Custom": "yes" } },
269
+ );
270
+
271
+ expect(mockBaseHttpInstance.post).toHaveBeenCalledWith(
272
+ "https://example.com/api",
273
+ { data: 1 },
274
+ { timeout: FEISHU_HTTP_TIMEOUT_MS, headers: { "X-Custom": "yes" } },
275
+ );
276
+ });
277
+
278
+ it("allows explicit timeout override per-request", async () => {
279
+ createFeishuClient({ appId: "app_3", appSecret: "secret_3", accountId: "timeout-override" }); // pragma: allowlist secret
280
+
281
+ const httpInstance = readLastClientHttpInstance();
282
+
283
+ await httpInstance.get("https://example.com/api", { timeout: 5_000 });
284
+
285
+ expect(mockBaseHttpInstance.get).toHaveBeenCalledWith("https://example.com/api", {
286
+ timeout: 5_000,
287
+ });
288
+ });
289
+
290
+ it("uses config-configured default timeout when provided", async () => {
291
+ createFeishuClient({
292
+ appId: "app_4",
293
+ appSecret: "secret_4", // pragma: allowlist secret
294
+ accountId: "timeout-config",
295
+ config: { httpTimeoutMs: 45_000 },
296
+ });
297
+
298
+ await expectGetCallTimeout(45_000);
299
+ });
300
+
301
+ it("falls back to default timeout when configured timeout is invalid", async () => {
302
+ createFeishuClient({
303
+ appId: "app_5",
304
+ appSecret: "secret_5", // pragma: allowlist secret
305
+ accountId: "timeout-config-invalid",
306
+ config: { httpTimeoutMs: -1 },
307
+ });
308
+
309
+ await expectGetCallTimeout(FEISHU_HTTP_TIMEOUT_MS);
310
+ });
311
+
312
+ it("uses env timeout override when provided and no direct timeout is set", async () => {
313
+ process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = "60000";
314
+
315
+ createFeishuClient({
316
+ appId: "app_8",
317
+ appSecret: "secret_8", // pragma: allowlist secret
318
+ accountId: "timeout-env-override",
319
+ config: { httpTimeoutMs: 45_000 },
320
+ });
321
+
322
+ await expectGetCallTimeout(60_000);
323
+ });
324
+
325
+ it("prefers direct timeout over env override", async () => {
326
+ process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = "60000";
327
+
328
+ createFeishuClient({
329
+ appId: "app_10",
330
+ appSecret: "secret_10", // pragma: allowlist secret
331
+ accountId: "timeout-direct-override",
332
+ httpTimeoutMs: 120_000,
333
+ config: { httpTimeoutMs: 45_000 },
334
+ });
335
+
336
+ await expectGetCallTimeout(120_000);
337
+ });
338
+
339
+ it("clamps env timeout override to max bound", async () => {
340
+ process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR] = String(FEISHU_HTTP_TIMEOUT_MAX_MS + 123_456);
341
+
342
+ createFeishuClient({
343
+ appId: "app_9",
344
+ appSecret: "secret_9", // pragma: allowlist secret
345
+ accountId: "timeout-env-clamp",
346
+ });
347
+
348
+ await expectGetCallTimeout(FEISHU_HTTP_TIMEOUT_MAX_MS);
349
+ });
350
+
351
+ it("recreates cached client when configured timeout changes", async () => {
352
+ createFeishuClient({
353
+ appId: "app_6",
354
+ appSecret: "secret_6", // pragma: allowlist secret
355
+ accountId: "timeout-cache-change",
356
+ config: { httpTimeoutMs: 30_000 },
357
+ });
358
+ createFeishuClient({
359
+ appId: "app_6",
360
+ appSecret: "secret_6", // pragma: allowlist secret
361
+ accountId: "timeout-cache-change",
362
+ config: { httpTimeoutMs: 45_000 },
363
+ });
364
+
365
+ expect(clientCtorMock.mock.calls.length).toBe(2);
366
+ const httpInstance = readLastClientHttpInstance();
367
+ await httpInstance.get("https://example.com/api");
368
+
369
+ expect(mockBaseHttpInstance.get).toHaveBeenCalledWith("https://example.com/api", {
370
+ timeout: 45_000,
371
+ });
372
+ });
373
+ });
374
+
375
+ describe("createFeishuWSClient proxy handling", () => {
376
+ it("passes heartbeat wsConfig defaults to Lark.WSClient", async () => {
377
+ await createFeishuWSClient(baseAccount);
378
+
379
+ const options = firstWsClientOptions();
380
+ expect(options.wsConfig).toEqual({
381
+ PingInterval: 30,
382
+ PingTimeout: 3,
383
+ });
384
+ });
385
+
386
+ it("passes lifecycle callbacks while preserving heartbeat wsConfig defaults", async () => {
387
+ const onError = vi.fn();
388
+ const onReady = vi.fn();
389
+ const onReconnected = vi.fn();
390
+ const onReconnecting = vi.fn();
391
+
392
+ await createFeishuWSClient(baseAccount, {
393
+ onError,
394
+ onReady,
395
+ onReconnected,
396
+ onReconnecting,
397
+ });
398
+
399
+ const options = firstWsClientOptions();
400
+ expect(options.onError).toBe(onError);
401
+ expect(options.onReady).toBe(onReady);
402
+ expect(options.onReconnected).toBe(onReconnected);
403
+ expect(options.onReconnecting).toBe(onReconnecting);
404
+ expect(options.wsConfig).toEqual({
405
+ PingInterval: 30,
406
+ PingTimeout: 3,
407
+ });
408
+ });
409
+
410
+ it("does not set a ws proxy agent when proxy env is absent", async () => {
411
+ await createFeishuWSClient(baseAccount);
412
+
413
+ expect(proxyAgentCtorMock).not.toHaveBeenCalled();
414
+ const options = firstWsClientOptions();
415
+ expect(options.agent).toBeUndefined();
416
+ });
417
+
418
+ it("creates a ws proxy agent when lowercase https_proxy is set", async () => {
419
+ process.env.https_proxy = "http://lower-https:8001";
420
+
421
+ await createFeishuWSClient(baseAccount);
422
+
423
+ expect(proxyAgentCtorMock).toHaveBeenCalledTimes(1);
424
+ const options = firstWsClientOptions();
425
+ expect(options.agent).toEqual({ proxied: true });
426
+ });
427
+
428
+ it("creates a ws proxy agent when uppercase HTTPS_PROXY is set", async () => {
429
+ process.env.HTTPS_PROXY = "http://upper-https:8002";
430
+
431
+ await createFeishuWSClient(baseAccount);
432
+
433
+ expect(proxyAgentCtorMock).toHaveBeenCalledTimes(1);
434
+ const options = firstWsClientOptions();
435
+ expect(options.agent).toEqual({ proxied: true });
436
+ });
437
+
438
+ it("falls back to HTTP_PROXY for ws proxy agent creation", async () => {
439
+ process.env.HTTP_PROXY = "http://upper-http:8999";
440
+
441
+ await createFeishuWSClient(baseAccount);
442
+
443
+ expect(proxyAgentCtorMock).toHaveBeenCalledTimes(1);
444
+ const options = firstWsClientOptions();
445
+ expect(options.agent).toEqual({ proxied: true });
446
+ });
447
+ });
package/src/client.ts ADDED
@@ -0,0 +1,262 @@
1
+ import type { Agent } from "node:https";
2
+ import { createRequire } from "node:module";
3
+ import * as Lark from "@larksuiteoapi/node-sdk";
4
+ import {
5
+ readPluginPackageVersion,
6
+ resolveAmbientNodeProxyAgent,
7
+ } from "klaw/plugin-sdk/extension-shared";
8
+ import {
9
+ FEISHU_HTTP_TIMEOUT_ENV_VAR,
10
+ FEISHU_HTTP_TIMEOUT_MAX_MS,
11
+ FEISHU_HTTP_TIMEOUT_MS,
12
+ resolveConfiguredHttpTimeoutMs,
13
+ } from "./client-timeout.js";
14
+ import type { FeishuConfig, FeishuDomain, ResolvedFeishuAccount } from "./types.js";
15
+
16
+ const require = createRequire(import.meta.url);
17
+ const pluginVersion = readPluginPackageVersion({ require });
18
+
19
+ export { pluginVersion };
20
+
21
+ const FEISHU_USER_AGENT = `klaw-feishu-builtin/${pluginVersion}/${process.platform}`;
22
+ export { FEISHU_USER_AGENT };
23
+
24
+ const FEISHU_WS_CONFIG = {
25
+ PingInterval: 30,
26
+ PingTimeout: 3,
27
+ } as const;
28
+
29
+ /** User-Agent header value for all Feishu API requests. */
30
+ export function getFeishuUserAgent(): string {
31
+ return FEISHU_USER_AGENT;
32
+ }
33
+
34
+ type FeishuClientSdk = Pick<
35
+ typeof Lark,
36
+ | "AppType"
37
+ | "Client"
38
+ | "defaultHttpInstance"
39
+ | "Domain"
40
+ | "EventDispatcher"
41
+ | "LoggerLevel"
42
+ | "WSClient"
43
+ >;
44
+
45
+ const defaultFeishuClientSdk: FeishuClientSdk = {
46
+ AppType: Lark.AppType,
47
+ Client: Lark.Client,
48
+ defaultHttpInstance: Lark.defaultHttpInstance,
49
+ Domain: Lark.Domain,
50
+ EventDispatcher: Lark.EventDispatcher,
51
+ LoggerLevel: Lark.LoggerLevel,
52
+ WSClient: Lark.WSClient,
53
+ };
54
+
55
+ let feishuClientSdk: FeishuClientSdk = defaultFeishuClientSdk;
56
+
57
+ // Override the SDK's default User-Agent interceptor.
58
+ // The Lark SDK registers an axios request interceptor that sets
59
+ // 'oapi-node-sdk/1.0.0'. Axios request interceptors execute in LIFO order
60
+ // (last-registered runs first), so simply appending ours doesn't work — the
61
+ // SDK's interceptor would run last and overwrite our UA. We must clear
62
+ // handlers[] first, then register our own as the sole interceptor.
63
+ //
64
+ // Risk is low: the SDK only registers one interceptor (UA) at init time, and
65
+ // we clear it at module load before any other code can register handlers.
66
+ // If a future SDK version adds more interceptors, the upgrade will need
67
+ // compatibility verification regardless.
68
+ {
69
+ const inst = Lark.defaultHttpInstance as {
70
+ interceptors?: {
71
+ request: { handlers: unknown[]; use: (fn: (req: unknown) => unknown) => void };
72
+ };
73
+ };
74
+ if (inst.interceptors?.request) {
75
+ inst.interceptors.request.handlers = [];
76
+ inst.interceptors.request.use((req: unknown) => {
77
+ const r = req as { headers?: Record<string, string> };
78
+ if (r.headers) {
79
+ r.headers["User-Agent"] = getFeishuUserAgent();
80
+ }
81
+ return req;
82
+ });
83
+ }
84
+ }
85
+
86
+ export { FEISHU_HTTP_TIMEOUT_ENV_VAR, FEISHU_HTTP_TIMEOUT_MAX_MS, FEISHU_HTTP_TIMEOUT_MS };
87
+
88
+ type FeishuHttpInstanceLike = Pick<
89
+ typeof feishuClientSdk.defaultHttpInstance,
90
+ "request" | "get" | "post" | "put" | "patch" | "delete" | "head" | "options"
91
+ >;
92
+
93
+ async function getWsProxyAgent() {
94
+ return resolveAmbientNodeProxyAgent<Agent>();
95
+ }
96
+
97
+ // Multi-account client cache
98
+ const clientCache = new Map<
99
+ string,
100
+ {
101
+ client: Lark.Client;
102
+ config: { appId: string; appSecret: string; domain?: FeishuDomain; httpTimeoutMs: number };
103
+ }
104
+ >();
105
+
106
+ function resolveDomain(domain: FeishuDomain | undefined): Lark.Domain | string {
107
+ if (domain === "lark") {
108
+ return feishuClientSdk.Domain.Lark;
109
+ }
110
+ if (domain === "feishu" || !domain) {
111
+ return feishuClientSdk.Domain.Feishu;
112
+ }
113
+ return domain.replace(/\/+$/, ""); // Custom URL for private deployment
114
+ }
115
+
116
+ /**
117
+ * Create an HTTP instance that delegates to the Lark SDK's default instance
118
+ * but injects a default request timeout and User-Agent header to prevent
119
+ * indefinite hangs and set a standardized User-Agent per OAPI best practices.
120
+ */
121
+ function createTimeoutHttpInstance(defaultTimeoutMs: number): Lark.HttpInstance {
122
+ const base: FeishuHttpInstanceLike = feishuClientSdk.defaultHttpInstance;
123
+
124
+ function injectTimeout<D>(opts?: Lark.HttpRequestOptions<D>): Lark.HttpRequestOptions<D> {
125
+ return { timeout: defaultTimeoutMs, ...opts } as Lark.HttpRequestOptions<D>;
126
+ }
127
+
128
+ return {
129
+ request: (opts) => base.request(injectTimeout(opts)),
130
+ get: (url, opts) => base.get(url, injectTimeout(opts)),
131
+ post: (url, data, opts) => base.post(url, data, injectTimeout(opts)),
132
+ put: (url, data, opts) => base.put(url, data, injectTimeout(opts)),
133
+ patch: (url, data, opts) => base.patch(url, data, injectTimeout(opts)),
134
+ delete: (url, opts) => base.delete(url, injectTimeout(opts)),
135
+ head: (url, opts) => base.head(url, injectTimeout(opts)),
136
+ options: (url, opts) => base.options(url, injectTimeout(opts)),
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Credentials needed to create a Feishu client.
142
+ * Both FeishuConfig and ResolvedFeishuAccount satisfy this interface.
143
+ */
144
+ export type FeishuClientCredentials = {
145
+ accountId?: string;
146
+ appId?: string;
147
+ appSecret?: string;
148
+ domain?: FeishuDomain;
149
+ httpTimeoutMs?: number;
150
+ config?: Pick<FeishuConfig, "httpTimeoutMs">;
151
+ };
152
+
153
+ /**
154
+ * Create or get a cached Feishu client for an account.
155
+ * Accepts any object with appId, appSecret, and optional domain/accountId.
156
+ */
157
+ export function createFeishuClient(creds: FeishuClientCredentials): Lark.Client {
158
+ const { accountId = "default", appId, appSecret, domain } = creds;
159
+ const defaultHttpTimeoutMs = resolveConfiguredHttpTimeoutMs(creds);
160
+
161
+ if (!appId || !appSecret) {
162
+ throw new Error(`Feishu credentials not configured for account "${accountId}"`);
163
+ }
164
+
165
+ // Check cache
166
+ const cached = clientCache.get(accountId);
167
+ if (
168
+ cached &&
169
+ cached.config.appId === appId &&
170
+ cached.config.appSecret === appSecret &&
171
+ cached.config.domain === domain &&
172
+ cached.config.httpTimeoutMs === defaultHttpTimeoutMs
173
+ ) {
174
+ return cached.client;
175
+ }
176
+
177
+ // Create new client with timeout-aware HTTP instance
178
+ const client = new feishuClientSdk.Client({
179
+ appId,
180
+ appSecret,
181
+ appType: feishuClientSdk.AppType.SelfBuild,
182
+ domain: resolveDomain(domain),
183
+ httpInstance: createTimeoutHttpInstance(defaultHttpTimeoutMs),
184
+ });
185
+
186
+ // Cache it
187
+ clientCache.set(accountId, {
188
+ client,
189
+ config: { appId, appSecret, domain, httpTimeoutMs: defaultHttpTimeoutMs },
190
+ });
191
+
192
+ return client;
193
+ }
194
+
195
+ export type FeishuWsClientCallbacks = Pick<
196
+ ConstructorParameters<typeof feishuClientSdk.WSClient>[0],
197
+ "onError" | "onReady" | "onReconnected" | "onReconnecting"
198
+ >;
199
+
200
+ /**
201
+ * Create a Feishu WebSocket client for an account.
202
+ * Note: WSClient is not cached since each call creates a new connection.
203
+ */
204
+ export async function createFeishuWSClient(
205
+ account: ResolvedFeishuAccount,
206
+ callbacks: FeishuWsClientCallbacks = {},
207
+ ): Promise<Lark.WSClient> {
208
+ const { accountId, appId, appSecret, domain } = account;
209
+
210
+ if (!appId || !appSecret) {
211
+ throw new Error(`Feishu credentials not configured for account "${accountId}"`);
212
+ }
213
+
214
+ const agent = await getWsProxyAgent();
215
+ return new feishuClientSdk.WSClient({
216
+ appId,
217
+ appSecret,
218
+ domain: resolveDomain(domain),
219
+ ...callbacks,
220
+ loggerLevel: feishuClientSdk.LoggerLevel.info,
221
+ wsConfig: FEISHU_WS_CONFIG,
222
+ ...(agent ? { agent } : {}),
223
+ } as ConstructorParameters<typeof feishuClientSdk.WSClient>[0] & {
224
+ wsConfig: typeof FEISHU_WS_CONFIG;
225
+ });
226
+ }
227
+
228
+ /**
229
+ * Create an event dispatcher for an account.
230
+ */
231
+ export function createEventDispatcher(account: ResolvedFeishuAccount): Lark.EventDispatcher {
232
+ return new feishuClientSdk.EventDispatcher({
233
+ encryptKey: account.encryptKey,
234
+ verificationToken: account.verificationToken,
235
+ });
236
+ }
237
+
238
+ /**
239
+ * Get a cached client for an account (if exists).
240
+ */
241
+ export function getFeishuClient(accountId: string): Lark.Client | null {
242
+ return clientCache.get(accountId)?.client ?? null;
243
+ }
244
+
245
+ /**
246
+ * Clear client cache for a specific account or all accounts.
247
+ */
248
+ export function clearClientCache(accountId?: string): void {
249
+ if (accountId) {
250
+ clientCache.delete(accountId);
251
+ } else {
252
+ clientCache.clear();
253
+ }
254
+ }
255
+
256
+ export function setFeishuClientRuntimeForTest(overrides?: {
257
+ sdk?: Partial<FeishuClientSdk>;
258
+ }): void {
259
+ feishuClientSdk = overrides?.sdk
260
+ ? { ...defaultFeishuClientSdk, ...overrides.sdk }
261
+ : defaultFeishuClientSdk;
262
+ }