From e6b609dd4e6ad4c08a5e7a41f9c2bd6e8ffc29e4 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 15 May 2026 01:12:40 +0800 Subject: [PATCH] refactor(bridge): extract BridgeInterface as the OneBot-facing seam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OneBot used to depend on the concrete Bridge class — 778 lines, ~99 public methods including PID management, raw packet dispatch, and cmd handler registration that no external consumer should touch. Add an explicit BridgeInterface (bridge/bridge-interface.ts) enumerating only the surface OneBot actually reads (verified by grepping every bridge.* access in onebot/), and have Bridge `implements BridgeInterface` so the compiler enforces alignment. Net effect at runtime: zero — Bridge's methods, fields, and bodies are unchanged; the interface is a TypeScript-only declaration. Net effect for typing: the OneBot package (instance, instance-context, instance-rkey, manager, media-url-resolver, and the modules under onebot/modules/) now imports `BridgeInterface` instead of `Bridge`, so tests / fakes can satisfy the interface without subclassing or pulling in the SQLite/native bits. In-tree bridge actions (actions/*, bridge-contacts, highway) keep their concrete `Bridge` typing — they legitimately need sendRawPacket and other low-level entry points that intentionally stay off the interface. --- packages/core/src/bridge/bridge-interface.ts | 130 ++++++++++++++++++ packages/core/src/bridge/bridge.ts | 3 +- packages/core/src/onebot/instance-context.ts | 4 +- packages/core/src/onebot/instance-rkey.ts | 13 +- packages/core/src/onebot/instance.ts | 6 +- packages/core/src/onebot/manager.ts | 6 +- .../core/src/onebot/media-url-resolver.ts | 4 +- .../src/onebot/modules/contact-actions.ts | 22 +-- .../core/src/onebot/modules/media-actions.ts | 4 +- .../src/onebot/modules/message-actions.ts | 6 +- .../src/onebot/modules/request-actions.ts | 4 +- 11 files changed, 167 insertions(+), 35 deletions(-) create mode 100644 packages/core/src/bridge/bridge-interface.ts diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts new file mode 100644 index 00000000..ca841697 --- /dev/null +++ b/packages/core/src/bridge/bridge-interface.ts @@ -0,0 +1,130 @@ +// BridgeInterface — the surface OneBot (and any other external consumer) +// is allowed to see. The concrete Bridge class additionally exposes raw +// protocol primitives (sendRawPacket, packet dispatch, PID management) +// used by the in-tree action / contacts / highway modules; those internal +// methods deliberately do NOT appear here so that callers depending on +// the interface stay decoupled from the wire format. +// +// Every method below has a matching signature on Bridge; `Bridge +// implements BridgeInterface` is the compile-time enforcement. + +import type { BridgeEventBus } from './event-bus'; +import type { IdentityService } from './identity-service'; +import type { + FriendInfo, QQGroupInfo, GroupMemberInfo, + UserProfileInfo, GroupRequestInfo, +} from './qq-info'; +import type { MessageElement, ForwardNodePayload } from './events'; +import type { GroupFilesResult } from './actions/group-file'; +import type { MediaIndexNode } from './actions/shared'; +import type { WebHonorType } from './web/group-honor'; +import type { + SendMessageReceipt, + DownloadRKeyInfo, + ClientKeyInfo, +} from './bridge'; + +export interface BridgeInterface { + // ─── Shared state ─── + readonly identity: IdentityService; + readonly events: BridgeEventBus; + readonly activePid: number | null; + + // ─── Resolution ─── + resolveUserUid(uin: number, groupId?: number): Promise; + + // ─── Send (messages) ─── + sendGroupMessage(groupId: number, elements: MessageElement[]): Promise; + sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise; + + // ─── Fetch (contacts / profile / system) ─── + fetchFriendList(): Promise; + fetchGroupList(): Promise; + fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise; + fetchUserProfile(uin: number): Promise; + fetchGroupRequests(filtered?: boolean): Promise; + fetchDownloadRKeys(): Promise; + + // ─── Group admin ─── + muteGroupMember(groupId: number, userId: number, duration: number): Promise; + muteGroupAll(groupId: number, enable: boolean): Promise; + setGroupAddOption(groupId: number, addType: number): Promise; + setGroupSearch(groupId: number): Promise; + setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason?: string, filtered?: boolean): Promise; + kickGroupMember(groupId: number, userId: number, reject: boolean, reason?: string): Promise; + kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise; + leaveGroup(groupId: number): Promise; + setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise; + setGroupCard(groupId: number, userId: number, card: string): Promise; + setGroupName(groupId: number, name: string): Promise; + setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise; + setGroupRemark(groupId: number, remark: string): Promise; + setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise; + setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise; + + // ─── Friend ─── + setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise; + deleteFriend(userId: number, block?: boolean): Promise; + setFriendRemark(userId: number, remark: string): Promise; + + // ─── Files ─── + uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; + uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>; + fetchGroupFiles(groupId: number, folderId?: string): Promise; + fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise; + fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise; + fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise; + fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise; + fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise; + fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise; + deleteGroupFile(groupId: number, fileId: string): Promise; + moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise; + createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise; + deleteGroupFileFolder(groupId: number, folderId: string): Promise; + renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise; + fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>; + + // ─── Forward ─── + uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise; + fetchForwardNodes(resId: string): Promise; + + // ─── Message ops ─── + recallGroupMessage(groupId: number, sequence: number): Promise; + recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise; + markGroupMsgAsRead(groupId: number, sequence: number): Promise; + markPrivateMsgAsRead(userId: number, sequence: number): Promise; + + // ─── Interaction ─── + sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise; + sendLike(userId: number, count: number): Promise; + getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }>; + + // ─── Web-backed ─── + getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise; + forceFetchClientKey(): Promise; + getGroupEssence(groupId: number, pageStart?: number, pageLimit?: number): Promise; + getGroupEssenceAll(groupId: number): Promise; + sendGroupNotice(groupId: number, content: string, options?: any): Promise; + getGroupNotice(groupId: number): Promise; + deleteGroupNotice(groupId: number, fid: string): Promise; + getCookiesStr(domain: string): Promise; + getCsrfToken(): Promise; + getCredentials(domain: string): Promise; + + // ─── Personal profile ─── + setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise; + setProfile(nickname?: string, personalNote?: string): Promise; + setSelfLongNick(longNick: string): Promise; + setInputStatus(userId: number, eventType: number): Promise; + setAvatar(source: string): Promise; + fetchCustomFace(count?: number): Promise; + getProfileLike(userId?: number, start?: number, limit?: number): Promise; + getUnidirectionalFriendList(): Promise; + getGroupAtAllRemain(groupId: number): Promise; + + // ─── Misc ─── + translateEn2Zh(words: string[]): Promise; + getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise; + clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise; + sendGroupSign(groupId: number): Promise; +} diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 9eafda09..aaabce17 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -10,6 +10,7 @@ import type { PacketSender, SendPacketResult } from '../protocol/packet-sender'; import { protoEncode, protoDecode } from '../protobuf/decode'; import { buildSendElems } from './element-builder'; import { IdentityService } from './identity-service'; +import type { BridgeInterface } from './bridge-interface'; import { createLogger } from '../utils/logger'; import { SendMessageRequestSchema, @@ -142,7 +143,7 @@ type GroupMemberIdentityEvent = Extract(); private lastRefreshAttempt = 0; - warmUp(bridge: Bridge, uin: string): void { + warmUp(bridge: BridgeInterface, uin: string): void { bridge.fetchDownloadRKeys().then( (rkeys) => { this.updateCache(rkeys); @@ -38,7 +39,7 @@ export class RKeyCache { ); } - resolveImageUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string { + resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { const url = element.imageUrl ?? ''; if (!urlNeedsRKey(url)) return url; @@ -54,7 +55,7 @@ export class RKeyCache { * Resolve a URL for video/record/file media elements. * Appends the correct RKey type based on media kind and group/private context. */ - resolveMediaUrl(bridge: Bridge, element: MessageElement, isGroup: boolean): string { + resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { const url = element.url ?? ''; if (!url || !urlNeedsRKey(url)) return url; @@ -93,12 +94,12 @@ export class RKeyCache { } } - private findRKey(bridge: Bridge, isGroup: boolean): string | null { + private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null { const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; return this.findRKeyForType(bridge, primaryType); } - private findRKeyForType(bridge: Bridge, primaryType: number): string | null { + private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null { const now = Math.floor(Date.now() / 1000); const tryFind = (type: number): string | null => { diff --git a/packages/core/src/onebot/instance.ts b/packages/core/src/onebot/instance.ts index 4d11eeed..ab11372e 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/core/src/onebot/instance.ts @@ -1,5 +1,5 @@ import path from 'path'; -import type { Bridge } from '../bridge/bridge'; +import type { BridgeInterface } from '../bridge/bridge-interface'; import { ApiHandler } from './api-handler'; import type { ConverterContext } from './event-converter'; import { MediaIndexer } from './media-indexer'; @@ -26,7 +26,7 @@ const log = createLogger('Event'); export class OneBotInstance { readonly uin: string; - private readonly bridge: Bridge; + private readonly bridge: BridgeInterface; private readonly apiHandler: ApiHandler; private readonly converterCtx: ConverterContext; private readonly messageStore: MessageStore; @@ -43,7 +43,7 @@ export class OneBotInstance { get nickname(): string { return this.bridge.identity.nickname; } - constructor(uin: string, bridge: Bridge, config: OneBotConfig) { + constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) { this.uin = uin; this.bridge = bridge; diff --git a/packages/core/src/onebot/manager.ts b/packages/core/src/onebot/manager.ts index d1d11f4f..ec4dfca4 100644 --- a/packages/core/src/onebot/manager.ts +++ b/packages/core/src/onebot/manager.ts @@ -1,4 +1,4 @@ -import type { Bridge } from '../bridge/bridge'; +import type { BridgeInterface } from '../bridge/bridge-interface'; import type { BridgeManager } from '../bridge/manager'; import { loadOneBotConfig } from './config'; import { OneBotInstance } from './instance'; @@ -48,7 +48,7 @@ export class OneBotManager { this.instances.clear(); } - private onSessionStarted(uin: string, bridge: Bridge): void { + private onSessionStarted(uin: string, bridge: BridgeInterface): void { if (this.instances.has(uin)) return; const config = loadOneBotConfig(uin); @@ -83,7 +83,7 @@ export class OneBotManager { } -async function warmUpBridgeState(uin: string, bridge: Bridge): Promise { +async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise { const selfUin = parseInt(uin, 10) || 0; let selfResolved = false; diff --git a/packages/core/src/onebot/media-url-resolver.ts b/packages/core/src/onebot/media-url-resolver.ts index 39e963da..b30c9546 100644 --- a/packages/core/src/onebot/media-url-resolver.ts +++ b/packages/core/src/onebot/media-url-resolver.ts @@ -12,13 +12,13 @@ // // Used as the `mediaUrlResolver` callback in `ConverterContext`. -import type { Bridge } from '../bridge/bridge'; +import type { BridgeInterface } from '../bridge/bridge-interface'; import type { MessageElement } from '../bridge/events'; import type { RKeyCache } from './instance-rkey'; export class MediaUrlResolver { constructor( - private readonly bridge: Bridge, + private readonly bridge: BridgeInterface, private readonly rkeyCache: RKeyCache, ) {} diff --git a/packages/core/src/onebot/modules/contact-actions.ts b/packages/core/src/onebot/modules/contact-actions.ts index 620f4bb8..f2e00ab2 100644 --- a/packages/core/src/onebot/modules/contact-actions.ts +++ b/packages/core/src/onebot/modules/contact-actions.ts @@ -1,4 +1,4 @@ -import type { Bridge } from '../../bridge/bridge'; +import type { BridgeInterface } from '../../bridge/bridge-interface'; import type { IdentityService } from '../../bridge/identity-service'; import type { OneBotInstanceContext } from '../instance-context'; import type { JsonObject } from '../types'; @@ -11,7 +11,7 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick // Keep refreshes scoped. A broad "refresh all members in all groups" call can // turn one OneBot request into N OIDB calls, which is risky for busy clients. -async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promise { +async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise { try { await bridge.fetchGroupMemberList(groupId); } catch { @@ -19,7 +19,7 @@ async function refreshSingleGroupMembers(bridge: Bridge, groupId: number): Promi } } -export async function getFriendList(bridge: Bridge): Promise { +export async function getFriendList(bridge: BridgeInterface): Promise { try { const friends = await bridge.fetchFriendList(); return friends.map(f => ({ @@ -37,7 +37,7 @@ export async function getFriendList(bridge: Bridge): Promise { } export async function getGroupList( - bridge: Bridge, + bridge: BridgeInterface, noCache?: boolean, ): Promise { try { @@ -56,7 +56,7 @@ export async function getGroupList( } export async function getGroupInfo( - bridge: Bridge, + bridge: BridgeInterface, groupId: number, noCache?: boolean, ): Promise { @@ -78,7 +78,7 @@ export async function getGroupInfo( } export async function getGroupMemberList( - bridge: Bridge, + bridge: BridgeInterface, groupId: number, noCache?: boolean, ): Promise { @@ -96,7 +96,7 @@ export async function getGroupMemberList( } export async function getGroupMemberInfo( - bridge: Bridge, + bridge: BridgeInterface, groupId: number, userId: number, noCache?: boolean, @@ -110,7 +110,7 @@ export async function getGroupMemberInfo( } export async function getGroupFiles( - bridge: Bridge, + bridge: BridgeInterface, groupId: number, folderId?: string, ): Promise { @@ -142,7 +142,7 @@ export async function getGroupFiles( } export async function getStrangerInfo( - bridge: Bridge, + bridge: BridgeInterface, userId: number, ): Promise { try { @@ -165,7 +165,7 @@ export async function getStrangerInfo( } } -export async function getGroupSystemMessages(bridge: Bridge): Promise { +export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { try { const reqs = await bridge.fetchGroupRequests(); return reqs.map(r => ({ @@ -182,7 +182,7 @@ export async function getGroupSystemMessages(bridge: Bridge): Promise { +export async function getDownloadRKeys(bridge: BridgeInterface): Promise { try { const rkeys = await bridge.fetchDownloadRKeys(); return rkeys.map(r => ({ diff --git a/packages/core/src/onebot/modules/media-actions.ts b/packages/core/src/onebot/modules/media-actions.ts index fb7a0319..f3be88f9 100644 --- a/packages/core/src/onebot/modules/media-actions.ts +++ b/packages/core/src/onebot/modules/media-actions.ts @@ -1,4 +1,4 @@ -import type { Bridge } from '../../bridge/bridge'; +import type { BridgeInterface } from '../../bridge/bridge-interface'; import { createLogger } from '../../utils/logger'; import type { MediaStore } from '../media-store'; import type { JsonObject } from '../types'; @@ -21,7 +21,7 @@ export async function getImageInfo( } export async function getRecordInfo( - bridge: Bridge, + bridge: BridgeInterface, mediaStore: MediaStore, file: string, ): Promise { diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index b0267909..a2b2a0a5 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -1,4 +1,4 @@ -import type { Bridge } from '../../bridge/bridge'; +import type { BridgeInterface } from '../../bridge/bridge-interface'; import type { ForwardNodePayload, MessageElement } from '../../bridge/events'; import { createLogger } from '../../utils/logger'; import type { MessageSendResult } from '../api-handler'; @@ -63,7 +63,7 @@ export async function getFriendMsgHistory( .map(sanitizeMessageEventForApi); } -export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise { +export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise { if (meta.isGroup) { await bridge.recallGroupMessage(meta.targetId, meta.sequence); } else { @@ -78,7 +78,7 @@ export async function deleteMessage(bridge: Bridge, meta: MessageMeta): Promise< } export async function setEssenceMessage( - bridge: Bridge, + bridge: BridgeInterface, messageStore: MessageStore, messageId: number, enable: boolean, diff --git a/packages/core/src/onebot/modules/request-actions.ts b/packages/core/src/onebot/modules/request-actions.ts index a9f34d48..e2bf9784 100644 --- a/packages/core/src/onebot/modules/request-actions.ts +++ b/packages/core/src/onebot/modules/request-actions.ts @@ -1,7 +1,7 @@ -import type { Bridge } from '../../bridge/bridge'; +import type { BridgeInterface } from '../../bridge/bridge-interface'; export async function handleGroupAddRequest( - bridge: Bridge, + bridge: BridgeInterface, flag: string, approve: boolean, reason: string,