Phase 1 of the 4-package split called out in RoadMap #3. Moves the "infrastructure" leaves — files with zero business dependencies that @snowluma/bridge, @snowluma/core, and @snowluma/onebot all consume — into a dedicated workspace package. Mirrors what #4 (proto-defs) did for wire-protobuf definitions. Why --- - Cleaner layering: these were never bridge- or onebot-specific. Logger / hex codec / runtime config sit at the bottom of every module's import graph; giving them their own package makes that graph readable and prevents future leaks the other direction. - Sets up #3's bridge + onebot extractions: those need a clean leaf to depend on. Without this, every cross-package import would have to re-export through core, which defeats the split. - Mirrors @snowluma/proto-defs layout — per-file subpath exports (`@snowluma/common/logger`, `@snowluma/common/hex`, …) keep import sites unambiguous and let bundlers tree-shake aggressively. Layout ------ Moved (via `git mv` — history preserved): packages/core/src/utils/logger.ts → @snowluma/common/logger packages/core/src/utils/hex.ts → @snowluma/common/hex packages/core/src/utils/log-file-transport.ts → @snowluma/common/log-file-transport packages/core/src/utils/log-summary.ts → @snowluma/common/log-summary packages/core/src/protocol/packet-sender.ts → @snowluma/common/packet-sender packages/core/src/protocol/types.ts → @snowluma/common/protocol-types packages/core/src/common/runtime.ts → @snowluma/common/runtime Not moved (deferred to Phase 2): `packages/core/src/utils/event-format.ts` — it has reverse imports on `bridge/events`, `bridge/identity-service`, `onebot/message-store`, `onebot/types`. It moves into @snowluma/bridge in Phase 2, with the MessageStore parameter decoupled via a structural type so bridge doesn't end up depending on onebot. Changes ------- - New package `packages/common/` (package.json, tsconfig.json — no src/index.ts barrel, callers use the subpath exports directly to avoid pulling in `node:fs` when only the hex codec is needed). - 7 `.ts` files moved via `git mv`. - 50+ import sites rewritten via sed across `packages/core/src` and `packages/core/tests`. Old shapes (`../utils/logger`, `../../protocol/types`, `./common/runtime`, `../src/utils/hex`) all collapse to `@snowluma/common/<sub>`. - `@snowluma/core` depends on `@snowluma/common` (workspace:*). - `packages/core/src/{protocol,common}/` directories removed (empty). Verification ------------ - core typecheck: clean - common typecheck: clean - Full workspace `pnpm -r typecheck`: all 9 projects clean - core test suite: 552 passed / 552 total (pre-existing websocket-darwin-arm64.node addon failure unchanged — same baseline as the previous refactor commits) - Vite build with stubbed native binary: clean (143 modules, 2.84 MB bundle, 224 KB gzip — same size envelope as before) Note: `utils/event-format.ts` is the only file remaining under the old `utils/` namespace. It moves into @snowluma/bridge alongside the events / identity-service / packet-pipeline trio in Phase 2.
165 lines
5.4 KiB
TypeScript
165 lines
5.4 KiB
TypeScript
import type { BridgeInterface } from '../bridge/bridge-interface';
|
|
import type { BridgeManager } from '../bridge/manager';
|
|
import { createLogger } from '@snowluma/common/logger';
|
|
import { loadOneBotConfig } from './config';
|
|
import { OneBotInstance } from './instance';
|
|
|
|
const log = createLogger('OneBot');
|
|
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
|
|
|
export class OneBotManager {
|
|
private readonly instances = new Map<string, OneBotInstance>();
|
|
|
|
bind(bridgeManager: BridgeManager): void {
|
|
bridgeManager.setSessionStartedCallback((uin, bridge) => {
|
|
this.onSessionStarted(uin, bridge);
|
|
});
|
|
|
|
bridgeManager.setSessionClosedCallback((uin) => {
|
|
this.onSessionClosed(uin);
|
|
});
|
|
}
|
|
|
|
getInstance(uin: string): OneBotInstance | null {
|
|
return this.instances.get(uin) ?? null;
|
|
}
|
|
|
|
getInstances(): OneBotInstance[] {
|
|
return [...this.instances.values()];
|
|
}
|
|
|
|
reloadConfig(uin: string): boolean {
|
|
const instance = this.instances.get(uin);
|
|
if (!instance) return false;
|
|
|
|
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
|
instance.reloadConfig(config);
|
|
log.info('configuration reloaded: UIN=%s', uin);
|
|
return true;
|
|
}
|
|
|
|
dispose(): void {
|
|
for (const instance of this.instances.values()) {
|
|
instance.dispose();
|
|
}
|
|
this.instances.clear();
|
|
}
|
|
|
|
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
|
|
if (this.instances.has(uin)) return;
|
|
|
|
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
|
const instance = new OneBotInstance(uin, bridge, config);
|
|
|
|
const activePid = bridge.activePid;
|
|
if (activePid !== null) {
|
|
instance.addPid(activePid);
|
|
}
|
|
|
|
// Seed nickname with the UIN so the WebUI never renders blank while
|
|
// warmup is in flight or if warmup never resolves a real nickname.
|
|
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
|
|
|
|
this.instances.set(uin, instance);
|
|
log.info('session started: UIN=%s', uin);
|
|
|
|
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
|
|
warmUpBridgeState(uin, bridge).catch((err) => {
|
|
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
|
});
|
|
}
|
|
|
|
private onSessionClosed(uin: string): void {
|
|
const instance = this.instances.get(uin);
|
|
if (!instance) return;
|
|
|
|
instance.dispose();
|
|
this.instances.delete(uin);
|
|
log.info('session closed: UIN=%s', uin);
|
|
}
|
|
|
|
}
|
|
|
|
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
|
|
const selfUin = parseInt(uin, 10) || 0;
|
|
let selfResolved = false;
|
|
|
|
// Step 1: Fetch friend list + derive self profile when QQ happens to
|
|
// include self in the response. Some accounts / versions omit self,
|
|
// which used to leave identity.nickname empty — see step 1b for the
|
|
// explicit fallback.
|
|
try {
|
|
const friends = await bridge.apis.contacts.fetchFriendList();
|
|
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
|
|
|
for (const f of friends) {
|
|
if (f.uin === selfUin) {
|
|
bridge.identity.setSelfProfile({
|
|
uin: f.uin, uid: f.uid,
|
|
nickname: f.nickname || uin,
|
|
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
|
|
});
|
|
bridge.identity.nickname = f.nickname || uin;
|
|
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
|
|
selfResolved = true;
|
|
break;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
|
}
|
|
|
|
// Step 1b: friend-list path didn't resolve self → fetch user profile
|
|
// directly via OIDB 0xFE1_2 so multi-account WebUI shows a nickname
|
|
// for every injected session, not just the ones where QQ echoed self
|
|
// back in the friend list.
|
|
if (!selfResolved && selfUin > 0) {
|
|
try {
|
|
const profile = await bridge.apis.contacts.fetchUserProfile(selfUin);
|
|
bridge.identity.setSelfProfile(profile);
|
|
bridge.identity.nickname = profile.nickname || uin;
|
|
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
|
uin, profile.uid, profile.nickname);
|
|
} catch (e) {
|
|
log.warn('failed to load self profile for UIN %s: %s',
|
|
uin, e instanceof Error ? e.message : String(e));
|
|
}
|
|
}
|
|
|
|
// Step 2: Fetch group list
|
|
let groups: { groupId: number }[] = [];
|
|
try {
|
|
groups = await bridge.apis.contacts.fetchGroupList();
|
|
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
|
} catch (e) {
|
|
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
|
}
|
|
|
|
// Step 3: Fetch members for each group
|
|
let loadedGroupCount = 0;
|
|
let loadedMemberCount = 0;
|
|
let failedGroupCount = 0;
|
|
for (const g of groups) {
|
|
try {
|
|
const members = await bridge.apis.contacts.fetchGroupMemberList(g.groupId);
|
|
loadedGroupCount += 1;
|
|
loadedMemberCount += members.length;
|
|
if (VERBOSE_WARMUP) {
|
|
log.debug('members loaded: group=%d count=%d', g.groupId, members.length);
|
|
}
|
|
} catch (e) {
|
|
failedGroupCount += 1;
|
|
log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e));
|
|
}
|
|
}
|
|
|
|
log.info(
|
|
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
|
|
uin,
|
|
loadedGroupCount,
|
|
groups.length,
|
|
loadedMemberCount,
|
|
failedGroupCount,
|
|
);
|
|
}
|