@nextclaw/channel-plugin-feishu 0.2.16 → 0.2.17

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.
package/src/oauth.ts ADDED
@@ -0,0 +1,248 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { OpenClawPluginApi } from "./nextclaw-sdk/feishu.js";
3
+ import { listEnabledFeishuAccounts } from "./accounts.js";
4
+ import { requestDeviceAuthorization, pollDeviceToken } from "./device-flow.js";
5
+ import { feishuFetch } from "./feishu-fetch.js";
6
+ import { getTicket } from "./lark-ticket.js";
7
+ import { getStoredToken, setStoredToken, tokenStatus } from "./token-store.js";
8
+ import { resolveAnyEnabledFeishuToolsConfig } from "./tool-account.js";
9
+ import { revokeUAT } from "./uat-client.js";
10
+ import { createUserToolClient } from "./user-tool-client.js";
11
+ import { jsonToolResult } from "./tool-result.js";
12
+ import { getAllKnownScopes } from "./tool-scopes.js";
13
+
14
+ const FeishuOAuthSchema = Type.Object({
15
+ action: Type.Union([
16
+ Type.Literal("authorize"),
17
+ Type.Literal("status"),
18
+ Type.Literal("revoke"),
19
+ ]),
20
+ scope: Type.Optional(
21
+ Type.String({
22
+ description: "可选,自定义 scope 空格串;不传时默认申请当前集成能力需要的全部高价值 scope。",
23
+ }),
24
+ ),
25
+ wait_seconds: Type.Optional(
26
+ Type.Integer({
27
+ description: "authorize 后轮询等待秒数,默认 15,最大 60。",
28
+ minimum: 0,
29
+ maximum: 60,
30
+ }),
31
+ ),
32
+ });
33
+
34
+ function json(data: unknown) {
35
+ return jsonToolResult(data);
36
+ }
37
+
38
+ async function verifyTokenIdentity(
39
+ domain: "feishu" | "lark" | (string & {}),
40
+ accessToken: string,
41
+ expectedOpenId: string,
42
+ ): Promise<{ valid: boolean; actualOpenId?: string }> {
43
+ const baseUrl = domain === "lark" ? "https://open.larksuite.com" : "https://open.feishu.cn";
44
+ const response = await feishuFetch(`${baseUrl}/open-apis/authen/v1/user_info`, {
45
+ headers: { Authorization: `Bearer ${accessToken}` },
46
+ });
47
+ const data = (await response.json()) as {
48
+ code?: number;
49
+ data?: { open_id?: string };
50
+ };
51
+ const actualOpenId = data.data?.open_id;
52
+ return {
53
+ valid: data.code === 0 && actualOpenId === expectedOpenId,
54
+ actualOpenId,
55
+ };
56
+ }
57
+
58
+ async function handleOAuthStatus(params: {
59
+ appId: string;
60
+ senderOpenId: string;
61
+ }) {
62
+ const stored = await getStoredToken(params.appId, params.senderOpenId);
63
+ if (!stored) {
64
+ return json({
65
+ authorized: false,
66
+ user_open_id: params.senderOpenId,
67
+ });
68
+ }
69
+ return json({
70
+ authorized: true,
71
+ user_open_id: params.senderOpenId,
72
+ scope: stored.scope,
73
+ token_status: tokenStatus(stored),
74
+ granted_at: new Date(stored.grantedAt).toISOString(),
75
+ expires_at: new Date(stored.expiresAt).toISOString(),
76
+ refresh_expires_at: new Date(stored.refreshExpiresAt).toISOString(),
77
+ });
78
+ }
79
+
80
+ async function handleOAuthRevoke(params: {
81
+ appId: string;
82
+ senderOpenId: string;
83
+ }) {
84
+ await revokeUAT(params.appId, params.senderOpenId);
85
+ return json({
86
+ success: true,
87
+ user_open_id: params.senderOpenId,
88
+ message: "当前用户的飞书 OAuth 授权已撤销。",
89
+ });
90
+ }
91
+
92
+ async function handleOAuthAuthorize(params: {
93
+ account: ReturnType<typeof createUserToolClient>["account"];
94
+ senderOpenId: string;
95
+ scope?: string;
96
+ waitSeconds?: number;
97
+ }) {
98
+ const scope = params.scope?.trim() || getAllKnownScopes().join(" ");
99
+ const waitSeconds = Math.min(Math.max(params.waitSeconds ?? 15, 0), 60);
100
+ const deviceFlow = await requestDeviceAuthorization({
101
+ appId: params.account.appId,
102
+ appSecret: params.account.appSecret,
103
+ domain: params.account.domain,
104
+ scope,
105
+ });
106
+
107
+ const controller = new AbortController();
108
+ const timeout = setTimeout(() => controller.abort(), waitSeconds * 1000);
109
+ try {
110
+ const result = await pollDeviceToken({
111
+ appId: params.account.appId,
112
+ appSecret: params.account.appSecret,
113
+ domain: params.account.domain,
114
+ deviceCode: deviceFlow.deviceCode,
115
+ interval: deviceFlow.interval,
116
+ expiresIn: deviceFlow.expiresIn,
117
+ signal: controller.signal,
118
+ });
119
+
120
+ if (!result.ok) {
121
+ return json({
122
+ authorized: false,
123
+ status: result.error,
124
+ message: result.message,
125
+ user_open_id: params.senderOpenId,
126
+ verification_uri: deviceFlow.verificationUri,
127
+ verification_uri_complete: deviceFlow.verificationUriComplete,
128
+ user_code: deviceFlow.userCode,
129
+ requested_scope: scope,
130
+ });
131
+ }
132
+
133
+ const verified = await verifyTokenIdentity(
134
+ params.account.domain,
135
+ result.token.accessToken,
136
+ params.senderOpenId,
137
+ );
138
+ if (!verified.valid) {
139
+ return json({
140
+ authorized: false,
141
+ status: "identity_mismatch",
142
+ message: "完成授权的飞书账号与当前消息发送者不一致,已拒绝写入令牌。",
143
+ expected_open_id: params.senderOpenId,
144
+ actual_open_id: verified.actualOpenId,
145
+ });
146
+ }
147
+
148
+ const now = Date.now();
149
+ await setStoredToken({
150
+ userOpenId: params.senderOpenId,
151
+ appId: params.account.appId,
152
+ accessToken: result.token.accessToken,
153
+ refreshToken: result.token.refreshToken,
154
+ expiresAt: now + result.token.expiresIn * 1000,
155
+ refreshExpiresAt: now + result.token.refreshExpiresIn * 1000,
156
+ scope: result.token.scope,
157
+ grantedAt: now,
158
+ });
159
+ return json({
160
+ authorized: true,
161
+ user_open_id: params.senderOpenId,
162
+ scope: result.token.scope,
163
+ expires_at: new Date(now + result.token.expiresIn * 1000).toISOString(),
164
+ message: "飞书 OAuth 授权成功,后续工具将按当前用户身份执行。",
165
+ });
166
+ } catch (error) {
167
+ if (!controller.signal.aborted) {
168
+ throw error;
169
+ }
170
+ return json({
171
+ authorized: false,
172
+ status: "authorization_pending",
173
+ message:
174
+ "授权请求已创建,但在等待窗口内尚未完成。请打开链接完成授权后重新调用 feishu_oauth status 或再次 authorize。",
175
+ user_open_id: params.senderOpenId,
176
+ verification_uri: deviceFlow.verificationUri,
177
+ verification_uri_complete: deviceFlow.verificationUriComplete,
178
+ user_code: deviceFlow.userCode,
179
+ requested_scope: scope,
180
+ });
181
+ } finally {
182
+ clearTimeout(timeout);
183
+ }
184
+ }
185
+
186
+ export function registerFeishuOAuthTool(api: OpenClawPluginApi) {
187
+ if (!api.config) {
188
+ return;
189
+ }
190
+
191
+ const accounts = listEnabledFeishuAccounts(api.config);
192
+ if (accounts.length === 0) {
193
+ return;
194
+ }
195
+
196
+ const toolsConfig = resolveAnyEnabledFeishuToolsConfig(accounts);
197
+ if (!toolsConfig.oauth) {
198
+ return;
199
+ }
200
+
201
+ api.registerTool(
202
+ {
203
+ name: "feishu_oauth",
204
+ label: "Feishu OAuth",
205
+ description:
206
+ "管理当前消息发送者的飞书 OAuth 授权。支持 authorize/status/revoke,授权后 calendar/task/sheets/identity 工具即可按本人身份执行。",
207
+ parameters: FeishuOAuthSchema,
208
+ async execute(_toolCallId, params) {
209
+ const payload = params as {
210
+ action: "authorize" | "status" | "revoke";
211
+ scope?: string;
212
+ wait_seconds?: number;
213
+ };
214
+
215
+ const ticket = getTicket();
216
+ const senderOpenId = ticket?.senderOpenId;
217
+ if (!senderOpenId) {
218
+ return json({
219
+ error: "missing_sender_identity",
220
+ message: "当前不在飞书消息上下文中,无法按本人身份管理 OAuth。",
221
+ });
222
+ }
223
+
224
+ try {
225
+ const client = createUserToolClient(api.config);
226
+ const account = client.account;
227
+ if (payload.action === "status") {
228
+ return handleOAuthStatus({ appId: account.appId, senderOpenId });
229
+ }
230
+ if (payload.action === "revoke") {
231
+ return handleOAuthRevoke({ appId: account.appId, senderOpenId });
232
+ }
233
+ return handleOAuthAuthorize({
234
+ account,
235
+ senderOpenId,
236
+ scope: payload.scope,
237
+ waitSeconds: payload.wait_seconds,
238
+ });
239
+ } catch (error) {
240
+ return json({
241
+ error: error instanceof Error ? error.message : String(error),
242
+ });
243
+ }
244
+ },
245
+ },
246
+ { name: "feishu_oauth" },
247
+ );
248
+ }
@@ -0,0 +1,45 @@
1
+ import { feishuFetch } from "./feishu-fetch.js";
2
+ import { resolveDomainUrl } from "./domains.js";
3
+ import type { FeishuDomain } from "./types.js";
4
+
5
+ export async function rawLarkRequest<T>(options: {
6
+ domain: FeishuDomain;
7
+ path: string;
8
+ method?: string;
9
+ body?: unknown;
10
+ query?: Record<string, string>;
11
+ headers?: Record<string, string>;
12
+ accessToken?: string;
13
+ }): Promise<T> {
14
+ const url = new URL(options.path, resolveDomainUrl(options.domain));
15
+ for (const [key, value] of Object.entries(options.query ?? {})) {
16
+ url.searchParams.set(key, value);
17
+ }
18
+
19
+ const headers: Record<string, string> = {
20
+ ...(options.headers ?? {}),
21
+ };
22
+ if (options.accessToken) {
23
+ headers.Authorization = `Bearer ${options.accessToken}`;
24
+ }
25
+ if (options.body !== undefined && !headers["Content-Type"]) {
26
+ headers["Content-Type"] = "application/json";
27
+ }
28
+
29
+ const response = await feishuFetch(url.toString(), {
30
+ method: options.method ?? "GET",
31
+ headers,
32
+ ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
33
+ });
34
+ const data = (await response.json()) as { code?: number; msg?: string };
35
+ if (data.code !== undefined && data.code !== 0) {
36
+ const error = new Error(data.msg ?? `Feishu API error: code=${data.code}`) as Error & {
37
+ code?: number;
38
+ msg?: string;
39
+ };
40
+ error.code = data.code;
41
+ error.msg = data.msg;
42
+ throw error;
43
+ }
44
+ return data as T;
45
+ }
package/src/sheets.ts ADDED
@@ -0,0 +1,374 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { OpenClawPluginApi } from "./nextclaw-sdk/feishu.js";
3
+ import { listEnabledFeishuAccounts } from "./accounts.js";
4
+ import { wwwDomain } from "./domains.js";
5
+ import { resolveAnyEnabledFeishuToolsConfig } from "./tool-account.js";
6
+ import {
7
+ assertLarkOk,
8
+ createToolContext,
9
+ handleInvokeError,
10
+ json,
11
+ registerTool,
12
+ StringEnum,
13
+ } from "./user-tool-helpers.js";
14
+
15
+ const MAX_READ_ROWS = 200;
16
+ const MAX_WRITE_ROWS = 5000;
17
+ const MAX_WRITE_COLS = 100;
18
+
19
+ const SheetSchema = Type.Union([
20
+ Type.Object({ action: Type.Literal("info"), url: Type.Optional(Type.String()), spreadsheet_token: Type.Optional(Type.String()) }),
21
+ Type.Object({
22
+ action: Type.Literal("read"),
23
+ url: Type.Optional(Type.String()),
24
+ spreadsheet_token: Type.Optional(Type.String()),
25
+ range: Type.Optional(Type.String()),
26
+ sheet_id: Type.Optional(Type.String()),
27
+ value_render_option: Type.Optional(StringEnum(["FormattedValue", "UnformattedValue", "Formula", "ToString"])),
28
+ }),
29
+ Type.Object({
30
+ action: Type.Literal("write"),
31
+ url: Type.Optional(Type.String()),
32
+ spreadsheet_token: Type.Optional(Type.String()),
33
+ range: Type.Optional(Type.String()),
34
+ sheet_id: Type.Optional(Type.String()),
35
+ values: Type.Array(Type.Array(Type.Any())),
36
+ }),
37
+ Type.Object({
38
+ action: Type.Literal("append"),
39
+ url: Type.Optional(Type.String()),
40
+ spreadsheet_token: Type.Optional(Type.String()),
41
+ range: Type.Optional(Type.String()),
42
+ sheet_id: Type.Optional(Type.String()),
43
+ values: Type.Array(Type.Array(Type.Any())),
44
+ }),
45
+ Type.Object({
46
+ action: Type.Literal("find"),
47
+ url: Type.Optional(Type.String()),
48
+ spreadsheet_token: Type.Optional(Type.String()),
49
+ sheet_id: Type.String(),
50
+ range: Type.Optional(Type.String()),
51
+ find: Type.String(),
52
+ match_case: Type.Optional(Type.Boolean()),
53
+ match_entire_cell: Type.Optional(Type.Boolean()),
54
+ search_by_regex: Type.Optional(Type.Boolean()),
55
+ include_formulas: Type.Optional(Type.Boolean()),
56
+ }),
57
+ Type.Object({
58
+ action: Type.Literal("create"),
59
+ title: Type.String(),
60
+ folder_token: Type.Optional(Type.String()),
61
+ headers: Type.Optional(Type.Array(Type.Any())),
62
+ data: Type.Optional(Type.Array(Type.Array(Type.Any()))),
63
+ }),
64
+ Type.Object({
65
+ action: Type.Literal("export"),
66
+ url: Type.Optional(Type.String()),
67
+ spreadsheet_token: Type.Optional(Type.String()),
68
+ sheet_id: Type.Optional(Type.String()),
69
+ file_extension: StringEnum(["xlsx", "csv"]),
70
+ }),
71
+ ]);
72
+
73
+ function parseSheetUrl(url: string): { token: string; sheetId?: string } | null {
74
+ try {
75
+ const parsed = new URL(url);
76
+ const match = parsed.pathname.match(/\/sheets\/([^/?#]+)/);
77
+ if (!match) {
78
+ return null;
79
+ }
80
+ return {
81
+ token: match[1],
82
+ sheetId: parsed.searchParams.get("sheet") || undefined,
83
+ };
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ function resolveToken(params: { url?: string; spreadsheet_token?: string }) {
90
+ if (params.spreadsheet_token) {
91
+ return { token: params.spreadsheet_token };
92
+ }
93
+ if (params.url) {
94
+ return parseSheetUrl(params.url);
95
+ }
96
+ return null;
97
+ }
98
+
99
+ function colLetter(n: number): string {
100
+ let result = "";
101
+ let value = n;
102
+ while (value > 0) {
103
+ value -= 1;
104
+ result = String.fromCharCode(65 + (value % 26)) + result;
105
+ value = Math.floor(value / 26);
106
+ }
107
+ return result;
108
+ }
109
+
110
+ function flattenCellValue(cell: unknown): unknown {
111
+ if (!Array.isArray(cell)) {
112
+ return cell;
113
+ }
114
+ if (cell.length > 0 && cell.every((segment) => segment && typeof segment === "object" && "text" in (segment as object))) {
115
+ return cell.map((segment) => String((segment as { text?: unknown }).text ?? "")).join("");
116
+ }
117
+ return cell;
118
+ }
119
+
120
+ async function resolveSheetRange(
121
+ client: ReturnType<typeof createToolContext>["toolClient"] extends () => infer T ? T : never,
122
+ token: string,
123
+ range?: string,
124
+ sheetId?: string,
125
+ ) {
126
+ if (range) return range;
127
+ if (sheetId) return sheetId;
128
+ const response = await client.invoke(
129
+ "feishu_sheet.info",
130
+ (sdk, opts) => sdk.sheets.spreadsheetSheet.query({ path: { spreadsheet_token: token } }, opts),
131
+ { as: "user" },
132
+ );
133
+ assertLarkOk(response);
134
+ const firstSheet = (response.data as { sheets?: Array<{ sheet_id?: string }> } | undefined)?.sheets?.[0];
135
+ if (!firstSheet?.sheet_id) {
136
+ throw new Error("Spreadsheet has no worksheets.");
137
+ }
138
+ return firstSheet.sheet_id;
139
+ }
140
+
141
+ export function registerFeishuSheetsTools(api: OpenClawPluginApi) {
142
+ if (!api.config) return;
143
+ const accounts = listEnabledFeishuAccounts(api.config);
144
+ if (accounts.length === 0) return;
145
+ if (!resolveAnyEnabledFeishuToolsConfig(accounts).sheets) return;
146
+
147
+ registerTool(api, {
148
+ name: "feishu_sheet",
149
+ label: "Feishu Sheet",
150
+ description: "按本人身份读取、写入、创建、查找和导出飞书电子表格。",
151
+ parameters: SheetSchema,
152
+ async execute(_toolCallId, params) {
153
+ const payload = params as any;
154
+ try {
155
+ const client = createToolContext(api, "feishu_sheet").toolClient();
156
+
157
+ if (payload.action === "create") {
158
+ const createResponse = await client.invoke(
159
+ "feishu_sheet.create",
160
+ (sdk, opts) =>
161
+ sdk.sheets.spreadsheet.create(
162
+ {
163
+ data: {
164
+ title: payload.title,
165
+ folder_token: payload.folder_token,
166
+ },
167
+ },
168
+ opts,
169
+ ),
170
+ { as: "user" },
171
+ );
172
+ assertLarkOk(createResponse);
173
+ const spreadsheet = (createResponse.data as { spreadsheet?: { spreadsheet_token?: string; title?: string } } | undefined)?.spreadsheet;
174
+ const token = spreadsheet?.spreadsheet_token;
175
+ if (!token) {
176
+ return json({ error: "创建电子表格失败,未返回 spreadsheet_token。" });
177
+ }
178
+ if (payload.headers || payload.data) {
179
+ const sheetsResponse = await client.invoke(
180
+ "feishu_sheet.create",
181
+ (sdk, opts) => sdk.sheets.spreadsheetSheet.query({ path: { spreadsheet_token: token } }, opts),
182
+ { as: "user" },
183
+ );
184
+ assertLarkOk(sheetsResponse);
185
+ const firstSheet = (sheetsResponse.data as { sheets?: Array<{ sheet_id?: string }> } | undefined)?.sheets?.[0];
186
+ const allRows = [
187
+ ...(payload.headers ? [payload.headers] : []),
188
+ ...((payload.data as unknown[][] | undefined) ?? []),
189
+ ];
190
+ if (firstSheet?.sheet_id && allRows.length > 0) {
191
+ const numCols = Math.max(...allRows.map((row) => row.length), 1);
192
+ const range = `${firstSheet.sheet_id}!A1:${colLetter(numCols)}${allRows.length}`;
193
+ await client.invokeByPath("feishu_sheet.create", `/open-apis/sheets/v2/spreadsheets/${token}/values`, {
194
+ method: "PUT",
195
+ body: { valueRange: { range, values: allRows } },
196
+ as: "user",
197
+ });
198
+ }
199
+ }
200
+ return json({
201
+ spreadsheet_token: token,
202
+ title: spreadsheet?.title ?? payload.title,
203
+ url: `${wwwDomain(client.account.domain)}/sheets/${token}`,
204
+ });
205
+ }
206
+
207
+ const tokenInfo = resolveToken(payload);
208
+ if (!tokenInfo?.token) {
209
+ return json({ error: "请传 spreadsheet_token 或 /sheets/TOKEN 形式的 url。" });
210
+ }
211
+
212
+ if (payload.action === "info") {
213
+ const [spreadsheetRes, sheetsRes] = await Promise.all([
214
+ client.invoke(
215
+ "feishu_sheet.info",
216
+ (sdk, opts) => sdk.sheets.spreadsheet.get({ path: { spreadsheet_token: tokenInfo.token } }, opts),
217
+ { as: "user" },
218
+ ),
219
+ client.invoke(
220
+ "feishu_sheet.info",
221
+ (sdk, opts) => sdk.sheets.spreadsheetSheet.query({ path: { spreadsheet_token: tokenInfo.token } }, opts),
222
+ { as: "user" },
223
+ ),
224
+ ]);
225
+ assertLarkOk(spreadsheetRes);
226
+ assertLarkOk(sheetsRes);
227
+ return json({
228
+ title: (spreadsheetRes.data as { spreadsheet?: { title?: string } } | undefined)?.spreadsheet?.title,
229
+ spreadsheet_token: tokenInfo.token,
230
+ url: `${wwwDomain(client.account.domain)}/sheets/${tokenInfo.token}`,
231
+ sheets:
232
+ ((sheetsRes.data as { sheets?: Array<Record<string, unknown>> } | undefined)?.sheets ?? []).map((sheet) => ({
233
+ sheet_id: sheet.sheet_id,
234
+ title: sheet.title,
235
+ index: sheet.index,
236
+ row_count: (sheet.grid_properties as { row_count?: number } | undefined)?.row_count,
237
+ column_count: (sheet.grid_properties as { column_count?: number } | undefined)?.column_count,
238
+ })),
239
+ });
240
+ }
241
+
242
+ if (payload.action === "read") {
243
+ const range = await resolveSheetRange(client, tokenInfo.token, payload.range, payload.sheet_id ?? tokenInfo.sheetId);
244
+ const response = await client.invokeByPath<{
245
+ data?: { valueRange?: { range?: string; values?: unknown[][] } };
246
+ }>("feishu_sheet.read", `/open-apis/sheets/v2/spreadsheets/${tokenInfo.token}/values/${encodeURIComponent(range)}`, {
247
+ method: "GET",
248
+ query: {
249
+ valueRenderOption: payload.value_render_option ?? "ToString",
250
+ dateTimeRenderOption: "FormattedString",
251
+ },
252
+ as: "user",
253
+ });
254
+ const values = (response.data?.valueRange?.values ?? []).map((row) => row.map(flattenCellValue));
255
+ return json({
256
+ range: response.data?.valueRange?.range,
257
+ values: values.slice(0, MAX_READ_ROWS),
258
+ ...(values.length > MAX_READ_ROWS
259
+ ? {
260
+ truncated: true,
261
+ total_rows: values.length,
262
+ hint: `结果超过 ${MAX_READ_ROWS} 行,已截断。请缩小 range 后重试。`,
263
+ }
264
+ : {}),
265
+ });
266
+ }
267
+
268
+ if (payload.action === "write" || payload.action === "append") {
269
+ if (payload.values.length > MAX_WRITE_ROWS) {
270
+ return json({ error: `写入行数超过限制 ${MAX_WRITE_ROWS}` });
271
+ }
272
+ if (payload.values.some((row: unknown[]) => row.length > MAX_WRITE_COLS)) {
273
+ return json({ error: `写入列数超过限制 ${MAX_WRITE_COLS}` });
274
+ }
275
+ const range = await resolveSheetRange(client, tokenInfo.token, payload.range, payload.sheet_id ?? tokenInfo.sheetId);
276
+ const response = await client.invokeByPath<any>(
277
+ payload.action === "write" ? "feishu_sheet.write" : "feishu_sheet.append",
278
+ `/open-apis/sheets/v2/spreadsheets/${tokenInfo.token}/${payload.action === "write" ? "values" : "values_append"}`,
279
+ {
280
+ method: payload.action === "write" ? "PUT" : "POST",
281
+ body: { valueRange: { range, values: payload.values } },
282
+ as: "user",
283
+ },
284
+ );
285
+ const updates = response.data?.updates ?? response.data;
286
+ return json({
287
+ updated_range: updates?.updatedRange,
288
+ updated_rows: updates?.updatedRows,
289
+ updated_columns: updates?.updatedColumns,
290
+ updated_cells: updates?.updatedCells,
291
+ revision: updates?.revision,
292
+ });
293
+ }
294
+
295
+ if (payload.action === "find") {
296
+ const response = await client.invoke(
297
+ "feishu_sheet.find",
298
+ (sdk, opts) =>
299
+ sdk.sheets.spreadsheetSheet.find(
300
+ {
301
+ path: { spreadsheet_token: tokenInfo.token, sheet_id: payload.sheet_id },
302
+ data: {
303
+ find: payload.find,
304
+ find_condition: {
305
+ range: payload.range ? `${payload.sheet_id}!${payload.range}` : payload.sheet_id,
306
+ ...(payload.match_case !== undefined ? { match_case: !payload.match_case } : {}),
307
+ ...(payload.match_entire_cell !== undefined ? { match_entire_cell: payload.match_entire_cell } : {}),
308
+ ...(payload.search_by_regex !== undefined ? { search_by_regex: payload.search_by_regex } : {}),
309
+ ...(payload.include_formulas !== undefined ? { include_formulas: payload.include_formulas } : {}),
310
+ },
311
+ },
312
+ },
313
+ opts,
314
+ ),
315
+ { as: "user" },
316
+ );
317
+ assertLarkOk(response);
318
+ return json({
319
+ matched_cells: (response.data as { find_result?: { matched_cells?: unknown[] } } | undefined)?.find_result?.matched_cells ?? [],
320
+ matched_formula_cells:
321
+ (response.data as { find_result?: { matched_formula_cells?: unknown[] } } | undefined)?.find_result?.matched_formula_cells ?? [],
322
+ });
323
+ }
324
+
325
+ const exportCreate = await client.invoke(
326
+ "feishu_sheet.export",
327
+ (sdk, opts) =>
328
+ sdk.drive.exportTask.create(
329
+ {
330
+ data: {
331
+ file_extension: payload.file_extension,
332
+ token: tokenInfo.token,
333
+ type: "sheet",
334
+ sub_id: payload.sheet_id,
335
+ },
336
+ },
337
+ opts,
338
+ ),
339
+ { as: "user" },
340
+ );
341
+ assertLarkOk(exportCreate);
342
+ const ticket = (exportCreate.data as { ticket?: string } | undefined)?.ticket;
343
+ if (!ticket) {
344
+ return json({ error: "导出任务创建失败,未返回 ticket。" });
345
+ }
346
+ for (let i = 0; i < 30; i += 1) {
347
+ await new Promise((resolve) => setTimeout(resolve, 1000));
348
+ const exportStatus = await client.invoke(
349
+ "feishu_sheet.export",
350
+ (sdk, opts) =>
351
+ sdk.drive.exportTask.get({ path: { ticket }, params: { token: tokenInfo.token } }, opts),
352
+ { as: "user" },
353
+ );
354
+ assertLarkOk(exportStatus);
355
+ const result = (exportStatus.data as { result?: { job_status?: number; file_token?: string; file_name?: string; file_size?: number; job_error_msg?: string } } | undefined)?.result;
356
+ if (result?.job_status === 0) {
357
+ return json({
358
+ file_token: result.file_token,
359
+ file_name: result.file_name,
360
+ file_size: result.file_size,
361
+ file_extension: payload.file_extension,
362
+ });
363
+ }
364
+ if ((result?.job_status ?? 0) >= 3) {
365
+ return json({ error: result?.job_error_msg ?? `导出失败 (status=${result?.job_status})` });
366
+ }
367
+ }
368
+ return json({ error: "导出任务超时,请稍后重试。" });
369
+ } catch (error) {
370
+ return handleInvokeError(error, api);
371
+ }
372
+ },
373
+ }, { name: "feishu_sheet" });
374
+ }