refactor(onebot): extract OneBot protocol translation into @snowluma/onebot
Phase 3 of the 4-package split (RoadMap #3). Moves the entire `packages/core/src/onebot/` subtree (43 source files + 20 test files spanning network adapters, action handlers, event converters, message parser, message store, media store, instance + manager) into the new `@snowluma/onebot` workspace package. The remaining `@snowluma/core` now hosts only the api-layer (Bridge class + 13 Api classes), the hook tooling, the WebUI server, and the runnable `index.ts`. Why --- - The OneBot adapter is the public-facing OneBot11 protocol surface; it has its own version cadence and its own consumers (third-party bots talking OneBot WS / HTTP). Splitting it lets that cadence move independently of the Api-on-ctx layer. - The two were sharing the `packages/core/` build pipeline only because they happened to live in the same directory. Nothing in the api-layer reaches into OneBot internals. - Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter is a separate assembly from the Core protocol library). Layout ------ Moved via `git mv` (history preserved): packages/core/src/onebot/* → @snowluma/onebot/src/<x> packages/core/tests/onebot/* (6 files) → @snowluma/onebot/tests/ packages/core/tests/{message-parser,message-store,event-pipeline, media-store,media-url-resolver,event-converter, http-server-hot-reload,http-server-content-type, api-handler-logging,message-id,group-msg-emoji-like, config,media-indexer,network-manager}.test.ts (14 files) → @snowluma/onebot/tests/ What stays in @snowluma/core ---------------------------- - `bridge/{bridge,bridge-interface,bridge-context,manager}.ts` - `bridge/apis/*` (the 13 typed Api classes) - `hook/*` (debugger/injector — tooling for the core protocol layer) - `webui/*` (admin UI server — application wiring, not the OneBot adapter itself) - `index.ts` (application entry that wires BridgeManager + OneBotManager + HookManager + WebUI together) Changes ------- - New package `packages/onebot/` (package.json with subpath exports mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json, vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action- dispatch logging tests see debug-level subscribers — copied verbatim from core's vitest.config.ts). - @snowluma/core grows new subpath exports for the api-layer files OneBot's type-only imports need: `./bridge`, `./bridge-interface`, `./bridge-context`, `./manager`, `./apis`. - `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`, `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`, `@snowluma/websocket`. - `@snowluma/core` depends on `@snowluma/onebot` (for index.ts + webui/server.ts wiring). - 100+ import sites rewritten via sed: * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`, `'../bridge/manager'` → `'@snowluma/core/manager'`, `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`, `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`. * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`, `'../onebot/config'` → `'@snowluma/onebot/config'`, etc. * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'` after the test file move (one level shallower). - New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads). Workspace cycle --------------- core ↔ onebot is allowed by pnpm workspaces. The runtime direction is one-way: core → onebot (index.ts constructs OneBotManager, webui/server reads OneBot config). OneBot only reaches into core for TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo, DownloadRKeyInfo); those imports use `import type` so they compile out at runtime and don't introduce a real cycle. Verification ------------ - Full workspace `pnpm -r typecheck`: all 11 projects clean. - `@snowluma/core` test suite: 302/302 pass (33 test files). - `@snowluma/onebot` test suite: 250/250 pass (20 test files; pre-existing `network-manager.test.ts` native-addon failure unchanged — same baseline as before the split). - Combined: 552/552 — identical pass count to the pre-Phase-3 baseline. - Vite build with stubbed native binary: clean, 2.84 MB bundle / 224 KB gzip (identical envelope).
This commit is contained in:
71 files changed
+286
-59
No files matched your search
@@ -0,0 +1,235 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
|
||||
const userId = parseInt(ref.uin, 10) || 0;
|
||||
const nickname = ref.bridge.identity.nickname || ref.uin;
|
||||
return { userId, nickname };
|
||||
}
|
||||
|
||||
// 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: BridgeInterface, groupId: number): Promise<void> {
|
||||
try {
|
||||
await bridge.apis.contacts.fetchGroupMemberList(groupId);
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const friends = await bridge.apis.contacts.fetchFriendList();
|
||||
return friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
} catch {
|
||||
return bridge.identity.friends.map(f => ({
|
||||
user_id: f.uin as any,
|
||||
nickname: f.nickname as any,
|
||||
remark: f.remark as any,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupList(
|
||||
bridge: BridgeInterface,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject[]> {
|
||||
try {
|
||||
if (noCache || bridge.identity.groups.length === 0) {
|
||||
await bridge.apis.contacts.fetchGroupList();
|
||||
}
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
return bridge.identity.groups.map(g => ({
|
||||
group_id: g.groupId as any,
|
||||
group_name: g.groupName as any,
|
||||
member_count: g.memberCount as any,
|
||||
max_member_count: g.memberMax as any,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getGroupInfo(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject | null> {
|
||||
if (noCache || !bridge.identity.findGroup(groupId)) {
|
||||
try {
|
||||
await bridge.apis.contacts.fetchGroupList();
|
||||
} catch {
|
||||
// Use cached data.
|
||||
}
|
||||
}
|
||||
const g = bridge.identity.findGroup(groupId);
|
||||
if (!g) return null;
|
||||
return {
|
||||
group_id: g.groupId as any,
|
||||
group_name: g.groupName as any,
|
||||
member_count: g.memberCount as any,
|
||||
max_member_count: g.memberMax as any,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getGroupMemberList(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject[]> {
|
||||
if (noCache) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
return getCachedGroupMembers(bridge.identity, groupId);
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await bridge.apis.contacts.fetchGroupMemberList(groupId);
|
||||
return members.map(m => formatGroupMember(groupId, m));
|
||||
} catch {
|
||||
return getCachedGroupMembers(bridge.identity, groupId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupMemberInfo(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
userId: number,
|
||||
noCache?: boolean,
|
||||
): Promise<JsonObject | null> {
|
||||
if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
|
||||
await refreshSingleGroupMembers(bridge, groupId);
|
||||
}
|
||||
const m = bridge.identity.findGroupMember(groupId, userId);
|
||||
if (!m) return null;
|
||||
return formatGroupMember(groupId, m);
|
||||
}
|
||||
|
||||
export async function getGroupFiles(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
folderId?: string,
|
||||
): Promise<JsonObject> {
|
||||
const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/');
|
||||
return {
|
||||
files: result.files.map((file) => ({
|
||||
group_id: groupId as any,
|
||||
file_id: file.fileId as any,
|
||||
file_name: file.fileName as any,
|
||||
busid: file.busId as any,
|
||||
file_size: file.fileSize as any,
|
||||
upload_time: file.uploadTime as any,
|
||||
dead_time: file.deadTime as any,
|
||||
modify_time: file.modifyTime as any,
|
||||
download_times: file.downloadTimes as any,
|
||||
uploader: file.uploader as any,
|
||||
uploader_name: file.uploaderName as any,
|
||||
} as JsonObject)) as any,
|
||||
folders: result.folders.map((folder) => ({
|
||||
group_id: groupId as any,
|
||||
folder_id: folder.folderId as any,
|
||||
folder_name: folder.folderName as any,
|
||||
create_time: folder.createTime as any,
|
||||
creator: folder.creator as any,
|
||||
create_name: folder.creatorName as any,
|
||||
total_file_count: folder.totalFileCount as any,
|
||||
} as JsonObject)) as any,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getStrangerInfo(
|
||||
bridge: BridgeInterface,
|
||||
userId: number,
|
||||
): Promise<JsonObject | null> {
|
||||
try {
|
||||
const p = await bridge.apis.contacts.fetchUserProfile(userId);
|
||||
return {
|
||||
user_id: p.uin as any,
|
||||
nickname: p.nickname as any,
|
||||
sex: p.sex as any,
|
||||
age: p.age as any,
|
||||
};
|
||||
} catch {
|
||||
const p = bridge.identity.findUserProfile(userId);
|
||||
if (!p) return null;
|
||||
return {
|
||||
user_id: p.uin as any,
|
||||
nickname: p.nickname as any,
|
||||
sex: p.sex as any,
|
||||
age: p.age as any,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const reqs = await bridge.apis.contacts.fetchGroupRequests();
|
||||
return reqs.map(r => ({
|
||||
group_id: r.groupId,
|
||||
group_name: r.groupName,
|
||||
request_id: r.sequence,
|
||||
requester_uin: r.targetUin,
|
||||
requester_nick: r.targetName,
|
||||
message: r.comment,
|
||||
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
|
||||
} as JsonObject));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||
try {
|
||||
const rkeys = await bridge.apis.contacts.fetchDownloadRKeys();
|
||||
return rkeys.map(r => ({
|
||||
rkey: r.rkey,
|
||||
type: r.type,
|
||||
ttl: r.ttlSeconds,
|
||||
create_time: r.createTime,
|
||||
} as JsonObject));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
|
||||
const g = identity.findGroup(groupId);
|
||||
if (!g) return [];
|
||||
const result: JsonObject[] = [];
|
||||
for (const [, member] of g.members) {
|
||||
result.push(formatGroupMember(groupId, member));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function formatGroupMember(
|
||||
groupId: number,
|
||||
member: {
|
||||
uin: number;
|
||||
nickname: string;
|
||||
card: string;
|
||||
joinTime: number;
|
||||
lastSentTime: number;
|
||||
level: number;
|
||||
role: string;
|
||||
title: string;
|
||||
},
|
||||
): JsonObject {
|
||||
return {
|
||||
group_id: groupId as any,
|
||||
user_id: member.uin as any,
|
||||
nickname: member.nickname as any,
|
||||
card: member.card as any,
|
||||
sex: 'unknown' as any,
|
||||
age: 0 as any,
|
||||
join_time: member.joinTime as any,
|
||||
last_sent_time: member.lastSentTime as any,
|
||||
level: String(member.level) as any,
|
||||
role: member.role as any,
|
||||
title: member.title as any,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export async function getImageInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
if (!cached) return null;
|
||||
const url = cached.url || cached.imageUrl || '';
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url,
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getRecordInfo(
|
||||
bridge: BridgeInterface,
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findRecord(file);
|
||||
if (!cached) return null;
|
||||
|
||||
// Re-resolve via OIDB if the cached URL is missing or empty.
|
||||
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
|
||||
let url = cached.url;
|
||||
if (!url && cached.mediaNode) {
|
||||
try {
|
||||
url = cached.isGroup
|
||||
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
|
||||
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
|
||||
if (url) {
|
||||
mediaStore.updateRecordUrl(file, url);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url: url || '',
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,38 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
|
||||
export async function handleGroupAddRequest(
|
||||
bridge: BridgeInterface,
|
||||
flag: string,
|
||||
approve: boolean,
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
|
||||
const parts = flag.split(':');
|
||||
if (parts.length < 3) throw new Error('invalid group request flag');
|
||||
const requestType = parts[0];
|
||||
const groupId = parseInt(parts[1], 10);
|
||||
const targetUid = parts.slice(2).join(':');
|
||||
if (!groupId) throw new Error('invalid group_id in flag');
|
||||
if (!targetUid) throw new Error('invalid request target in flag');
|
||||
|
||||
const requests = await bridge.apis.contacts.fetchGroupRequests();
|
||||
const matching = requests.find((r) => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
if (requestType === 'add') return r.targetUid === targetUid;
|
||||
if (requestType === 'invite') return r.invitorUid === targetUid;
|
||||
return false;
|
||||
}) || requests.find(r => r.groupId === groupId);
|
||||
|
||||
if (!matching) {
|
||||
throw new Error('matching group request not found');
|
||||
}
|
||||
|
||||
await bridge.apis.groupAdmin.setAddRequest(
|
||||
groupId,
|
||||
matching.sequence,
|
||||
matching.eventType,
|
||||
approve,
|
||||
reason,
|
||||
matching.filtered,
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user