@kodelyth/feishu 2026.5.42 → 2026.6.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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
package/src/directory.ts DELETED
@@ -1,124 +0,0 @@
1
- import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
2
- import type { ClawdbotConfig } from "../runtime-api.js";
3
- import { resolveFeishuAccount } from "./accounts.js";
4
- import { createFeishuClient } from "./client.js";
5
- import {
6
- listFeishuDirectoryGroups,
7
- listFeishuDirectoryPeers,
8
- type FeishuDirectoryGroup,
9
- type FeishuDirectoryPeer,
10
- } from "./directory.static.js";
11
-
12
- export async function listFeishuDirectoryPeersLive(params: {
13
- cfg: ClawdbotConfig;
14
- query?: string;
15
- limit?: number;
16
- accountId?: string;
17
- fallbackToStatic?: boolean;
18
- }): Promise<FeishuDirectoryPeer[]> {
19
- const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
20
- if (!account.configured) {
21
- return listFeishuDirectoryPeers(params);
22
- }
23
-
24
- try {
25
- const client = createFeishuClient(account);
26
- const peers: FeishuDirectoryPeer[] = [];
27
- const limit = params.limit ?? 50;
28
-
29
- const response = await client.contact.user.list({
30
- params: {
31
- page_size: Math.min(limit, 50),
32
- },
33
- });
34
-
35
- if (response.code !== 0) {
36
- throw new Error(response.msg || `code ${response.code}`);
37
- }
38
-
39
- const q = normalizeLowercaseStringOrEmpty(params.query);
40
- for (const user of response.data?.items ?? []) {
41
- if (user.open_id) {
42
- const name = user.name || "";
43
- if (
44
- !q ||
45
- normalizeLowercaseStringOrEmpty(user.open_id).includes(q) ||
46
- normalizeLowercaseStringOrEmpty(name).includes(q)
47
- ) {
48
- peers.push({
49
- kind: "user",
50
- id: user.open_id,
51
- name: name || undefined,
52
- });
53
- }
54
- }
55
- if (peers.length >= limit) {
56
- break;
57
- }
58
- }
59
-
60
- return peers;
61
- } catch (err) {
62
- if (params.fallbackToStatic === false) {
63
- throw err instanceof Error ? err : new Error("Feishu live peer lookup failed");
64
- }
65
- return listFeishuDirectoryPeers(params);
66
- }
67
- }
68
-
69
- export async function listFeishuDirectoryGroupsLive(params: {
70
- cfg: ClawdbotConfig;
71
- query?: string;
72
- limit?: number;
73
- accountId?: string;
74
- fallbackToStatic?: boolean;
75
- }): Promise<FeishuDirectoryGroup[]> {
76
- const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
77
- if (!account.configured) {
78
- return listFeishuDirectoryGroups(params);
79
- }
80
-
81
- try {
82
- const client = createFeishuClient(account);
83
- const groups: FeishuDirectoryGroup[] = [];
84
- const limit = params.limit ?? 50;
85
-
86
- const response = await client.im.chat.list({
87
- params: {
88
- page_size: Math.min(limit, 100),
89
- },
90
- });
91
-
92
- if (response.code !== 0) {
93
- throw new Error(response.msg || `code ${response.code}`);
94
- }
95
-
96
- const q = normalizeLowercaseStringOrEmpty(params.query);
97
- for (const chat of response.data?.items ?? []) {
98
- if (chat.chat_id) {
99
- const name = chat.name || "";
100
- if (
101
- !q ||
102
- normalizeLowercaseStringOrEmpty(chat.chat_id).includes(q) ||
103
- normalizeLowercaseStringOrEmpty(name).includes(q)
104
- ) {
105
- groups.push({
106
- kind: "group",
107
- id: chat.chat_id,
108
- name: name || undefined,
109
- });
110
- }
111
- }
112
- if (groups.length >= limit) {
113
- break;
114
- }
115
- }
116
-
117
- return groups;
118
- } catch (err) {
119
- if (params.fallbackToStatic === false) {
120
- throw err instanceof Error ? err : new Error("Feishu live group lookup failed");
121
- }
122
- return listFeishuDirectoryGroups(params);
123
- }
124
- }
package/src/doc-schema.ts DELETED
@@ -1,182 +0,0 @@
1
- import { Type, type Static } from "typebox";
2
-
3
- const tableCreationProperties = {
4
- doc_token: Type.String({ description: "Document token" }),
5
- parent_block_id: Type.Optional(
6
- Type.String({ description: "Parent block ID (default: document root)" }),
7
- ),
8
- row_size: Type.Integer({ description: "Table row count", minimum: 1 }),
9
- column_size: Type.Integer({ description: "Table column count", minimum: 1 }),
10
- column_width: Type.Optional(
11
- Type.Array(Type.Number({ minimum: 1 }), {
12
- description: "Column widths in px (length should match column_size)",
13
- }),
14
- ),
15
- };
16
-
17
- export const FeishuDocSchema = Type.Union([
18
- Type.Object({
19
- action: Type.Literal("read"),
20
- doc_token: Type.String({ description: "Document token (extract from URL /docx/XXX)" }),
21
- }),
22
- Type.Object({
23
- action: Type.Literal("write"),
24
- doc_token: Type.String({ description: "Document token" }),
25
- content: Type.String({
26
- description: "Markdown content to write (replaces entire document content)",
27
- }),
28
- }),
29
- Type.Object({
30
- action: Type.Literal("append"),
31
- doc_token: Type.String({ description: "Document token" }),
32
- content: Type.String({ description: "Markdown content to append to end of document" }),
33
- }),
34
- Type.Object({
35
- action: Type.Literal("insert"),
36
- doc_token: Type.String({ description: "Document token" }),
37
- content: Type.String({ description: "Markdown content to insert" }),
38
- after_block_id: Type.String({
39
- description: "Insert content after this block ID. Use list_blocks to find block IDs.",
40
- }),
41
- }),
42
- Type.Object({
43
- action: Type.Literal("create"),
44
- title: Type.String({ description: "Document title" }),
45
- folder_token: Type.Optional(Type.String({ description: "Target folder token (optional)" })),
46
- grant_to_requester: Type.Optional(
47
- Type.Boolean({
48
- description:
49
- "Grant edit permission to the trusted requesting Feishu user from runtime context (default: true).",
50
- }),
51
- ),
52
- }),
53
- Type.Object({
54
- action: Type.Literal("list_blocks"),
55
- doc_token: Type.String({ description: "Document token" }),
56
- }),
57
- Type.Object({
58
- action: Type.Literal("get_block"),
59
- doc_token: Type.String({ description: "Document token" }),
60
- block_id: Type.String({ description: "Block ID (from list_blocks)" }),
61
- }),
62
- Type.Object({
63
- action: Type.Literal("update_block"),
64
- doc_token: Type.String({ description: "Document token" }),
65
- block_id: Type.String({ description: "Block ID (from list_blocks)" }),
66
- content: Type.String({ description: "New text content" }),
67
- }),
68
- Type.Object({
69
- action: Type.Literal("delete_block"),
70
- doc_token: Type.String({ description: "Document token" }),
71
- block_id: Type.String({ description: "Block ID" }),
72
- }),
73
- // Table creation (explicit structure)
74
- Type.Object({
75
- action: Type.Literal("create_table"),
76
- ...tableCreationProperties,
77
- }),
78
- Type.Object({
79
- action: Type.Literal("write_table_cells"),
80
- doc_token: Type.String({ description: "Document token" }),
81
- table_block_id: Type.String({ description: "Table block ID" }),
82
- values: Type.Array(Type.Array(Type.String()), {
83
- description: "2D matrix values[row][col] to write into table cells",
84
- minItems: 1,
85
- }),
86
- }),
87
- Type.Object({
88
- action: Type.Literal("create_table_with_values"),
89
- ...tableCreationProperties,
90
- values: Type.Array(Type.Array(Type.String()), {
91
- description: "2D matrix values[row][col] to write into table cells",
92
- minItems: 1,
93
- }),
94
- }),
95
- // Table row/column manipulation
96
- Type.Object({
97
- action: Type.Literal("insert_table_row"),
98
- doc_token: Type.String({ description: "Document token" }),
99
- block_id: Type.String({ description: "Table block ID" }),
100
- row_index: Type.Optional(
101
- Type.Number({ description: "Row index to insert at (-1 for end, default: -1)" }),
102
- ),
103
- }),
104
- Type.Object({
105
- action: Type.Literal("insert_table_column"),
106
- doc_token: Type.String({ description: "Document token" }),
107
- block_id: Type.String({ description: "Table block ID" }),
108
- column_index: Type.Optional(
109
- Type.Number({ description: "Column index to insert at (-1 for end, default: -1)" }),
110
- ),
111
- }),
112
- Type.Object({
113
- action: Type.Literal("delete_table_rows"),
114
- doc_token: Type.String({ description: "Document token" }),
115
- block_id: Type.String({ description: "Table block ID" }),
116
- row_start: Type.Number({ description: "Start row index (0-based)" }),
117
- row_count: Type.Optional(Type.Number({ description: "Number of rows to delete (default: 1)" })),
118
- }),
119
- Type.Object({
120
- action: Type.Literal("delete_table_columns"),
121
- doc_token: Type.String({ description: "Document token" }),
122
- block_id: Type.String({ description: "Table block ID" }),
123
- column_start: Type.Number({ description: "Start column index (0-based)" }),
124
- column_count: Type.Optional(
125
- Type.Number({ description: "Number of columns to delete (default: 1)" }),
126
- ),
127
- }),
128
- Type.Object({
129
- action: Type.Literal("merge_table_cells"),
130
- doc_token: Type.String({ description: "Document token" }),
131
- block_id: Type.String({ description: "Table block ID" }),
132
- row_start: Type.Number({ description: "Start row index" }),
133
- row_end: Type.Number({ description: "End row index (exclusive)" }),
134
- column_start: Type.Number({ description: "Start column index" }),
135
- column_end: Type.Number({ description: "End column index (exclusive)" }),
136
- }),
137
- // Image / file upload
138
- Type.Object({
139
- action: Type.Literal("upload_image"),
140
- doc_token: Type.String({ description: "Document token" }),
141
- url: Type.Optional(Type.String({ description: "Remote image URL (http/https)" })),
142
- file_path: Type.Optional(Type.String({ description: "Local image file path" })),
143
- image: Type.Optional(
144
- Type.String({
145
- description:
146
- "Image as data URI (data:image/png;base64,...) or plain base64 string. Use instead of url/file_path for DALL-E outputs, canvas screenshots, etc.",
147
- }),
148
- ),
149
- parent_block_id: Type.Optional(
150
- Type.String({ description: "Parent block ID (default: document root)" }),
151
- ),
152
- filename: Type.Optional(Type.String({ description: "Optional filename override" })),
153
- index: Type.Optional(
154
- Type.Integer({
155
- minimum: 0,
156
- description: "Insert position (0-based index among siblings). Omit to append.",
157
- }),
158
- ),
159
- }),
160
- Type.Object({
161
- action: Type.Literal("upload_file"),
162
- doc_token: Type.String({ description: "Document token" }),
163
- url: Type.Optional(Type.String({ description: "Remote file URL (http/https)" })),
164
- file_path: Type.Optional(Type.String({ description: "Local file path" })),
165
- parent_block_id: Type.Optional(
166
- Type.String({ description: "Parent block ID (default: document root)" }),
167
- ),
168
- filename: Type.Optional(Type.String({ description: "Optional filename override" })),
169
- }),
170
- // Text color / style
171
- Type.Object({
172
- action: Type.Literal("color_text"),
173
- doc_token: Type.String({ description: "Document token" }),
174
- block_id: Type.String({ description: "Text block ID to update" }),
175
- content: Type.String({
176
- description:
177
- 'Text with color markup. Tags: [red], [green], [blue], [orange], [yellow], [purple], [grey], [bold], [bg:yellow]. Example: "Revenue [green]+15%[/green] YoY"',
178
- }),
179
- }),
180
- ]);
181
-
182
- export type FeishuDocParams = Static<typeof FeishuDocSchema>;
@@ -1,116 +0,0 @@
1
- import type * as Lark from "@larksuiteoapi/node-sdk";
2
- import { describe, expect, it, vi } from "vitest";
3
- import { BATCH_SIZE, insertBlocksInBatches } from "./docx-batch-insert.js";
4
- import type { FeishuDocxBlock } from "./docx-types.js";
5
-
6
- type InsertBlocksClient = Parameters<typeof insertBlocksInBatches>[0];
7
- type DocxDescendantCreate = Lark.Client["docx"]["documentBlockDescendant"]["create"];
8
- type DocxDescendantCreateParams = Parameters<DocxDescendantCreate>[0];
9
- type DocxDescendantCreateResponse = Awaited<ReturnType<DocxDescendantCreate>>;
10
- type RequiredDocxDescendantCreateParams = NonNullable<DocxDescendantCreateParams> & {
11
- data: NonNullable<NonNullable<DocxDescendantCreateParams>["data"]>;
12
- };
13
-
14
- function createDocxDescendantClient(create: DocxDescendantCreate): InsertBlocksClient {
15
- return {
16
- docx: {
17
- documentBlockDescendant: {
18
- create,
19
- },
20
- },
21
- } as InsertBlocksClient;
22
- }
23
-
24
- function createCountingIterable<T>(values: T[]) {
25
- let iterations = 0;
26
- return {
27
- values: {
28
- [Symbol.iterator]: function* () {
29
- iterations += 1;
30
- yield* values;
31
- },
32
- },
33
- getIterations: () => iterations,
34
- };
35
- }
36
-
37
- function createSuccessfulDocxDescendantCreateMock() {
38
- return vi.fn(
39
- async (params?: DocxDescendantCreateParams): Promise<DocxDescendantCreateResponse> => ({
40
- code: 0,
41
- data: {
42
- children: (params?.data?.children_id ?? []).map((id) => ({
43
- block_id: id,
44
- block_type: 2,
45
- })),
46
- },
47
- }),
48
- );
49
- }
50
-
51
- function createCallParams(
52
- createMock: ReturnType<typeof createSuccessfulDocxDescendantCreateMock>,
53
- index = 0,
54
- ): RequiredDocxDescendantCreateParams {
55
- const call = createMock.mock.calls.at(index);
56
- if (!call) {
57
- throw new Error(`Expected DOCX descendant create call ${index}`);
58
- }
59
- const params = call.at(0);
60
- if (!params) {
61
- throw new Error(`Expected DOCX descendant create params ${index}`);
62
- }
63
- if (!params.data) {
64
- throw new Error(`Expected DOCX descendant create data ${index}`);
65
- }
66
- return params as RequiredDocxDescendantCreateParams;
67
- }
68
-
69
- describe("insertBlocksInBatches", () => {
70
- it("builds the source block map once for large flat trees", async () => {
71
- const blockCount = BATCH_SIZE + 200;
72
- const blocks = Array.from({ length: blockCount }, (_, index) => ({
73
- block_id: `block_${index}`,
74
- block_type: 2,
75
- }));
76
- const counting = createCountingIterable(blocks);
77
- const createMock = createSuccessfulDocxDescendantCreateMock();
78
- const client = createDocxDescendantClient((params) => createMock(params));
79
-
80
- const result = await insertBlocksInBatches(
81
- client,
82
- "doc_1",
83
- Array.from(counting.values),
84
- blocks.map((block) => block.block_id),
85
- );
86
-
87
- expect(counting.getIterations()).toBe(1);
88
- expect(createMock).toHaveBeenCalledTimes(2);
89
- expect(createCallParams(createMock).data.children_id).toHaveLength(BATCH_SIZE);
90
- expect(createCallParams(createMock, 1).data.children_id).toHaveLength(200);
91
- expect(result.children).toHaveLength(blockCount);
92
- });
93
-
94
- it("keeps nested descendants grouped with their root blocks", async () => {
95
- const createMock = createSuccessfulDocxDescendantCreateMock();
96
- const client = createDocxDescendantClient((params) => createMock(params));
97
- const blocks: FeishuDocxBlock[] = [
98
- { block_id: "root_a", block_type: 1, children: ["child_a"] },
99
- { block_id: "child_a", block_type: 2 },
100
- { block_id: "root_b", block_type: 1, children: ["child_b"] },
101
- { block_id: "child_b", block_type: 2 },
102
- ];
103
-
104
- await insertBlocksInBatches(client, "doc_1", blocks, ["root_a", "root_b"]);
105
-
106
- expect(createMock).toHaveBeenCalledTimes(1);
107
- const createParams = createCallParams(createMock);
108
- expect(createParams.data.children_id).toEqual(["root_a", "root_b"]);
109
- expect(createParams.data.descendants.map((block) => block.block_id ?? "")).toEqual([
110
- "root_a",
111
- "child_a",
112
- "root_b",
113
- "child_b",
114
- ]);
115
- });
116
- });
@@ -1,223 +0,0 @@
1
- /**
2
- * Batch insertion for large Feishu documents (>1000 blocks).
3
- *
4
- * The Feishu Descendant API has a limit of 1000 blocks per request.
5
- * This module handles splitting large documents into batches while
6
- * preserving parent-child relationships between blocks.
7
- */
8
-
9
- import type * as Lark from "@larksuiteoapi/node-sdk";
10
- import { readStringValue } from "klaw/plugin-sdk/string-coerce-runtime";
11
- import { cleanBlocksForDescendant } from "./docx-table-ops.js";
12
- import type { FeishuDocxBlock, FeishuDocxBlockChild } from "./docx-types.js";
13
-
14
- export const BATCH_SIZE = 1000; // Feishu API limit per request
15
-
16
- type Logger = { info?: (msg: string) => void };
17
-
18
- type DocxDescendantCreatePayload = NonNullable<
19
- Parameters<Lark.Client["docx"]["documentBlockDescendant"]["create"]>[0]
20
- >;
21
- type DocxDescendantCreateBlock = NonNullable<
22
- NonNullable<DocxDescendantCreatePayload["data"]>["descendants"]
23
- >[number];
24
-
25
- function normalizeChildIds(children: string[] | string | undefined): string[] | undefined {
26
- if (Array.isArray(children)) {
27
- return children;
28
- }
29
- const child = readStringValue(children);
30
- return child ? [child] : undefined;
31
- }
32
-
33
- function toDescendantBlock(block: FeishuDocxBlock): DocxDescendantCreateBlock {
34
- const children = normalizeChildIds(block.children);
35
- return {
36
- ...block,
37
- ...(children ? { children } : {}),
38
- } as DocxDescendantCreateBlock;
39
- }
40
-
41
- /**
42
- * Collect all descendant blocks for a given first-level block ID.
43
- * Recursively traverses the block tree to gather all children.
44
- */
45
- function collectDescendants(
46
- blockMap: Map<string, FeishuDocxBlock>,
47
- rootId: string,
48
- ): FeishuDocxBlock[] {
49
- const result: FeishuDocxBlock[] = [];
50
- const visited = new Set<string>();
51
-
52
- function collect(blockId: string) {
53
- if (visited.has(blockId)) {
54
- return;
55
- }
56
- visited.add(blockId);
57
-
58
- const block = blockMap.get(blockId);
59
- if (!block) {
60
- return;
61
- }
62
-
63
- result.push(block);
64
-
65
- // Recursively collect children
66
- const children = block.children;
67
- if (Array.isArray(children)) {
68
- for (const childId of children) {
69
- collect(childId);
70
- }
71
- } else if (typeof children === "string") {
72
- collect(children);
73
- }
74
- }
75
-
76
- collect(rootId);
77
-
78
- return result;
79
- }
80
-
81
- /**
82
- * Insert a single batch of blocks using Descendant API.
83
- *
84
- * @param parentBlockId - Parent block to insert into (defaults to docToken)
85
- * @param index - Position within parent's children (-1 = end)
86
- */
87
- async function insertBatch(
88
- client: Lark.Client,
89
- docToken: string,
90
- blocks: FeishuDocxBlock[],
91
- firstLevelBlockIds: string[],
92
- parentBlockId: string = docToken,
93
- index: number = -1,
94
- ): Promise<FeishuDocxBlockChild[]> {
95
- const descendants = cleanBlocksForDescendant(blocks);
96
-
97
- if (descendants.length === 0) {
98
- return [];
99
- }
100
-
101
- const res = await client.docx.documentBlockDescendant.create({
102
- path: { document_id: docToken, block_id: parentBlockId },
103
- data: {
104
- children_id: firstLevelBlockIds,
105
- descendants: descendants.map(toDescendantBlock),
106
- index,
107
- },
108
- });
109
-
110
- if (res.code !== 0) {
111
- throw new Error(`${res.msg} (code: ${res.code})`);
112
- }
113
-
114
- return res.data?.children ?? [];
115
- }
116
-
117
- /**
118
- * Insert blocks in batches for large documents (>1000 blocks).
119
- *
120
- * Batches are split to ensure BOTH children_id AND descendants
121
- * arrays stay under the 1000 block API limit.
122
- *
123
- * @param client - Feishu API client
124
- * @param docToken - Document ID
125
- * @param blocks - All blocks from Convert API
126
- * @param firstLevelBlockIds - IDs of top-level blocks to insert
127
- * @param logger - Optional logger for progress updates
128
- * @param parentBlockId - Parent block to insert into (defaults to docToken = document root)
129
- * @param startIndex - Starting position within parent (-1 = end). For multi-batch inserts,
130
- * each batch advances this by the number of first-level IDs inserted so far.
131
- * @returns Inserted children blocks and any skipped block IDs
132
- */
133
- export async function insertBlocksInBatches(
134
- client: Lark.Client,
135
- docToken: string,
136
- blocks: FeishuDocxBlock[],
137
- firstLevelBlockIds: string[],
138
- logger?: Logger,
139
- parentBlockId: string = docToken,
140
- startIndex: number = -1,
141
- ): Promise<{ children: FeishuDocxBlockChild[]; skipped: string[] }> {
142
- const allChildren: FeishuDocxBlockChild[] = [];
143
-
144
- // Build batches ensuring each batch has ≤1000 total descendants
145
- const batches: Array<{ firstLevelIds: string[]; blocks: FeishuDocxBlock[] }> = [];
146
- let currentBatch: { firstLevelIds: string[]; blocks: FeishuDocxBlock[] } = {
147
- firstLevelIds: [],
148
- blocks: [],
149
- };
150
- const usedBlockIds = new Set<string>();
151
- const blockMap = new Map<string, FeishuDocxBlock>();
152
- for (const block of blocks) {
153
- if (block.block_id) {
154
- blockMap.set(block.block_id, block);
155
- }
156
- }
157
-
158
- for (const firstLevelId of firstLevelBlockIds) {
159
- const descendants = collectDescendants(blockMap, firstLevelId);
160
- const newBlocks = descendants.filter((b) => b.block_id && !usedBlockIds.has(b.block_id));
161
-
162
- // A single block whose subtree exceeds the API limit cannot be split
163
- // (a table or other compound block must be inserted atomically).
164
- if (newBlocks.length > BATCH_SIZE) {
165
- throw new Error(
166
- `Block "${firstLevelId}" has ${newBlocks.length} descendants, which exceeds the ` +
167
- `Feishu API limit of ${BATCH_SIZE} blocks per request. ` +
168
- `Please split the content into smaller sections.`,
169
- );
170
- }
171
-
172
- // If adding this first-level block would exceed limit, start new batch
173
- if (
174
- currentBatch.blocks.length + newBlocks.length > BATCH_SIZE &&
175
- currentBatch.blocks.length > 0
176
- ) {
177
- batches.push(currentBatch);
178
- currentBatch = { firstLevelIds: [], blocks: [] };
179
- }
180
-
181
- // Add to current batch
182
- currentBatch.firstLevelIds.push(firstLevelId);
183
- for (const block of newBlocks) {
184
- currentBatch.blocks.push(block);
185
- if (block.block_id) {
186
- usedBlockIds.add(block.block_id);
187
- }
188
- }
189
- }
190
-
191
- // Don't forget the last batch
192
- if (currentBatch.blocks.length > 0) {
193
- batches.push(currentBatch);
194
- }
195
-
196
- // Insert each batch, advancing index for position-aware inserts.
197
- // When startIndex == -1 (append to end), each batch appends after the previous.
198
- // When startIndex >= 0, each batch starts at startIndex + count of first-level IDs already inserted.
199
- let currentIndex = startIndex;
200
- for (let i = 0; i < batches.length; i++) {
201
- const batch = batches[i];
202
- logger?.info?.(
203
- `feishu_doc: Inserting batch ${i + 1}/${batches.length} (${batch.blocks.length} blocks)...`,
204
- );
205
-
206
- const children = await insertBatch(
207
- client,
208
- docToken,
209
- batch.blocks,
210
- batch.firstLevelIds,
211
- parentBlockId,
212
- currentIndex,
213
- );
214
- allChildren.push(...children);
215
-
216
- // Advance index only for explicit positions; -1 always means "after last inserted"
217
- if (currentIndex !== -1) {
218
- currentIndex += batch.firstLevelIds.length;
219
- }
220
- }
221
-
222
- return { children: allChildren, skipped: [] };
223
- }