@openclaw/feishu 2026.2.24 → 2026.3.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.
- package/index.ts +2 -0
- package/package.json +2 -1
- package/skills/feishu-doc/SKILL.md +109 -3
- package/src/accounts.test.ts +90 -0
- package/src/accounts.ts +11 -2
- package/src/async.ts +62 -0
- package/src/bitable.ts +189 -215
- package/src/bot.card-action.test.ts +63 -0
- package/src/bot.checkBotMentioned.test.ts +55 -0
- package/src/bot.test.ts +863 -9
- package/src/bot.ts +414 -200
- package/src/card-action.ts +79 -0
- package/src/channel.ts +6 -0
- package/src/chat-schema.ts +24 -0
- package/src/chat.test.ts +89 -0
- package/src/chat.ts +130 -0
- package/src/client.test.ts +107 -0
- package/src/client.ts +13 -0
- package/src/config-schema.test.ts +82 -1
- package/src/config-schema.ts +54 -3
- package/src/doc-schema.ts +141 -0
- package/src/docx-batch-insert.ts +190 -0
- package/src/docx-color-text.ts +149 -0
- package/src/docx-table-ops.ts +298 -0
- package/src/docx.account-selection.test.ts +76 -0
- package/src/docx.test.ts +470 -0
- package/src/docx.ts +996 -72
- package/src/drive.ts +38 -33
- package/src/media.test.ts +123 -6
- package/src/media.ts +31 -10
- package/src/monitor.account.ts +286 -0
- package/src/monitor.reaction.test.ts +235 -0
- package/src/monitor.startup.test.ts +187 -0
- package/src/monitor.startup.ts +51 -0
- package/src/monitor.state.ts +76 -0
- package/src/monitor.transport.ts +163 -0
- package/src/monitor.ts +44 -346
- package/src/monitor.webhook-security.test.ts +27 -1
- package/src/outbound.test.ts +181 -0
- package/src/outbound.ts +94 -7
- package/src/perm.ts +37 -30
- package/src/policy.test.ts +56 -1
- package/src/policy.ts +5 -1
- package/src/post.test.ts +105 -0
- package/src/post.ts +274 -0
- package/src/probe.test.ts +253 -0
- package/src/probe.ts +99 -7
- package/src/reply-dispatcher.test.ts +259 -0
- package/src/reply-dispatcher.ts +139 -45
- package/src/send.reply-fallback.test.ts +105 -0
- package/src/send.test.ts +168 -0
- package/src/send.ts +143 -18
- package/src/streaming-card.ts +131 -43
- package/src/targets.test.ts +26 -1
- package/src/targets.ts +11 -6
- package/src/tool-account-routing.test.ts +129 -0
- package/src/tool-account.ts +70 -0
- package/src/tool-factory-test-harness.ts +76 -0
- package/src/tools-config.test.ts +21 -0
- package/src/tools-config.ts +2 -1
- package/src/types.ts +1 -0
- package/src/typing.test.ts +144 -0
- package/src/typing.ts +140 -10
- package/src/wiki.ts +55 -50
package/src/outbound.ts
CHANGED
|
@@ -1,7 +1,64 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
1
3
|
import type { ChannelOutboundAdapter } from "openclaw/plugin-sdk";
|
|
4
|
+
import { resolveFeishuAccount } from "./accounts.js";
|
|
2
5
|
import { sendMediaFeishu } from "./media.js";
|
|
3
6
|
import { getFeishuRuntime } from "./runtime.js";
|
|
4
|
-
import { sendMessageFeishu } from "./send.js";
|
|
7
|
+
import { sendMarkdownCardFeishu, sendMessageFeishu } from "./send.js";
|
|
8
|
+
|
|
9
|
+
function normalizePossibleLocalImagePath(text: string | undefined): string | null {
|
|
10
|
+
const raw = text?.trim();
|
|
11
|
+
if (!raw) return null;
|
|
12
|
+
|
|
13
|
+
// Only auto-convert when the message is a pure path-like payload.
|
|
14
|
+
// Avoid converting regular sentences that merely contain a path.
|
|
15
|
+
const hasWhitespace = /\s/.test(raw);
|
|
16
|
+
if (hasWhitespace) return null;
|
|
17
|
+
|
|
18
|
+
// Ignore links/data URLs; those should stay in normal mediaUrl/text paths.
|
|
19
|
+
if (/^(https?:\/\/|data:|file:\/\/)/i.test(raw)) return null;
|
|
20
|
+
|
|
21
|
+
const ext = path.extname(raw).toLowerCase();
|
|
22
|
+
const isImageExt = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(
|
|
23
|
+
ext,
|
|
24
|
+
);
|
|
25
|
+
if (!isImageExt) return null;
|
|
26
|
+
|
|
27
|
+
if (!path.isAbsolute(raw)) return null;
|
|
28
|
+
if (!fs.existsSync(raw)) return null;
|
|
29
|
+
|
|
30
|
+
// Fix race condition: wrap statSync in try-catch to handle file deletion
|
|
31
|
+
// between existsSync and statSync
|
|
32
|
+
try {
|
|
33
|
+
if (!fs.statSync(raw).isFile()) return null;
|
|
34
|
+
} catch {
|
|
35
|
+
// File may have been deleted or became inaccessible between checks
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return raw;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function shouldUseCard(text: string): boolean {
|
|
43
|
+
return /```[\s\S]*?```/.test(text) || /\|.+\|[\r\n]+\|[-:| ]+\|/.test(text);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function sendOutboundText(params: {
|
|
47
|
+
cfg: Parameters<typeof sendMessageFeishu>[0]["cfg"];
|
|
48
|
+
to: string;
|
|
49
|
+
text: string;
|
|
50
|
+
accountId?: string;
|
|
51
|
+
}) {
|
|
52
|
+
const { cfg, to, text, accountId } = params;
|
|
53
|
+
const account = resolveFeishuAccount({ cfg, accountId });
|
|
54
|
+
const renderMode = account.config?.renderMode ?? "auto";
|
|
55
|
+
|
|
56
|
+
if (renderMode === "card" || (renderMode === "auto" && shouldUseCard(text))) {
|
|
57
|
+
return sendMarkdownCardFeishu({ cfg, to, text, accountId });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return sendMessageFeishu({ cfg, to, text, accountId });
|
|
61
|
+
}
|
|
5
62
|
|
|
6
63
|
export const feishuOutbound: ChannelOutboundAdapter = {
|
|
7
64
|
deliveryMode: "direct",
|
|
@@ -9,16 +66,45 @@ export const feishuOutbound: ChannelOutboundAdapter = {
|
|
|
9
66
|
chunkerMode: "markdown",
|
|
10
67
|
textChunkLimit: 4000,
|
|
11
68
|
sendText: async ({ cfg, to, text, accountId }) => {
|
|
12
|
-
|
|
69
|
+
// Scheme A compatibility shim:
|
|
70
|
+
// when upstream accidentally returns a local image path as plain text,
|
|
71
|
+
// auto-upload and send as Feishu image message instead of leaking path text.
|
|
72
|
+
const localImagePath = normalizePossibleLocalImagePath(text);
|
|
73
|
+
if (localImagePath) {
|
|
74
|
+
try {
|
|
75
|
+
const result = await sendMediaFeishu({
|
|
76
|
+
cfg,
|
|
77
|
+
to,
|
|
78
|
+
mediaUrl: localImagePath,
|
|
79
|
+
accountId: accountId ?? undefined,
|
|
80
|
+
});
|
|
81
|
+
return { channel: "feishu", ...result };
|
|
82
|
+
} catch (err) {
|
|
83
|
+
console.error(`[feishu] local image path auto-send failed:`, err);
|
|
84
|
+
// fall through to plain text as last resort
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const result = await sendOutboundText({
|
|
89
|
+
cfg,
|
|
90
|
+
to,
|
|
91
|
+
text,
|
|
92
|
+
accountId: accountId ?? undefined,
|
|
93
|
+
});
|
|
13
94
|
return { channel: "feishu", ...result };
|
|
14
95
|
},
|
|
15
|
-
sendMedia: async ({ cfg, to, text, mediaUrl, accountId }) => {
|
|
96
|
+
sendMedia: async ({ cfg, to, text, mediaUrl, accountId, mediaLocalRoots }) => {
|
|
16
97
|
// Send text first if provided
|
|
17
98
|
if (text?.trim()) {
|
|
18
|
-
await
|
|
99
|
+
await sendOutboundText({
|
|
100
|
+
cfg,
|
|
101
|
+
to,
|
|
102
|
+
text,
|
|
103
|
+
accountId: accountId ?? undefined,
|
|
104
|
+
});
|
|
19
105
|
}
|
|
20
106
|
|
|
21
|
-
// Upload and send media if URL provided
|
|
107
|
+
// Upload and send media if URL or local path provided
|
|
22
108
|
if (mediaUrl) {
|
|
23
109
|
try {
|
|
24
110
|
const result = await sendMediaFeishu({
|
|
@@ -26,6 +112,7 @@ export const feishuOutbound: ChannelOutboundAdapter = {
|
|
|
26
112
|
to,
|
|
27
113
|
mediaUrl,
|
|
28
114
|
accountId: accountId ?? undefined,
|
|
115
|
+
mediaLocalRoots,
|
|
29
116
|
});
|
|
30
117
|
return { channel: "feishu", ...result };
|
|
31
118
|
} catch (err) {
|
|
@@ -33,7 +120,7 @@ export const feishuOutbound: ChannelOutboundAdapter = {
|
|
|
33
120
|
console.error(`[feishu] sendMediaFeishu failed:`, err);
|
|
34
121
|
// Fallback to URL link if upload fails
|
|
35
122
|
const fallbackText = `📎 ${mediaUrl}`;
|
|
36
|
-
const result = await
|
|
123
|
+
const result = await sendOutboundText({
|
|
37
124
|
cfg,
|
|
38
125
|
to,
|
|
39
126
|
text: fallbackText,
|
|
@@ -44,7 +131,7 @@ export const feishuOutbound: ChannelOutboundAdapter = {
|
|
|
44
131
|
}
|
|
45
132
|
|
|
46
133
|
// No media URL, just return text result
|
|
47
|
-
const result = await
|
|
134
|
+
const result = await sendOutboundText({
|
|
48
135
|
cfg,
|
|
49
136
|
to,
|
|
50
137
|
text: text ?? "",
|
package/src/perm.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import type * as Lark from "@larksuiteoapi/node-sdk";
|
|
2
2
|
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
|
|
3
3
|
import { listEnabledFeishuAccounts } from "./accounts.js";
|
|
4
|
-
import { createFeishuClient } from "./client.js";
|
|
5
4
|
import { FeishuPermSchema, type FeishuPermParams } from "./perm-schema.js";
|
|
6
|
-
import {
|
|
5
|
+
import { createFeishuToolClient, resolveAnyEnabledFeishuToolsConfig } from "./tool-account.js";
|
|
7
6
|
|
|
8
7
|
// ============ Helpers ============
|
|
9
8
|
|
|
@@ -129,42 +128,50 @@ export function registerFeishuPermTools(api: OpenClawPluginApi) {
|
|
|
129
128
|
return;
|
|
130
129
|
}
|
|
131
130
|
|
|
132
|
-
const
|
|
133
|
-
const toolsCfg = resolveToolsConfig(firstAccount.config.tools);
|
|
131
|
+
const toolsCfg = resolveAnyEnabledFeishuToolsConfig(accounts);
|
|
134
132
|
if (!toolsCfg.perm) {
|
|
135
133
|
api.logger.debug?.("feishu_perm: perm tool disabled in config (default: false)");
|
|
136
134
|
return;
|
|
137
135
|
}
|
|
138
136
|
|
|
139
|
-
|
|
137
|
+
type FeishuPermExecuteParams = FeishuPermParams & { accountId?: string };
|
|
140
138
|
|
|
141
139
|
api.registerTool(
|
|
142
|
-
{
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
140
|
+
(ctx) => {
|
|
141
|
+
const defaultAccountId = ctx.agentAccountId;
|
|
142
|
+
return {
|
|
143
|
+
name: "feishu_perm",
|
|
144
|
+
label: "Feishu Perm",
|
|
145
|
+
description: "Feishu permission management. Actions: list, add, remove",
|
|
146
|
+
parameters: FeishuPermSchema,
|
|
147
|
+
async execute(_toolCallId, params) {
|
|
148
|
+
const p = params as FeishuPermExecuteParams;
|
|
149
|
+
try {
|
|
150
|
+
const client = createFeishuToolClient({
|
|
151
|
+
api,
|
|
152
|
+
executeParams: p,
|
|
153
|
+
defaultAccountId,
|
|
154
|
+
});
|
|
155
|
+
switch (p.action) {
|
|
156
|
+
case "list":
|
|
157
|
+
return json(await listMembers(client, p.token, p.type));
|
|
158
|
+
case "add":
|
|
159
|
+
return json(
|
|
160
|
+
await addMember(client, p.token, p.type, p.member_type, p.member_id, p.perm),
|
|
161
|
+
);
|
|
162
|
+
case "remove":
|
|
163
|
+
return json(
|
|
164
|
+
await removeMember(client, p.token, p.type, p.member_type, p.member_id),
|
|
165
|
+
);
|
|
166
|
+
default:
|
|
167
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- exhaustive check fallback
|
|
168
|
+
return json({ error: `Unknown action: ${(p as any).action}` });
|
|
169
|
+
}
|
|
170
|
+
} catch (err) {
|
|
171
|
+
return json({ error: err instanceof Error ? err.message : String(err) });
|
|
163
172
|
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
},
|
|
173
|
+
},
|
|
174
|
+
};
|
|
168
175
|
},
|
|
169
176
|
{ name: "feishu_perm" },
|
|
170
177
|
);
|
package/src/policy.test.ts
CHANGED
|
@@ -1,7 +1,62 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
isFeishuGroupAllowed,
|
|
4
|
+
resolveFeishuAllowlistMatch,
|
|
5
|
+
resolveFeishuGroupConfig,
|
|
6
|
+
} from "./policy.js";
|
|
7
|
+
import type { FeishuConfig } from "./types.js";
|
|
3
8
|
|
|
4
9
|
describe("feishu policy", () => {
|
|
10
|
+
describe("resolveFeishuGroupConfig", () => {
|
|
11
|
+
it("falls back to wildcard group config when direct match is missing", () => {
|
|
12
|
+
const cfg = {
|
|
13
|
+
groups: {
|
|
14
|
+
"*": { requireMention: false },
|
|
15
|
+
"oc-explicit": { requireMention: true },
|
|
16
|
+
},
|
|
17
|
+
} as unknown as FeishuConfig;
|
|
18
|
+
|
|
19
|
+
const resolved = resolveFeishuGroupConfig({
|
|
20
|
+
cfg,
|
|
21
|
+
groupId: "oc-missing",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
expect(resolved).toEqual({ requireMention: false });
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("prefers exact group config over wildcard", () => {
|
|
28
|
+
const cfg = {
|
|
29
|
+
groups: {
|
|
30
|
+
"*": { requireMention: false },
|
|
31
|
+
"oc-explicit": { requireMention: true },
|
|
32
|
+
},
|
|
33
|
+
} as unknown as FeishuConfig;
|
|
34
|
+
|
|
35
|
+
const resolved = resolveFeishuGroupConfig({
|
|
36
|
+
cfg,
|
|
37
|
+
groupId: "oc-explicit",
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
expect(resolved).toEqual({ requireMention: true });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("keeps case-insensitive matching for explicit group ids", () => {
|
|
44
|
+
const cfg = {
|
|
45
|
+
groups: {
|
|
46
|
+
"*": { requireMention: false },
|
|
47
|
+
OC_UPPER: { requireMention: true },
|
|
48
|
+
},
|
|
49
|
+
} as unknown as FeishuConfig;
|
|
50
|
+
|
|
51
|
+
const resolved = resolveFeishuGroupConfig({
|
|
52
|
+
cfg,
|
|
53
|
+
groupId: "oc_upper",
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
expect(resolved).toEqual({ requireMention: true });
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
5
60
|
describe("resolveFeishuAllowlistMatch", () => {
|
|
6
61
|
it("allows wildcard", () => {
|
|
7
62
|
expect(
|
package/src/policy.ts
CHANGED
|
@@ -56,6 +56,7 @@ export function resolveFeishuGroupConfig(params: {
|
|
|
56
56
|
groupId?: string | null;
|
|
57
57
|
}): FeishuGroupConfig | undefined {
|
|
58
58
|
const groups = params.cfg?.groups ?? {};
|
|
59
|
+
const wildcard = groups["*"];
|
|
59
60
|
const groupId = params.groupId?.trim();
|
|
60
61
|
if (!groupId) {
|
|
61
62
|
return undefined;
|
|
@@ -68,7 +69,10 @@ export function resolveFeishuGroupConfig(params: {
|
|
|
68
69
|
|
|
69
70
|
const lowered = groupId.toLowerCase();
|
|
70
71
|
const matchKey = Object.keys(groups).find((key) => key.toLowerCase() === lowered);
|
|
71
|
-
|
|
72
|
+
if (matchKey) {
|
|
73
|
+
return groups[matchKey];
|
|
74
|
+
}
|
|
75
|
+
return wildcard;
|
|
72
76
|
}
|
|
73
77
|
|
|
74
78
|
export function resolveFeishuGroupToolPolicy(
|
package/src/post.test.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { parsePostContent } from "./post.js";
|
|
3
|
+
|
|
4
|
+
describe("parsePostContent", () => {
|
|
5
|
+
it("renders title and styled text as markdown", () => {
|
|
6
|
+
const content = JSON.stringify({
|
|
7
|
+
title: "Daily *Plan*",
|
|
8
|
+
content: [
|
|
9
|
+
[
|
|
10
|
+
{ tag: "text", text: "Bold", style: { bold: true } },
|
|
11
|
+
{ tag: "text", text: " " },
|
|
12
|
+
{ tag: "text", text: "Italic", style: { italic: true } },
|
|
13
|
+
{ tag: "text", text: " " },
|
|
14
|
+
{ tag: "text", text: "Underline", style: { underline: true } },
|
|
15
|
+
{ tag: "text", text: " " },
|
|
16
|
+
{ tag: "text", text: "Strike", style: { strikethrough: true } },
|
|
17
|
+
{ tag: "text", text: " " },
|
|
18
|
+
{ tag: "text", text: "Code", style: { code: true, bold: true } },
|
|
19
|
+
],
|
|
20
|
+
],
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const result = parsePostContent(content);
|
|
24
|
+
|
|
25
|
+
expect(result.textContent).toBe(
|
|
26
|
+
"Daily \\*Plan\\*\n\n**Bold** *Italic* <u>Underline</u> ~~Strike~~ `Code`",
|
|
27
|
+
);
|
|
28
|
+
expect(result.imageKeys).toEqual([]);
|
|
29
|
+
expect(result.mentionedOpenIds).toEqual([]);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("renders links and mentions", () => {
|
|
33
|
+
const content = JSON.stringify({
|
|
34
|
+
title: "",
|
|
35
|
+
content: [
|
|
36
|
+
[
|
|
37
|
+
{ tag: "a", text: "Docs [v2]", href: "https://example.com/guide(a)" },
|
|
38
|
+
{ tag: "text", text: " " },
|
|
39
|
+
{ tag: "at", user_name: "alice_bob" },
|
|
40
|
+
{ tag: "text", text: " " },
|
|
41
|
+
{ tag: "at", open_id: "ou_123" },
|
|
42
|
+
{ tag: "text", text: " " },
|
|
43
|
+
{ tag: "a", href: "https://example.com/no-text" },
|
|
44
|
+
],
|
|
45
|
+
],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const result = parsePostContent(content);
|
|
49
|
+
|
|
50
|
+
expect(result.textContent).toBe(
|
|
51
|
+
"[Docs \\[v2\\]](https://example.com/guide(a)) @alice\\_bob @ou\\_123 [https://example.com/no\\-text](https://example.com/no-text)",
|
|
52
|
+
);
|
|
53
|
+
expect(result.mentionedOpenIds).toEqual(["ou_123"]);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("inserts image placeholders and collects image keys", () => {
|
|
57
|
+
const content = JSON.stringify({
|
|
58
|
+
title: "",
|
|
59
|
+
content: [
|
|
60
|
+
[
|
|
61
|
+
{ tag: "text", text: "Before " },
|
|
62
|
+
{ tag: "img", image_key: "img_1" },
|
|
63
|
+
{ tag: "text", text: " after" },
|
|
64
|
+
],
|
|
65
|
+
[{ tag: "img", image_key: "img_2" }],
|
|
66
|
+
],
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const result = parsePostContent(content);
|
|
70
|
+
|
|
71
|
+
expect(result.textContent).toBe("Before ![image] after\n![image]");
|
|
72
|
+
expect(result.imageKeys).toEqual(["img_1", "img_2"]);
|
|
73
|
+
expect(result.mentionedOpenIds).toEqual([]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("supports locale wrappers", () => {
|
|
77
|
+
const wrappedByPost = JSON.stringify({
|
|
78
|
+
post: {
|
|
79
|
+
zh_cn: {
|
|
80
|
+
title: "标题",
|
|
81
|
+
content: [[{ tag: "text", text: "内容A" }]],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
const wrappedByLocale = JSON.stringify({
|
|
86
|
+
zh_cn: {
|
|
87
|
+
title: "标题",
|
|
88
|
+
content: [[{ tag: "text", text: "内容B" }]],
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
expect(parsePostContent(wrappedByPost)).toEqual({
|
|
93
|
+
textContent: "标题\n\n内容A",
|
|
94
|
+
imageKeys: [],
|
|
95
|
+
mediaKeys: [],
|
|
96
|
+
mentionedOpenIds: [],
|
|
97
|
+
});
|
|
98
|
+
expect(parsePostContent(wrappedByLocale)).toEqual({
|
|
99
|
+
textContent: "标题\n\n内容B",
|
|
100
|
+
imageKeys: [],
|
|
101
|
+
mediaKeys: [],
|
|
102
|
+
mentionedOpenIds: [],
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
});
|
package/src/post.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { normalizeFeishuExternalKey } from "./external-keys.js";
|
|
2
|
+
|
|
3
|
+
const FALLBACK_POST_TEXT = "[Rich text message]";
|
|
4
|
+
const MARKDOWN_SPECIAL_CHARS = /([\\`*_{}\[\]()#+\-!|>~])/g;
|
|
5
|
+
|
|
6
|
+
type PostParseResult = {
|
|
7
|
+
textContent: string;
|
|
8
|
+
imageKeys: string[];
|
|
9
|
+
mediaKeys: Array<{ fileKey: string; fileName?: string }>;
|
|
10
|
+
mentionedOpenIds: string[];
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
type PostPayload = {
|
|
14
|
+
title: string;
|
|
15
|
+
content: unknown[];
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
19
|
+
return typeof value === "object" && value !== null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function toStringOrEmpty(value: unknown): string {
|
|
23
|
+
return typeof value === "string" ? value : "";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function escapeMarkdownText(text: string): string {
|
|
27
|
+
return text.replace(MARKDOWN_SPECIAL_CHARS, "\\$1");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function toBoolean(value: unknown): boolean {
|
|
31
|
+
return value === true || value === 1 || value === "true";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isStyleEnabled(style: Record<string, unknown> | undefined, key: string): boolean {
|
|
35
|
+
if (!style) {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
return toBoolean(style[key]);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function wrapInlineCode(text: string): string {
|
|
42
|
+
const maxRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
|
|
43
|
+
const fence = "`".repeat(maxRun + 1);
|
|
44
|
+
const needsPadding = text.startsWith("`") || text.endsWith("`");
|
|
45
|
+
const body = needsPadding ? ` ${text} ` : text;
|
|
46
|
+
return `${fence}${body}${fence}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sanitizeFenceLanguage(language: string): string {
|
|
50
|
+
return language.trim().replace(/[^A-Za-z0-9_+#.-]/g, "");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function renderTextElement(element: Record<string, unknown>): string {
|
|
54
|
+
const text = toStringOrEmpty(element.text);
|
|
55
|
+
const style = isRecord(element.style) ? element.style : undefined;
|
|
56
|
+
|
|
57
|
+
if (isStyleEnabled(style, "code")) {
|
|
58
|
+
return wrapInlineCode(text);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let rendered = escapeMarkdownText(text);
|
|
62
|
+
if (!rendered) {
|
|
63
|
+
return "";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (isStyleEnabled(style, "bold")) {
|
|
67
|
+
rendered = `**${rendered}**`;
|
|
68
|
+
}
|
|
69
|
+
if (isStyleEnabled(style, "italic")) {
|
|
70
|
+
rendered = `*${rendered}*`;
|
|
71
|
+
}
|
|
72
|
+
if (isStyleEnabled(style, "underline")) {
|
|
73
|
+
rendered = `<u>${rendered}</u>`;
|
|
74
|
+
}
|
|
75
|
+
if (
|
|
76
|
+
isStyleEnabled(style, "strikethrough") ||
|
|
77
|
+
isStyleEnabled(style, "line_through") ||
|
|
78
|
+
isStyleEnabled(style, "lineThrough")
|
|
79
|
+
) {
|
|
80
|
+
rendered = `~~${rendered}~~`;
|
|
81
|
+
}
|
|
82
|
+
return rendered;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function renderLinkElement(element: Record<string, unknown>): string {
|
|
86
|
+
const href = toStringOrEmpty(element.href).trim();
|
|
87
|
+
const rawText = toStringOrEmpty(element.text);
|
|
88
|
+
const text = rawText || href;
|
|
89
|
+
if (!text) {
|
|
90
|
+
return "";
|
|
91
|
+
}
|
|
92
|
+
if (!href) {
|
|
93
|
+
return escapeMarkdownText(text);
|
|
94
|
+
}
|
|
95
|
+
return `[${escapeMarkdownText(text)}](${href})`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function renderMentionElement(element: Record<string, unknown>): string {
|
|
99
|
+
const mention =
|
|
100
|
+
toStringOrEmpty(element.user_name) ||
|
|
101
|
+
toStringOrEmpty(element.user_id) ||
|
|
102
|
+
toStringOrEmpty(element.open_id);
|
|
103
|
+
if (!mention) {
|
|
104
|
+
return "";
|
|
105
|
+
}
|
|
106
|
+
return `@${escapeMarkdownText(mention)}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function renderEmotionElement(element: Record<string, unknown>): string {
|
|
110
|
+
const text =
|
|
111
|
+
toStringOrEmpty(element.emoji) ||
|
|
112
|
+
toStringOrEmpty(element.text) ||
|
|
113
|
+
toStringOrEmpty(element.emoji_type);
|
|
114
|
+
return escapeMarkdownText(text);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function renderCodeBlockElement(element: Record<string, unknown>): string {
|
|
118
|
+
const language = sanitizeFenceLanguage(
|
|
119
|
+
toStringOrEmpty(element.language) || toStringOrEmpty(element.lang),
|
|
120
|
+
);
|
|
121
|
+
const code = (toStringOrEmpty(element.text) || toStringOrEmpty(element.content)).replace(
|
|
122
|
+
/\r\n/g,
|
|
123
|
+
"\n",
|
|
124
|
+
);
|
|
125
|
+
const trailingNewline = code.endsWith("\n") ? "" : "\n";
|
|
126
|
+
return `\`\`\`${language}\n${code}${trailingNewline}\`\`\``;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function renderElement(
|
|
130
|
+
element: unknown,
|
|
131
|
+
imageKeys: string[],
|
|
132
|
+
mediaKeys: Array<{ fileKey: string; fileName?: string }>,
|
|
133
|
+
mentionedOpenIds: string[],
|
|
134
|
+
): string {
|
|
135
|
+
if (!isRecord(element)) {
|
|
136
|
+
return escapeMarkdownText(toStringOrEmpty(element));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const tag = toStringOrEmpty(element.tag).toLowerCase();
|
|
140
|
+
switch (tag) {
|
|
141
|
+
case "text":
|
|
142
|
+
return renderTextElement(element);
|
|
143
|
+
case "a":
|
|
144
|
+
return renderLinkElement(element);
|
|
145
|
+
case "at":
|
|
146
|
+
{
|
|
147
|
+
const mentioned = toStringOrEmpty(element.open_id) || toStringOrEmpty(element.user_id);
|
|
148
|
+
const normalizedMention = normalizeFeishuExternalKey(mentioned);
|
|
149
|
+
if (normalizedMention) {
|
|
150
|
+
mentionedOpenIds.push(normalizedMention);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return renderMentionElement(element);
|
|
154
|
+
case "img": {
|
|
155
|
+
const imageKey = normalizeFeishuExternalKey(toStringOrEmpty(element.image_key));
|
|
156
|
+
if (imageKey) {
|
|
157
|
+
imageKeys.push(imageKey);
|
|
158
|
+
}
|
|
159
|
+
return "![image]";
|
|
160
|
+
}
|
|
161
|
+
case "media": {
|
|
162
|
+
const fileKey = normalizeFeishuExternalKey(toStringOrEmpty(element.file_key));
|
|
163
|
+
if (fileKey) {
|
|
164
|
+
const fileName = toStringOrEmpty(element.file_name) || undefined;
|
|
165
|
+
mediaKeys.push({ fileKey, fileName });
|
|
166
|
+
}
|
|
167
|
+
return "[media]";
|
|
168
|
+
}
|
|
169
|
+
case "emotion":
|
|
170
|
+
return renderEmotionElement(element);
|
|
171
|
+
case "br":
|
|
172
|
+
return "\n";
|
|
173
|
+
case "hr":
|
|
174
|
+
return "\n\n---\n\n";
|
|
175
|
+
case "code": {
|
|
176
|
+
const code = toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
177
|
+
return code ? wrapInlineCode(code) : "";
|
|
178
|
+
}
|
|
179
|
+
case "code_block":
|
|
180
|
+
case "pre":
|
|
181
|
+
return renderCodeBlockElement(element);
|
|
182
|
+
default:
|
|
183
|
+
return escapeMarkdownText(toStringOrEmpty(element.text));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function toPostPayload(candidate: unknown): PostPayload | null {
|
|
188
|
+
if (!isRecord(candidate) || !Array.isArray(candidate.content)) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
title: toStringOrEmpty(candidate.title),
|
|
193
|
+
content: candidate.content,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function resolveLocalePayload(candidate: unknown): PostPayload | null {
|
|
198
|
+
const direct = toPostPayload(candidate);
|
|
199
|
+
if (direct) {
|
|
200
|
+
return direct;
|
|
201
|
+
}
|
|
202
|
+
if (!isRecord(candidate)) {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
for (const value of Object.values(candidate)) {
|
|
206
|
+
const localePayload = toPostPayload(value);
|
|
207
|
+
if (localePayload) {
|
|
208
|
+
return localePayload;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function resolvePostPayload(parsed: unknown): PostPayload | null {
|
|
215
|
+
const direct = toPostPayload(parsed);
|
|
216
|
+
if (direct) {
|
|
217
|
+
return direct;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (!isRecord(parsed)) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const wrappedPost = resolveLocalePayload(parsed.post);
|
|
225
|
+
if (wrappedPost) {
|
|
226
|
+
return wrappedPost;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return resolveLocalePayload(parsed);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function parsePostContent(content: string): PostParseResult {
|
|
233
|
+
try {
|
|
234
|
+
const parsed = JSON.parse(content);
|
|
235
|
+
const payload = resolvePostPayload(parsed);
|
|
236
|
+
if (!payload) {
|
|
237
|
+
return {
|
|
238
|
+
textContent: FALLBACK_POST_TEXT,
|
|
239
|
+
imageKeys: [],
|
|
240
|
+
mediaKeys: [],
|
|
241
|
+
mentionedOpenIds: [],
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const imageKeys: string[] = [];
|
|
246
|
+
const mediaKeys: Array<{ fileKey: string; fileName?: string }> = [];
|
|
247
|
+
const mentionedOpenIds: string[] = [];
|
|
248
|
+
const paragraphs: string[] = [];
|
|
249
|
+
|
|
250
|
+
for (const paragraph of payload.content) {
|
|
251
|
+
if (!Array.isArray(paragraph)) {
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
let renderedParagraph = "";
|
|
255
|
+
for (const element of paragraph) {
|
|
256
|
+
renderedParagraph += renderElement(element, imageKeys, mediaKeys, mentionedOpenIds);
|
|
257
|
+
}
|
|
258
|
+
paragraphs.push(renderedParagraph);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const title = escapeMarkdownText(payload.title.trim());
|
|
262
|
+
const body = paragraphs.join("\n").trim();
|
|
263
|
+
const textContent = [title, body].filter(Boolean).join("\n\n").trim();
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
textContent: textContent || FALLBACK_POST_TEXT,
|
|
267
|
+
imageKeys,
|
|
268
|
+
mediaKeys,
|
|
269
|
+
mentionedOpenIds,
|
|
270
|
+
};
|
|
271
|
+
} catch {
|
|
272
|
+
return { textContent: FALLBACK_POST_TEXT, imageKeys: [], mediaKeys: [], mentionedOpenIds: [] };
|
|
273
|
+
}
|
|
274
|
+
}
|