@alexsun-top/opencode-chat-room 0.8.0 → 0.8.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/CHANGELOG.md +29 -0
- package/LICENSE +2 -2
- package/README.md +38 -6
- package/README.zh-CN.md +38 -6
- package/cli.ts +27 -1
- package/dist/cli.js +5074 -3212
- package/package.json +23 -3
- package/packages/chat-room-channeld/README.md +98 -25
- package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
- package/packages/chat-room-channeld/src/adapter.ts +36 -2
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
- package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
- package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
- package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +120 -2
- package/packages/chat-room-channeld/src/inbound.ts +26 -0
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +15 -9
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +184 -35
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +498 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown.js +22 -8
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/panels.js +36 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +15 -3
- package/server/assets/chat/reminders.js +69 -8
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/side-pane.js +1 -2
- package/server/assets/chat/state.js +93 -10
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +55 -32
- package/server/assets/conversation.css +123 -23
- package/server/assets/doc-preview.css +35 -3
- package/server/assets/files.css +5 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1297 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +50 -11
- package/server/assets/settings.css +73 -1
- package/server/assets/tasks.css +57 -7
- package/server/channel-integration.ts +519 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +261 -18
- package/server/chat-server.ts +32 -580
- package/server/chat.html +187 -21
- package/server/http-server.ts +3 -182
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +4 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +2 -10
- package/src/config/file-config.ts +7 -54
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/watch.ts +1 -1
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +148 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +121 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +87 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +33 -0
- package/src/state/sqlite-state.ts +15 -897
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +439 -0
- package/src/web/integration-rules.ts +22 -0
- package/src/web/integration-schema.ts +228 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { IngestEvent, MessageRef } from "./protocol.ts";
|
|
2
|
+
|
|
3
|
+
export interface InboundOptions {
|
|
4
|
+
accountId: string;
|
|
5
|
+
appId: string;
|
|
6
|
+
/** Group chat ids explicitly allowed by the operator. */
|
|
7
|
+
chats: ReadonlySet<string>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface ParsedInbound {
|
|
11
|
+
event?: IngestEvent;
|
|
12
|
+
ignored?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function stringValue(value: unknown): string | undefined {
|
|
20
|
+
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function replaceMentions(text: string, mentions: unknown): string {
|
|
24
|
+
if (!Array.isArray(mentions)) return text;
|
|
25
|
+
let next = text;
|
|
26
|
+
for (const item of mentions) {
|
|
27
|
+
if (!isRecord(item)) continue;
|
|
28
|
+
const key = stringValue(item.key);
|
|
29
|
+
const name = stringValue(item.name);
|
|
30
|
+
if (key && name) next = next.split(key).join(`@${name}`);
|
|
31
|
+
}
|
|
32
|
+
return next;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function richText(value: unknown): string | undefined {
|
|
36
|
+
if (!Array.isArray(value)) return undefined;
|
|
37
|
+
const parts: string[] = [];
|
|
38
|
+
for (const line of value) {
|
|
39
|
+
if (!Array.isArray(line)) continue;
|
|
40
|
+
for (const item of line) {
|
|
41
|
+
if (!isRecord(item)) continue;
|
|
42
|
+
if (item.tag === "at") {
|
|
43
|
+
const name = stringValue(item.user_name) ?? stringValue(item.user_id);
|
|
44
|
+
if (name) parts.push(`@${name}`);
|
|
45
|
+
} else {
|
|
46
|
+
const text = stringValue(item.text);
|
|
47
|
+
if (text) parts.push(text);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
parts.push("\n");
|
|
51
|
+
}
|
|
52
|
+
return parts.join("").trim() || undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function messageText(messageType: string, raw: string, mentions: unknown): string | undefined {
|
|
56
|
+
let parsed: unknown;
|
|
57
|
+
try {
|
|
58
|
+
parsed = JSON.parse(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
if (!isRecord(parsed)) return undefined;
|
|
63
|
+
if (messageType === "text") {
|
|
64
|
+
const text = stringValue(parsed.text);
|
|
65
|
+
return text ? replaceMentions(text, mentions) : undefined;
|
|
66
|
+
}
|
|
67
|
+
if (messageType === "post") {
|
|
68
|
+
const post = isRecord(parsed.content)
|
|
69
|
+
? Object.values(parsed.content).find((item) => Array.isArray(item))
|
|
70
|
+
: parsed.content;
|
|
71
|
+
return richText(post);
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function occurredAt(value: unknown): string | undefined {
|
|
77
|
+
const text = stringValue(value);
|
|
78
|
+
if (!text || !/^\d{10,16}$/.test(text)) return undefined;
|
|
79
|
+
const ms = Number(text);
|
|
80
|
+
const stamp = text.length <= 11 ? ms * 1000 : ms;
|
|
81
|
+
const date = new Date(stamp);
|
|
82
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Map one Feishu `im.message.receive_v1` payload to a Channel D ingest event.
|
|
87
|
+
* Only allowlisted group text/post messages from human senders are relayed.
|
|
88
|
+
*/
|
|
89
|
+
export function parseInboundEvent(payload: string, options: InboundOptions): ParsedInbound {
|
|
90
|
+
let root: unknown;
|
|
91
|
+
try {
|
|
92
|
+
root = JSON.parse(payload);
|
|
93
|
+
} catch {
|
|
94
|
+
return { ignored: "malformed event JSON" };
|
|
95
|
+
}
|
|
96
|
+
if (!isRecord(root)) return { ignored: "malformed event JSON" };
|
|
97
|
+
const header = isRecord(root.header) ? root.header : undefined;
|
|
98
|
+
if (!header) return { ignored: "missing event header" };
|
|
99
|
+
if (header.event_type !== "im.message.receive_v1") return { ignored: "unsubscribed event type" };
|
|
100
|
+
if (stringValue(header.app_id) !== options.appId) return { ignored: "event app mismatch" };
|
|
101
|
+
|
|
102
|
+
const body = isRecord(root.event) ? root.event : undefined;
|
|
103
|
+
const message = body && isRecord(body.message) ? body.message : undefined;
|
|
104
|
+
const sender = body && isRecord(body.sender) ? body.sender : undefined;
|
|
105
|
+
if (!body || !message || !sender) return { ignored: "malformed message event" };
|
|
106
|
+
|
|
107
|
+
const chatType = stringValue(message.chat_type);
|
|
108
|
+
if (chatType !== "group" && chatType !== "topic_group") return { ignored: "not a group message" };
|
|
109
|
+
const chatId = stringValue(message.chat_id);
|
|
110
|
+
const messageId = stringValue(message.message_id);
|
|
111
|
+
const messageType = stringValue(message.message_type);
|
|
112
|
+
if (!chatId || !messageId || !messageType) return { ignored: "message identity is incomplete" };
|
|
113
|
+
if (!options.chats.has(chatId)) return { ignored: "chat is not in FEISHU_INBOUND_CHATS" };
|
|
114
|
+
|
|
115
|
+
const senderType = stringValue(sender.sender_type);
|
|
116
|
+
if (senderType !== "user") return { ignored: "bot or unknown sender" };
|
|
117
|
+
const senderIds = isRecord(sender.sender_id) ? sender.sender_id : {};
|
|
118
|
+
if (stringValue(senderIds.app_id)) return { ignored: "bot sender" };
|
|
119
|
+
const nativeUserId = stringValue(senderIds.open_id)
|
|
120
|
+
?? stringValue(senderIds.user_id)
|
|
121
|
+
?? stringValue(senderIds.union_id);
|
|
122
|
+
if (!nativeUserId) return { ignored: "sender identity is unavailable" };
|
|
123
|
+
|
|
124
|
+
const text = messageText(messageType, stringValue(message.content) ?? "", message.mentions);
|
|
125
|
+
if (!text) return { ignored: `unsupported or empty ${messageType} message` };
|
|
126
|
+
|
|
127
|
+
const source = { platform: "feishu", accountId: options.accountId, roomId: chatId };
|
|
128
|
+
const parentId = stringValue(message.parent_id) ?? stringValue(message.root_id);
|
|
129
|
+
const parent: MessageRef | undefined = parentId
|
|
130
|
+
? { endpoint: source, nativeMessageId: parentId }
|
|
131
|
+
: undefined;
|
|
132
|
+
const eventRef: MessageRef = { endpoint: source, nativeMessageId: messageId, text };
|
|
133
|
+
const providerEventId = stringValue(header.event_id) ?? messageId;
|
|
134
|
+
const eventId = `feishu-${options.accountId}-${providerEventId}`;
|
|
135
|
+
const createTime = occurredAt(message.create_time);
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
event: {
|
|
139
|
+
schemaVersion: 1,
|
|
140
|
+
eventId,
|
|
141
|
+
kind: "message.created",
|
|
142
|
+
source,
|
|
143
|
+
actor: {
|
|
144
|
+
platform: "feishu",
|
|
145
|
+
identityNamespace: stringValue(senderIds.open_id) ? "open_id" : "user_id",
|
|
146
|
+
nativeUserId,
|
|
147
|
+
},
|
|
148
|
+
providerEventId,
|
|
149
|
+
// Feishu event ids are stable across retries; fall back to the message id.
|
|
150
|
+
sourceDedupKey: `feishu:${options.accountId}:${providerEventId}`,
|
|
151
|
+
message: eventRef,
|
|
152
|
+
...(parent ? { parent } : {}),
|
|
153
|
+
...(createTime ? { occurredAt: createTime } : {}),
|
|
154
|
+
receivedAt: new Date().toISOString(),
|
|
155
|
+
content: { text },
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { decodeFrame, encodeFrame, headerValue, jsonPayload, type WsFrame } from "./feishu-ws-frames.ts";
|
|
2
|
+
|
|
3
|
+
const DEFAULT_PING_MS = 120_000;
|
|
4
|
+
const DEFAULT_RECONNECT_MS = 120_000;
|
|
5
|
+
const DEFAULT_NONCE_MS = 30_000;
|
|
6
|
+
const FRAGMENT_TTL_MS = 10_000;
|
|
7
|
+
const CONNECT_TIMEOUT_MS = 10_000;
|
|
8
|
+
|
|
9
|
+
export interface LiveSocket {
|
|
10
|
+
binaryType: string;
|
|
11
|
+
readyState: number;
|
|
12
|
+
send(data: Uint8Array): void;
|
|
13
|
+
close(): void;
|
|
14
|
+
addEventListener(type: string, listener: (event: any) => void): void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type SocketCtor = new (url: string) => LiveSocket;
|
|
18
|
+
|
|
19
|
+
interface Discovered {
|
|
20
|
+
url: string;
|
|
21
|
+
serviceId: number;
|
|
22
|
+
pingMs: number;
|
|
23
|
+
reconnectMs: number;
|
|
24
|
+
reconnectNonceMs: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface Fragment {
|
|
28
|
+
parts: Array<Uint8Array | undefined>;
|
|
29
|
+
received: number;
|
|
30
|
+
timer: ReturnType<typeof setTimeout>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface LiveConnectionOptions {
|
|
34
|
+
appId: string;
|
|
35
|
+
appSecret: string;
|
|
36
|
+
baseUrl: string;
|
|
37
|
+
timeoutMs: number;
|
|
38
|
+
/** Test seam: defaults to the platform WebSocket constructor. */
|
|
39
|
+
socketFactory?: (url: string) => LiveSocket;
|
|
40
|
+
/** Complete JSON event payloads; return false to make Feishu retry. */
|
|
41
|
+
onEvent(payload: string): Promise<boolean>;
|
|
42
|
+
log(message: string): void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
46
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function discovery(options: LiveConnectionOptions): Promise<Discovered> {
|
|
50
|
+
const controller = new AbortController();
|
|
51
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs);
|
|
52
|
+
let raw: { status: number; body: unknown };
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetch(`${options.baseUrl}/callback/ws/endpoint`, {
|
|
55
|
+
method: "POST",
|
|
56
|
+
headers: { "Content-Type": "application/json; charset=utf-8", locale: "zh" },
|
|
57
|
+
body: JSON.stringify({ AppID: options.appId, AppSecret: options.appSecret }),
|
|
58
|
+
signal: controller.signal,
|
|
59
|
+
});
|
|
60
|
+
const text = await response.text();
|
|
61
|
+
let body: unknown;
|
|
62
|
+
try {
|
|
63
|
+
body = JSON.parse(text);
|
|
64
|
+
} catch {
|
|
65
|
+
body = undefined;
|
|
66
|
+
}
|
|
67
|
+
raw = { status: response.status, body };
|
|
68
|
+
} catch (error) {
|
|
69
|
+
const code = (error as { cause?: { code?: unknown } } | null)?.cause?.code;
|
|
70
|
+
const detail = typeof code === "string" ? ` (${code})` : "";
|
|
71
|
+
throw new Error(`feishu long connection discovery failed${detail}`);
|
|
72
|
+
} finally {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
}
|
|
75
|
+
if (!isRecord(raw.body) || typeof raw.body.code !== "number") {
|
|
76
|
+
throw new Error(`feishu long connection discovery failed: http ${raw.status}`);
|
|
77
|
+
}
|
|
78
|
+
if (raw.body.code !== 0) {
|
|
79
|
+
const msg = typeof raw.body.msg === "string" && raw.body.msg ? `: ${raw.body.msg}` : "";
|
|
80
|
+
throw new Error(`feishu long connection unavailable: code ${raw.body.code}${msg}`);
|
|
81
|
+
}
|
|
82
|
+
const data = isRecord(raw.body.data) ? raw.body.data : undefined;
|
|
83
|
+
const url = data && typeof data.URL === "string" ? data.URL : "";
|
|
84
|
+
if (!url.startsWith("ws://") && !url.startsWith("wss://")) {
|
|
85
|
+
throw new Error("feishu long connection discovery returned no WebSocket URL");
|
|
86
|
+
}
|
|
87
|
+
const parsed = new URL(url);
|
|
88
|
+
const serviceId = Number(parsed.searchParams.get("service_id"));
|
|
89
|
+
if (!Number.isInteger(serviceId)) {
|
|
90
|
+
throw new Error("feishu long connection URL is missing service_id");
|
|
91
|
+
}
|
|
92
|
+
const config = data && isRecord(data.ClientConfig) ? data.ClientConfig : {};
|
|
93
|
+
const seconds = (value: unknown, fallback: number): number =>
|
|
94
|
+
typeof value === "number" && Number.isFinite(value) && value > 0 ? value * 1000 : fallback;
|
|
95
|
+
return {
|
|
96
|
+
url,
|
|
97
|
+
serviceId,
|
|
98
|
+
pingMs: seconds(config.PingInterval, DEFAULT_PING_MS),
|
|
99
|
+
reconnectMs: seconds(config.ReconnectInterval, DEFAULT_RECONNECT_MS),
|
|
100
|
+
reconnectNonceMs: seconds(config.ReconnectNonce, DEFAULT_NONCE_MS),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Feishu event long connection: endpoint discovery, pbbp2 frames, ping/pong,
|
|
106
|
+
* fragment reassembly, acknowledgement after the host commits, and reconnect.
|
|
107
|
+
*/
|
|
108
|
+
export class FeishuLiveConnection {
|
|
109
|
+
readonly #options: LiveConnectionOptions;
|
|
110
|
+
readonly #fragments = new Map<string, Fragment>();
|
|
111
|
+
#socket?: LiveSocket;
|
|
112
|
+
#discovered?: Discovered;
|
|
113
|
+
#pingTimer?: ReturnType<typeof setTimeout>;
|
|
114
|
+
#reconnectTimer?: ReturnType<typeof setTimeout>;
|
|
115
|
+
#stopped = false;
|
|
116
|
+
#connecting = false;
|
|
117
|
+
#attempts = 0;
|
|
118
|
+
|
|
119
|
+
constructor(options: LiveConnectionOptions) {
|
|
120
|
+
this.#options = options;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async start(): Promise<void> {
|
|
124
|
+
this.#stopped = false;
|
|
125
|
+
this.#discovered = await discovery(this.#options);
|
|
126
|
+
await this.#connect();
|
|
127
|
+
this.#options.log(`inbound long connection ready service=${this.#discovered.serviceId}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async stop(): Promise<void> {
|
|
131
|
+
this.#stopped = true;
|
|
132
|
+
if (this.#pingTimer) clearTimeout(this.#pingTimer);
|
|
133
|
+
if (this.#reconnectTimer) clearTimeout(this.#reconnectTimer);
|
|
134
|
+
this.#pingTimer = undefined;
|
|
135
|
+
this.#reconnectTimer = undefined;
|
|
136
|
+
for (const fragment of this.#fragments.values()) clearTimeout(fragment.timer);
|
|
137
|
+
this.#fragments.clear();
|
|
138
|
+
const socket = this.#socket;
|
|
139
|
+
this.#socket = undefined;
|
|
140
|
+
if (socket) {
|
|
141
|
+
try {
|
|
142
|
+
socket.close();
|
|
143
|
+
} catch {
|
|
144
|
+
// Socket may already be closed.
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
#connect(): Promise<void> {
|
|
150
|
+
const factory = this.#options.socketFactory;
|
|
151
|
+
const Ctor = factory
|
|
152
|
+
? undefined
|
|
153
|
+
: (globalThis as { WebSocket?: SocketCtor }).WebSocket;
|
|
154
|
+
if (!factory && !Ctor) {
|
|
155
|
+
return Promise.reject(new Error("feishu long connection requires a WebSocket client"));
|
|
156
|
+
}
|
|
157
|
+
const discovered = this.#discovered;
|
|
158
|
+
if (!discovered) return Promise.reject(new Error("feishu long connection is not discovered"));
|
|
159
|
+
const create = factory ?? ((url: string) => new Ctor!(url));
|
|
160
|
+
return new Promise((resolve, reject) => {
|
|
161
|
+
const socket = create(discovered.url);
|
|
162
|
+
socket.binaryType = "arraybuffer";
|
|
163
|
+
let settled = false;
|
|
164
|
+
const timer = setTimeout(() => {
|
|
165
|
+
if (settled) return;
|
|
166
|
+
settled = true;
|
|
167
|
+
try {
|
|
168
|
+
socket.close();
|
|
169
|
+
} catch {
|
|
170
|
+
// Ignore close failures on a dead handshake.
|
|
171
|
+
}
|
|
172
|
+
reject(new Error("feishu long connection timed out"));
|
|
173
|
+
}, CONNECT_TIMEOUT_MS);
|
|
174
|
+
socket.addEventListener("open", () => {
|
|
175
|
+
if (settled) return;
|
|
176
|
+
settled = true;
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
if (this.#stopped) {
|
|
179
|
+
try {
|
|
180
|
+
socket.close();
|
|
181
|
+
} catch {
|
|
182
|
+
// Ignore close failures after stop.
|
|
183
|
+
}
|
|
184
|
+
reject(new Error("feishu long connection stopped"));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
this.#attempts = 0;
|
|
188
|
+
this.#socket = socket;
|
|
189
|
+
this.#attach(socket);
|
|
190
|
+
this.#ping();
|
|
191
|
+
resolve();
|
|
192
|
+
});
|
|
193
|
+
socket.addEventListener("error", () => {
|
|
194
|
+
if (settled) return;
|
|
195
|
+
settled = true;
|
|
196
|
+
clearTimeout(timer);
|
|
197
|
+
reject(new Error("feishu long connection failed"));
|
|
198
|
+
});
|
|
199
|
+
socket.addEventListener("close", () => {
|
|
200
|
+
if (settled) return;
|
|
201
|
+
settled = true;
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
reject(new Error("feishu long connection closed during handshake"));
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
#attach(socket: LiveSocket): void {
|
|
209
|
+
socket.addEventListener("message", (event: { data?: unknown }) => {
|
|
210
|
+
void this.#onSocketMessage(event.data).catch((error: unknown) => {
|
|
211
|
+
this.#options.log(`inbound frame failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
socket.addEventListener("error", () => {
|
|
215
|
+
this.#options.log("inbound socket error");
|
|
216
|
+
});
|
|
217
|
+
socket.addEventListener("close", () => {
|
|
218
|
+
// A late close from a socket replaced by a reconnect must not clear the
|
|
219
|
+
// current connection's ping timer or schedule a duplicate reconnect.
|
|
220
|
+
if (this.#socket !== socket) return;
|
|
221
|
+
this.#socket = undefined;
|
|
222
|
+
if (this.#pingTimer) clearTimeout(this.#pingTimer);
|
|
223
|
+
this.#pingTimer = undefined;
|
|
224
|
+
this.#scheduleReconnect();
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async #onSocketMessage(data: unknown): Promise<void> {
|
|
229
|
+
let bytes: Uint8Array;
|
|
230
|
+
if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
|
|
231
|
+
else if (ArrayBuffer.isView(data)) bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
232
|
+
else if (typeof Blob !== "undefined" && data instanceof Blob) bytes = new Uint8Array(await data.arrayBuffer());
|
|
233
|
+
else return;
|
|
234
|
+
|
|
235
|
+
const frame = decodeFrame(bytes);
|
|
236
|
+
if (frame.method === 0) {
|
|
237
|
+
this.#onControl(frame);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (frame.method !== 1) return;
|
|
241
|
+
const type = headerValue(frame, "type");
|
|
242
|
+
if (type !== "event") return;
|
|
243
|
+
const payload = this.#assemble(frame);
|
|
244
|
+
if (!payload) return;
|
|
245
|
+
const text = new TextDecoder().decode(payload);
|
|
246
|
+
let ok = false;
|
|
247
|
+
try {
|
|
248
|
+
ok = await this.#options.onEvent(text);
|
|
249
|
+
} catch {
|
|
250
|
+
ok = false;
|
|
251
|
+
}
|
|
252
|
+
this.#ack(frame, ok ? 200 : 500);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#onControl(frame: WsFrame): void {
|
|
256
|
+
if (headerValue(frame, "type") !== "pong" || !frame.payload) return;
|
|
257
|
+
try {
|
|
258
|
+
const pong = JSON.parse(new TextDecoder().decode(frame.payload)) as Record<string, unknown>;
|
|
259
|
+
const next = this.#discovered;
|
|
260
|
+
if (!next) return;
|
|
261
|
+
if (typeof pong.PingInterval === "number" && pong.PingInterval > 0) next.pingMs = pong.PingInterval * 1000;
|
|
262
|
+
if (typeof pong.ReconnectInterval === "number" && pong.ReconnectInterval > 0) {
|
|
263
|
+
next.reconnectMs = pong.ReconnectInterval * 1000;
|
|
264
|
+
}
|
|
265
|
+
if (typeof pong.ReconnectNonce === "number" && pong.ReconnectNonce > 0) {
|
|
266
|
+
next.reconnectNonceMs = pong.ReconnectNonce * 1000;
|
|
267
|
+
}
|
|
268
|
+
} catch {
|
|
269
|
+
// A malformed pong only means the old intervals stay in effect.
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
#assemble(frame: WsFrame): Uint8Array | undefined {
|
|
274
|
+
const id = headerValue(frame, "message_id");
|
|
275
|
+
const total = Number(headerValue(frame, "sum") ?? "1");
|
|
276
|
+
const seq = Number(headerValue(frame, "seq") ?? "0");
|
|
277
|
+
if (!id || !frame.payload || !Number.isInteger(total) || total <= 1) return frame.payload;
|
|
278
|
+
if (!Number.isInteger(seq) || seq < 0 || seq >= total) return undefined;
|
|
279
|
+
const current = this.#fragments.get(id) ?? {
|
|
280
|
+
parts: Array.from({ length: total }),
|
|
281
|
+
received: 0,
|
|
282
|
+
timer: setTimeout(() => this.#fragments.delete(id), FRAGMENT_TTL_MS),
|
|
283
|
+
};
|
|
284
|
+
if (current.parts.length !== total) return undefined;
|
|
285
|
+
if (!current.parts[seq]) {
|
|
286
|
+
current.parts[seq] = frame.payload;
|
|
287
|
+
current.received += 1;
|
|
288
|
+
}
|
|
289
|
+
this.#fragments.set(id, current);
|
|
290
|
+
if (current.received < total) return undefined;
|
|
291
|
+
clearTimeout(current.timer);
|
|
292
|
+
this.#fragments.delete(id);
|
|
293
|
+
return Uint8Array.from(current.parts.flatMap((part) => [...(part ?? [])]));
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
#ack(frame: WsFrame, code: number): void {
|
|
297
|
+
const socket = this.#socket;
|
|
298
|
+
if (!socket) return;
|
|
299
|
+
const ack: WsFrame = {
|
|
300
|
+
...frame,
|
|
301
|
+
headers: [...(frame.headers ?? []), { key: "biz_rt", value: "0" }],
|
|
302
|
+
payload: jsonPayload({ code }),
|
|
303
|
+
};
|
|
304
|
+
try {
|
|
305
|
+
socket.send(encodeFrame(ack));
|
|
306
|
+
} catch {
|
|
307
|
+
this.#options.log("inbound ack failed");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
#ping(): void {
|
|
312
|
+
if (this.#stopped || !this.#discovered) return;
|
|
313
|
+
const socket = this.#socket;
|
|
314
|
+
if (!socket) return;
|
|
315
|
+
try {
|
|
316
|
+
socket.send(encodeFrame({
|
|
317
|
+
SeqID: 0,
|
|
318
|
+
LogID: 0,
|
|
319
|
+
service: this.#discovered.serviceId,
|
|
320
|
+
method: 0,
|
|
321
|
+
headers: [{ key: "type", value: "ping" }],
|
|
322
|
+
}));
|
|
323
|
+
} catch {
|
|
324
|
+
this.#options.log("inbound ping failed");
|
|
325
|
+
}
|
|
326
|
+
this.#pingTimer = setTimeout(() => this.#ping(), this.#discovered.pingMs);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
#scheduleReconnect(): void {
|
|
330
|
+
if (this.#stopped || this.#connecting) return;
|
|
331
|
+
this.#connecting = true;
|
|
332
|
+
const next = this.#discovered;
|
|
333
|
+
const delay = (next?.reconnectNonceMs ?? DEFAULT_NONCE_MS) * Math.random()
|
|
334
|
+
+ (next?.reconnectMs ?? DEFAULT_RECONNECT_MS);
|
|
335
|
+
this.#options.log(`inbound reconnecting in ${Math.round(delay)}ms`);
|
|
336
|
+
this.#reconnectTimer = setTimeout(() => {
|
|
337
|
+
void this.#reconnect();
|
|
338
|
+
}, delay);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async #reconnect(): Promise<void> {
|
|
342
|
+
this.#connecting = false;
|
|
343
|
+
if (this.#stopped) return;
|
|
344
|
+
this.#attempts += 1;
|
|
345
|
+
try {
|
|
346
|
+
this.#discovered = await discovery(this.#options);
|
|
347
|
+
if (this.#stopped) return;
|
|
348
|
+
await this.#connect();
|
|
349
|
+
this.#options.log(`inbound reconnected attempt=${this.#attempts}`);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
this.#options.log(`inbound reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
352
|
+
this.#scheduleReconnect();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|