@max1874/feishu 0.2.7 → 0.2.9

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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/docx.ts +292 -148
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@max1874/feishu",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "description": "OpenClaw Feishu/Lark channel plugin",
6
6
  "license": "MIT",
package/src/docx.ts CHANGED
@@ -64,101 +64,119 @@ const BLOCK_TYPE_NAMES: Record<number, string> = {
64
64
  32: "TableCell",
65
65
  };
66
66
 
67
- // Block types that cannot be created via documentBlockChildren.create API
68
- const UNSUPPORTED_CREATE_TYPES = new Set([
69
- 31, // Table - must use different API or workaround
70
- 32, // TableCell - child of Table
71
- ]);
72
-
73
- /** Clean blocks for insertion (remove unsupported types and read-only fields) */
74
- function cleanBlocksForInsert(blocks: any[]): { cleaned: any[]; skipped: string[] } {
75
- const skipped: string[] = [];
76
- const cleaned = blocks
77
- .filter((block) => {
78
- if (UNSUPPORTED_CREATE_TYPES.has(block.block_type)) {
79
- const typeName = BLOCK_TYPE_NAMES[block.block_type] || `type_${block.block_type}`;
80
- skipped.push(typeName);
81
- return false;
82
- }
83
- return true;
84
- })
85
- .map((block) => {
86
- // Remove any read-only fields that might slip through
87
- if (block.block_type === 31 && block.table?.merge_info) {
88
- const { merge_info, ...tableRest } = block.table;
89
- return { ...block, table: tableRest };
90
- }
91
- return block;
92
- });
93
- return { cleaned, skipped };
67
+ // Block types that need special handling (not via standard documentBlockChildren.create)
68
+ const TABLE_BLOCK_TYPE = 31;
69
+ const TABLE_CELL_BLOCK_TYPE = 32;
70
+
71
+ /** Extracted table data from convert API result */
72
+ interface TableData {
73
+ rowSize: number;
74
+ colSize: number;
75
+ cells: string[][]; // 2D array of cell text content
94
76
  }
95
77
 
96
- // ============ Core Functions ============
78
+ /** Extract table data from converted blocks (flat list with ID references) */
79
+ function extractTableFromBlocks(blocks: any[]): { tables: TableData[]; otherBlocks: any[] } {
80
+ const tables: TableData[] = [];
81
+ const otherBlocks: any[] = [];
97
82
 
98
- /**
99
- * Convert Markdown tables to code blocks.
100
- * Feishu API doesn't support creating Table blocks directly, so we preserve
101
- * table formatting by wrapping them in code blocks.
102
- */
103
- function convertTablesToCodeBlocks(markdown: string): string {
104
- const lines = markdown.split("\n");
105
- const result: string[] = [];
106
- let tableLines: string[] = [];
107
- let inTable = false;
108
-
109
- const isTableLine = (line: string): boolean => {
110
- const trimmed = line.trim();
111
- // Table line starts with | or is a separator line like |---|---|
112
- return trimmed.startsWith("|") && trimmed.endsWith("|");
113
- };
83
+ // Build a map of block_id -> block for quick lookup
84
+ const blockMap = new Map<string, any>();
85
+ for (const block of blocks) {
86
+ if (block.block_id) {
87
+ blockMap.set(block.block_id, block);
88
+ }
89
+ }
114
90
 
115
- const isSeparatorLine = (line: string): boolean => {
116
- const trimmed = line.trim();
117
- // Separator line contains only |, -, :, and spaces
118
- return /^\|[\s\-:|]+\|$/.test(trimmed);
119
- };
91
+ // Track which blocks are part of tables (to exclude from otherBlocks)
92
+ const tableRelatedIds = new Set<string>();
93
+
94
+ for (const block of blocks) {
95
+ if (block.block_type === TABLE_BLOCK_TYPE) {
96
+ tableRelatedIds.add(block.block_id);
97
+
98
+ const tableInfo = block.table;
99
+ if (tableInfo) {
100
+ const rowSize = tableInfo.property?.row_size ?? 0;
101
+ const colSize = tableInfo.property?.column_size ?? 0;
102
+
103
+ // Initialize cells array
104
+ const cells: string[][] = Array.from({ length: rowSize }, () =>
105
+ Array.from({ length: colSize }, () => ""),
106
+ );
107
+
108
+ // table.cells is a flat array of cell block IDs in row-major order
109
+ const cellIds: string[] = tableInfo.cells ?? [];
110
+
111
+ let cellIndex = 0;
112
+ for (let row = 0; row < rowSize; row++) {
113
+ for (let col = 0; col < colSize; col++) {
114
+ if (cellIndex >= cellIds.length) break;
115
+
116
+ const cellId = cellIds[cellIndex];
117
+ tableRelatedIds.add(cellId);
118
+
119
+ // Find the TableCell block
120
+ const cellBlock = blockMap.get(cellId);
121
+ if (cellBlock?.block_type === TABLE_CELL_BLOCK_TYPE) {
122
+ // Get text content from cell's children (Text blocks)
123
+ const childIds: string[] = cellBlock.children ?? [];
124
+ const textParts: string[] = [];
125
+
126
+ for (const childId of childIds) {
127
+ tableRelatedIds.add(childId);
128
+ const textBlock = blockMap.get(childId);
129
+ if (textBlock?.block_type === 2 && textBlock.text?.elements) {
130
+ const text = textBlock.text.elements
131
+ .filter((e: any) => e.text_run)
132
+ .map((e: any) => e.text_run.content)
133
+ .join("");
134
+ textParts.push(text);
135
+ }
136
+ }
137
+
138
+ cells[row][col] = textParts.join("\n");
139
+ }
140
+
141
+ cellIndex++;
142
+ }
143
+ }
120
144
 
121
- const flushTable = () => {
122
- if (tableLines.length >= 2) {
123
- // Check if we have a valid table (at least header + separator)
124
- const hasSeparator = tableLines.some(isSeparatorLine);
125
- if (hasSeparator) {
126
- // Wrap table in code block to preserve formatting
127
- result.push("```");
128
- result.push(...tableLines);
129
- result.push("```");
130
- } else {
131
- // Not a valid table, keep as-is
132
- result.push(...tableLines);
145
+ tables.push({ rowSize, colSize, cells });
133
146
  }
134
- } else {
135
- // Single line with |, keep as-is
136
- result.push(...tableLines);
137
147
  }
138
- tableLines = [];
139
- };
148
+ }
140
149
 
141
- for (const line of lines) {
142
- if (isTableLine(line)) {
143
- inTable = true;
144
- tableLines.push(line);
145
- } else {
146
- if (inTable) {
147
- flushTable();
148
- inTable = false;
149
- }
150
- result.push(line);
150
+ // Collect non-table blocks
151
+ for (const block of blocks) {
152
+ if (!tableRelatedIds.has(block.block_id)) {
153
+ otherBlocks.push(block);
151
154
  }
152
155
  }
153
156
 
154
- // Flush remaining table if any
155
- if (inTable) {
156
- flushTable();
157
- }
157
+ return { tables, otherBlocks };
158
+ }
159
+
160
+ /** Clean blocks for insertion (remove read-only fields and unsupported nested structures) */
161
+ function cleanBlocksForInsert(blocks: any[]): { cleaned: any[]; skipped: string[] } {
162
+ const skipped: string[] = [];
163
+ const cleaned = blocks.map((block) => {
164
+ const { children, parent_id, block_id, ...rest } = block;
165
+
166
+ // Remove children from non-table blocks (nested lists not supported in create API)
167
+ // Table children are handled separately via table.cells
168
+ if (block.block_type === TABLE_BLOCK_TYPE && block.table?.merge_info) {
169
+ const { merge_info, ...tableRest } = block.table;
170
+ return { ...rest, table: tableRest };
171
+ }
158
172
 
159
- return result.join("\n");
173
+ return rest;
174
+ });
175
+ return { cleaned, skipped };
160
176
  }
161
177
 
178
+ // ============ Core Functions ============
179
+
162
180
  /** Convert markdown to Feishu blocks using the Convert API */
163
181
  async function convertMarkdown(client: Lark.Client, markdown: string) {
164
182
  const res = await client.docx.document.convert({
@@ -171,10 +189,7 @@ async function convertMarkdown(client: Lark.Client, markdown: string) {
171
189
  };
172
190
  }
173
191
 
174
- /** Insert blocks as children of a parent block */
175
- // Batch size for inserting blocks (API may have limits)
176
- const INSERT_BATCH_SIZE = 50;
177
-
192
+ /** Insert blocks as children of a parent block (with batching for >50 blocks) */
178
193
  async function insertBlocks(
179
194
  client: Lark.Client,
180
195
  docToken: string,
@@ -188,23 +203,18 @@ async function insertBlocks(
188
203
  return { children: [], skipped };
189
204
  }
190
205
 
206
+ // Feishu API limits to 50 blocks per request
207
+ const BATCH_SIZE = 50;
191
208
  const allChildren: any[] = [];
192
209
 
193
- // Insert in batches to avoid API limits
194
- for (let i = 0; i < cleaned.length; i += INSERT_BATCH_SIZE) {
195
- const batch = cleaned.slice(i, i + INSERT_BATCH_SIZE);
196
- try {
197
- const res = await client.docx.documentBlockChildren.create({
198
- path: { document_id: docToken, block_id: blockId },
199
- data: { children: batch },
200
- });
201
- if (res.code !== 0) throw new Error(res.msg);
202
- allChildren.push(...(res.data?.children ?? []));
203
- } catch (err) {
204
- const blockTypes = batch.map((b) => BLOCK_TYPE_NAMES[b.block_type] || `type_${b.block_type}`);
205
- const errMsg = err instanceof Error ? err.message : String(err);
206
- throw new Error(`insertBlocks failed at batch ${Math.floor(i / INSERT_BATCH_SIZE) + 1}: ${errMsg}. Batch types: [${blockTypes.join(", ")}]. Batch size: ${batch.length}`);
207
- }
210
+ for (let i = 0; i < cleaned.length; i += BATCH_SIZE) {
211
+ const batch = cleaned.slice(i, i + BATCH_SIZE);
212
+ const res = await client.docx.documentBlockChildren.create({
213
+ path: { document_id: docToken, block_id: blockId },
214
+ data: { children: batch },
215
+ });
216
+ if (res.code !== 0) throw new Error(res.msg);
217
+ allChildren.push(...(res.data?.children ?? []));
208
218
  }
209
219
 
210
220
  return { children: allChildren, skipped };
@@ -266,6 +276,140 @@ async function downloadImage(url: string): Promise<Buffer> {
266
276
  return Buffer.from(await response.arrayBuffer());
267
277
  }
268
278
 
279
+ /** Create an empty table and return its block ID */
280
+ async function createEmptyTable(
281
+ client: Lark.Client,
282
+ docToken: string,
283
+ parentBlockId: string,
284
+ rowSize: number,
285
+ colSize: number,
286
+ ): Promise<string | null> {
287
+ const tableBlock = {
288
+ block_type: TABLE_BLOCK_TYPE,
289
+ table: {
290
+ property: {
291
+ row_size: rowSize,
292
+ column_size: colSize,
293
+ header_row: true,
294
+ },
295
+ cells: [], // Empty cells, will be filled later
296
+ },
297
+ };
298
+
299
+ const res = await client.docx.documentBlockChildren.create({
300
+ path: { document_id: docToken, block_id: parentBlockId },
301
+ data: { children: [tableBlock] },
302
+ });
303
+
304
+ if (res.code !== 0) {
305
+ console.error(`Failed to create table: ${res.msg}`);
306
+ return null;
307
+ }
308
+
309
+ const created = res.data?.children ?? [];
310
+ return created[0]?.block_id ?? null;
311
+ }
312
+
313
+ /** Get children blocks of a parent block */
314
+ async function getBlockChildren(
315
+ client: Lark.Client,
316
+ docToken: string,
317
+ blockId: string,
318
+ ): Promise<any[]> {
319
+ const res = await client.docx.documentBlockChildren.get({
320
+ path: { document_id: docToken, block_id: blockId },
321
+ });
322
+ if (res.code !== 0) {
323
+ throw new Error(`Failed to get block children: ${res.msg}`);
324
+ }
325
+ return res.data?.items ?? [];
326
+ }
327
+
328
+ /** Update a text block's content */
329
+ async function updateTextBlock(
330
+ client: Lark.Client,
331
+ docToken: string,
332
+ blockId: string,
333
+ content: string,
334
+ ): Promise<void> {
335
+ const res = await client.docx.documentBlock.patch({
336
+ path: { document_id: docToken, block_id: blockId },
337
+ data: {
338
+ update_text_elements: {
339
+ elements: [{ text_run: { content } }],
340
+ },
341
+ },
342
+ });
343
+ if (res.code !== 0) {
344
+ console.error(`Failed to update text block ${blockId}: ${res.msg}`);
345
+ }
346
+ }
347
+
348
+ /** Fill table cells with content */
349
+ async function fillTableContent(
350
+ client: Lark.Client,
351
+ docToken: string,
352
+ tableBlockId: string,
353
+ cells: string[][],
354
+ ): Promise<void> {
355
+ // Get table's cell blocks (they are direct children of the table)
356
+ const cellBlocks = await getBlockChildren(client, docToken, tableBlockId);
357
+
358
+ // Cells are in row-major order
359
+ const colSize = cells[0]?.length ?? 0;
360
+ let cellIndex = 0;
361
+
362
+ for (let row = 0; row < cells.length; row++) {
363
+ for (let col = 0; col < colSize; col++) {
364
+ if (cellIndex >= cellBlocks.length) break;
365
+
366
+ const cellBlock = cellBlocks[cellIndex];
367
+ const cellBlockId = cellBlock?.block_id;
368
+ const cellText = cells[row]?.[col] ?? "";
369
+
370
+ if (cellBlockId && cellText) {
371
+ // Each cell block contains text blocks as children
372
+ const cellChildren = await getBlockChildren(client, docToken, cellBlockId);
373
+ if (cellChildren.length > 0) {
374
+ // Update the first text block in the cell
375
+ const textBlockId = cellChildren[0]?.block_id;
376
+ if (textBlockId) {
377
+ await updateTextBlock(client, docToken, textBlockId, cellText);
378
+ }
379
+ }
380
+ }
381
+
382
+ cellIndex++;
383
+ }
384
+ }
385
+ }
386
+
387
+ /** Create and fill a table */
388
+ async function createAndFillTable(
389
+ client: Lark.Client,
390
+ docToken: string,
391
+ parentBlockId: string,
392
+ tableData: TableData,
393
+ ): Promise<boolean> {
394
+ // 1. Create empty table
395
+ const tableBlockId = await createEmptyTable(
396
+ client,
397
+ docToken,
398
+ parentBlockId,
399
+ tableData.rowSize,
400
+ tableData.colSize,
401
+ );
402
+
403
+ if (!tableBlockId) {
404
+ return false;
405
+ }
406
+
407
+ // 2. Fill table content
408
+ await fillTableContent(client, docToken, tableBlockId, tableData.cells);
409
+
410
+ return true;
411
+ }
412
+
269
413
  /** Process images in markdown: download from URL, upload to Feishu, update blocks */
270
414
  async function processImages(
271
415
  client: Lark.Client,
@@ -497,74 +641,74 @@ async function createDoc(
497
641
  }
498
642
 
499
643
  async function writeDoc(client: Lark.Client, docToken: string, markdown: string) {
500
- let step = "init";
501
- try {
502
- // 1. Clear existing content
503
- step = "clear_content";
504
- const deleted = await clearDocumentContent(client, docToken);
505
-
506
- // 2. Pre-process markdown (convert tables to code blocks)
507
- step = "preprocess_markdown";
508
- const processedMarkdown = convertTablesToCodeBlocks(markdown);
509
-
510
- // 3. Convert markdown to blocks
511
- step = "convert_markdown";
512
- const res = await client.docx.document.convert({
513
- data: { content_type: "markdown", content: processedMarkdown },
514
- });
515
- if (res.code !== 0) throw new Error(`convert failed: ${res.msg}`);
516
- const blocks = res.data?.blocks ?? [];
644
+ // 1. Clear existing content
645
+ const deleted = await clearDocumentContent(client, docToken);
517
646
 
518
- if (blocks.length === 0) {
519
- return { success: true, blocks_deleted: deleted, blocks_added: 0, images_processed: 0 };
520
- }
647
+ // 2. Convert markdown to blocks
648
+ const { blocks } = await convertMarkdown(client, markdown);
649
+ if (blocks.length === 0) {
650
+ return { success: true, blocks_deleted: deleted, blocks_added: 0, images_processed: 0, tables_created: 0 };
651
+ }
521
652
 
522
- // 4. Insert new blocks (unsupported types like Table are filtered)
523
- step = "insert_blocks";
524
- const { children: inserted, skipped } = await insertBlocks(client, docToken, blocks);
653
+ // 3. Separate tables from other blocks
654
+ const { tables, otherBlocks } = extractTableFromBlocks(blocks);
525
655
 
526
- // 5. Process images
527
- step = "process_images";
528
- const imagesProcessed = await processImages(client, docToken, markdown, inserted);
656
+ // 4. Insert non-table blocks
657
+ const { children: inserted, skipped } = await insertBlocks(client, docToken, otherBlocks);
529
658
 
530
- return {
531
- success: true,
532
- blocks_deleted: deleted,
533
- blocks_added: inserted.length,
534
- images_processed: imagesProcessed,
535
- ...(skipped.length > 0 && {
536
- warning: `Skipped unsupported block types: ${skipped.join(", ")}. Tables are not supported via this API.`,
537
- }),
538
- };
539
- } catch (err) {
540
- const errMsg = err instanceof Error ? err.message : String(err);
541
- throw new Error(`writeDoc failed at step '${step}': ${errMsg}`);
659
+ // 5. Create and fill tables
660
+ let tablesCreated = 0;
661
+ for (const tableData of tables) {
662
+ const success = await createAndFillTable(client, docToken, docToken, tableData);
663
+ if (success) tablesCreated++;
542
664
  }
665
+
666
+ // 6. Process images
667
+ const imagesProcessed = await processImages(client, docToken, markdown, inserted);
668
+
669
+ return {
670
+ success: true,
671
+ blocks_deleted: deleted,
672
+ blocks_added: inserted.length,
673
+ tables_created: tablesCreated,
674
+ images_processed: imagesProcessed,
675
+ ...(skipped.length > 0 && {
676
+ warning: `Skipped unsupported block types: ${skipped.join(", ")}.`,
677
+ }),
678
+ };
543
679
  }
544
680
 
545
681
  async function appendDoc(client: Lark.Client, docToken: string, markdown: string) {
546
- // 1. Pre-process markdown (convert tables to code blocks)
547
- const processedMarkdown = convertTablesToCodeBlocks(markdown);
548
-
549
- // 2. Convert markdown to blocks
550
- const { blocks } = await convertMarkdown(client, processedMarkdown);
682
+ // 1. Convert markdown to blocks
683
+ const { blocks } = await convertMarkdown(client, markdown);
551
684
  if (blocks.length === 0) {
552
685
  throw new Error("Content is empty");
553
686
  }
554
687
 
555
- // 3. Insert blocks (unsupported types like Table are filtered)
556
- const { children: inserted, skipped } = await insertBlocks(client, docToken, blocks);
688
+ // 2. Separate tables from other blocks
689
+ const { tables, otherBlocks } = extractTableFromBlocks(blocks);
690
+
691
+ // 3. Insert non-table blocks
692
+ const { children: inserted, skipped } = await insertBlocks(client, docToken, otherBlocks);
693
+
694
+ // 4. Create and fill tables
695
+ let tablesCreated = 0;
696
+ for (const tableData of tables) {
697
+ const success = await createAndFillTable(client, docToken, docToken, tableData);
698
+ if (success) tablesCreated++;
699
+ }
557
700
 
558
- // 4. Process images
701
+ // 5. Process images
559
702
  const imagesProcessed = await processImages(client, docToken, markdown, inserted);
560
703
 
561
704
  return {
562
705
  success: true,
563
706
  blocks_added: inserted.length,
707
+ tables_created: tablesCreated,
564
708
  images_processed: imagesProcessed,
565
709
  block_ids: inserted.map((b: any) => b.block_id),
566
710
  ...(skipped.length > 0 && {
567
- warning: `Skipped unsupported block types: ${skipped.join(", ")}. Tables are not supported via this API.`,
711
+ warning: `Skipped unsupported block types: ${skipped.join(", ")}.`,
568
712
  }),
569
713
  };
570
714
  }
@@ -803,7 +947,7 @@ export function registerFeishuDocTools(api: OpenClawPluginApi) {
803
947
  name: "feishu_doc_write",
804
948
  label: "Feishu Doc Write",
805
949
  description:
806
- "Write markdown content to a Feishu document (replaces all content). Supports headings, lists, code blocks, quotes, links, images, and text styling. Note: tables are not supported.",
950
+ "Write markdown content to a Feishu document (replaces all content). Supports headings, lists, code blocks, quotes, links, images, tables, and text styling.",
807
951
  parameters: WriteDocSchema,
808
952
  async execute(_toolCallId, params) {
809
953
  const { doc_token, content } = params as { doc_token: string; content: string };