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
@@ -1,130 +0,0 @@
|
||||
// Tests for ApiHandler's central dispatch logging.
|
||||
// Verifies that every action call emits a debug entry line, failures
|
||||
// fold into a warn line with stack, and unknown actions are surfaced.
|
||||
// Also covers the summarizeParams helper used to keep the entry log
|
||||
// from blowing the line width.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { ApiHandler } from '../src/onebot/api-handler';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import { summarizeParams } from '@snowluma/common/log-summary';
|
||||
|
||||
// Minimal context — we never reach the real action handlers; we
|
||||
// register our own via registerAction.
|
||||
function emptyContext(): any {
|
||||
return {
|
||||
bridge: {},
|
||||
getLoginInfo: () => ({ userId: 0, nickname: '' }),
|
||||
isOnline: () => true,
|
||||
getMessage: () => null,
|
||||
getMessageMeta: () => null,
|
||||
sendPrivateMessage: async () => ({ messageId: 0 }),
|
||||
sendGroupMessage: async () => ({ messageId: 0 }),
|
||||
deleteMessage: async () => {},
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
getFriendList: async () => [],
|
||||
getImageInfo: async () => null,
|
||||
getRecordInfo: async () => null,
|
||||
};
|
||||
}
|
||||
|
||||
let captured: LogEntry[];
|
||||
let unsub: () => void;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = 'debug';
|
||||
captured = [];
|
||||
unsub = subscribeLogs((e) => captured.push(e));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsub();
|
||||
if (savedLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = savedLogLevel;
|
||||
});
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders flat scalar fields as k=v pairs', () => {
|
||||
const out = summarizeParams({ group_id: 12345, auto_escape: false, foo: 'bar' });
|
||||
expect(out).toBe('group_id=12345 auto_escape=false foo="bar"');
|
||||
});
|
||||
|
||||
it('truncates long string values with an ellipsis', () => {
|
||||
const long = 'x'.repeat(80);
|
||||
const out = summarizeParams({ s: long });
|
||||
expect(out).toMatch(/^s="x{40}\.\.\."$/);
|
||||
});
|
||||
|
||||
it('collapses arrays and nested objects rather than dumping them', () => {
|
||||
const out = summarizeParams({ messages: [1, 2, 3, 4], meta: { a: 1, b: 2 } });
|
||||
expect(out).toBe('messages=[len=4] meta={...}');
|
||||
});
|
||||
|
||||
it('caps the total line and tags the cut with ellipsis', () => {
|
||||
const params: Record<string, number> = {};
|
||||
for (let i = 0; i < 30; i++) params[`field_with_some_padding_${i}`] = i;
|
||||
const out = summarizeParams(params);
|
||||
expect(out.length).toBeLessThan(220);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
});
|
||||
|
||||
it('handles null / undefined inputs gracefully', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler dispatch logging', () => {
|
||||
it('emits a debug entry under [Bridge.Action] when an action is called', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
|
||||
await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] });
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.uin).toBe(12345);
|
||||
expect(entry!.message).toContain('echo');
|
||||
expect(entry!.message).toContain('group_id=67890');
|
||||
expect(entry!.message).toContain('message=[len=3]');
|
||||
});
|
||||
|
||||
it('emits a warn line with the error stack when the handler throws', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('boom', async () => {
|
||||
throw new Error('kapow');
|
||||
});
|
||||
|
||||
const result = await handler.handle('boom', {});
|
||||
expect(result.status).toBe('failed');
|
||||
|
||||
const warn = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'warn');
|
||||
expect(warn).toBeDefined();
|
||||
expect(warn!.message).toContain('boom');
|
||||
expect(warn!.message).toContain('kapow');
|
||||
// stack contains the test file path; just check that something stack-shaped is appended
|
||||
expect(warn!.message).toMatch(/at\s+/);
|
||||
});
|
||||
|
||||
it('logs unknown actions at debug level', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 99);
|
||||
await handler.handle('not_a_real_action', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action'));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
|
||||
it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => {
|
||||
const handler = new ApiHandler(emptyContext());
|
||||
handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
|
||||
await handler.handle('ping', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.uin).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,203 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/onebot/config';
|
||||
|
||||
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||
|
||||
describe('makeDefaultOneBotConfig', () => {
|
||||
it('returns default unified networks structure', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
expect(config.networks.httpServers[0].name).toBe('http-default');
|
||||
expect(config.networks.httpServers[0].host).toBe('0.0.0.0');
|
||||
expect(config.networks.httpServers[0].port).toBe(3000);
|
||||
expect(config.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
expect(config.networks.httpServers[0].messageFormat).toBe('array');
|
||||
expect(config.networks.httpServers[0].reportSelfMessage).toBe(false);
|
||||
expect(config.networks.httpClients).toEqual([]);
|
||||
expect(config.networks.wsServers).toHaveLength(1);
|
||||
expect(config.networks.wsServers[0].port).toBe(3001);
|
||||
expect(config.networks.wsServers[0].role).toBe('Universal');
|
||||
expect(config.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
expect(config.networks.wsServers[0].messageFormat).toBe('array');
|
||||
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
|
||||
expect(config.networks.wsClients).toEqual([]);
|
||||
expect(config.musicSignUrl).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadOneBotConfig', () => {
|
||||
let tempDir: string;
|
||||
let prevCwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-config-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(prevCwd);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('creates and persists default config when none exists', () => {
|
||||
const uin = '10001';
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
|
||||
expect(onDisk.networks).toBeDefined();
|
||||
expect(Array.isArray(onDisk.networks.httpServers)).toBe(true);
|
||||
expect(onDisk.networks.httpServers[0].name).toBe('http-default');
|
||||
expect(onDisk.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
expect(onDisk.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||
// Legacy keys must not appear in the persisted file.
|
||||
expect(onDisk.httpServers).toBeUndefined();
|
||||
expect(onDisk.wsServers).toBeUndefined();
|
||||
});
|
||||
|
||||
it('migrates legacy per-type arrays into networks groups', () => {
|
||||
const uin = '10002';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const legacy = {
|
||||
httpServers: [{ host: '0.0.0.0', port: 3100, path: '/', accessToken: 'tok' }],
|
||||
httpPostEndpoints: [{ name: 'main-bot', url: 'http://127.0.0.1:5700' }],
|
||||
wsServers: [{ host: '0.0.0.0', port: 3101 }],
|
||||
wsClients: [{ url: 'ws://127.0.0.1:8080' }],
|
||||
musicSignUrl: 'https://example.com/sign',
|
||||
messageFormat: 'string',
|
||||
reportSelfMessage: true,
|
||||
};
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
expect(config.networks.httpServers[0].port).toBe(3100);
|
||||
expect(config.networks.httpServers[0].accessToken).toBe('tok');
|
||||
expect(config.networks.httpServers[0].messageFormat).toBe('string');
|
||||
expect(config.networks.httpServers[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.networks.httpClients).toHaveLength(1);
|
||||
expect(config.networks.httpClients[0].name).toBe('main-bot');
|
||||
expect(config.networks.httpClients[0].url).toBe('http://127.0.0.1:5700');
|
||||
expect(config.networks.httpClients[0].messageFormat).toBe('string');
|
||||
expect(config.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.networks.wsServers).toHaveLength(1);
|
||||
expect(config.networks.wsServers[0].port).toBe(3101);
|
||||
expect(config.networks.wsServers[0].messageFormat).toBe('string');
|
||||
expect(config.networks.wsServers[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.networks.wsClients).toHaveLength(1);
|
||||
expect(config.networks.wsClients[0].url).toBe('ws://127.0.0.1:8080');
|
||||
expect(config.networks.wsClients[0].messageFormat).toBe('string');
|
||||
expect(config.networks.wsClients[0].reportSelfMessage).toBe(true);
|
||||
|
||||
expect(config.musicSignUrl).toBe('https://example.com/sign');
|
||||
|
||||
// File should now be in unified format on disk.
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8'));
|
||||
expect(onDisk.networks).toBeDefined();
|
||||
expect(onDisk.httpServers).toBeUndefined();
|
||||
expect(onDisk.httpPostEndpoints).toBeUndefined();
|
||||
expect(onDisk.messageFormat).toBeUndefined();
|
||||
expect(onDisk.reportSelfMessage).toBeUndefined();
|
||||
expect(onDisk.networks.httpServers[0].messageFormat).toBe('string');
|
||||
expect(onDisk.networks.httpServers[0].reportSelfMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('round-trips per-adapter overrides through save/load', () => {
|
||||
const uin = '10003';
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.httpClients.push({
|
||||
name: 'self-mirror',
|
||||
url: 'http://127.0.0.1:9000',
|
||||
messageFormat: 'string',
|
||||
reportSelfMessage: true,
|
||||
});
|
||||
saveOneBotConfig(uin, config);
|
||||
|
||||
const reloaded = loadOneBotConfig(uin);
|
||||
expect(reloaded.networks.httpClients).toHaveLength(1);
|
||||
expect(reloaded.networks.httpClients[0].name).toBe('self-mirror');
|
||||
expect(reloaded.networks.httpClients[0].messageFormat).toBe('string');
|
||||
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('does not write to disk by default (read-only contract)', () => {
|
||||
const uin = '10006';
|
||||
const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`);
|
||||
|
||||
// Default call must not materialize the file or mint a fresh access token.
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
expect(fs.existsSync(cfgPath)).toBe(false);
|
||||
|
||||
// Explicit opt-in still writes.
|
||||
loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(fs.existsSync(cfgPath)).toBe(true);
|
||||
});
|
||||
|
||||
it('respects an operator-emptied adapter list instead of seeding defaults back', () => {
|
||||
const uin = '10007';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
|
||||
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
|
||||
musicSignUrl: '',
|
||||
}), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(config.networks.httpServers).toEqual([]);
|
||||
expect(config.networks.wsServers).toEqual([]);
|
||||
});
|
||||
|
||||
it('migrates legacy lowercase WsRole values into canonical uppercase form', () => {
|
||||
const uin = '10005';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
|
||||
networks: {
|
||||
httpServers: [],
|
||||
httpClients: [],
|
||||
wsServers: [
|
||||
{ name: 'ws-legacy', host: '0.0.0.0', port: 3201, path: '/', role: 'universal', messageFormat: 'array', reportSelfMessage: false },
|
||||
],
|
||||
wsClients: [
|
||||
{ name: 'wsc-legacy', url: 'ws://127.0.0.1:8080', role: 'event', messageFormat: 'array', reportSelfMessage: false },
|
||||
],
|
||||
},
|
||||
}), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.networks.wsServers).toHaveLength(1);
|
||||
expect(config.networks.wsServers[0].role).toBe('Universal');
|
||||
expect(config.networks.wsClients).toHaveLength(1);
|
||||
expect(config.networks.wsClients[0].role).toBe('Event');
|
||||
});
|
||||
|
||||
it('auto-generates names for legacy entries that lack one', () => {
|
||||
const uin = '10004';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
|
||||
httpServers: [
|
||||
{ port: 3000 },
|
||||
{ port: 3001 },
|
||||
],
|
||||
}), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const names = config.networks.httpServers.map((n) => n.name);
|
||||
expect(names).toHaveLength(2);
|
||||
expect(new Set(names).size).toBe(2); // unique
|
||||
expect(names.every((n) => n.length > 0)).toBe(true);
|
||||
expect(config.networks.httpServers.every((n) => n.messageFormat === 'array')).toBe(true);
|
||||
expect(config.networks.httpServers.every((n) => n.reportSelfMessage === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,627 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
convertEvent,
|
||||
elementsToOneBotSegments,
|
||||
type ConverterContext,
|
||||
} from '../src/onebot/event-converter';
|
||||
import {
|
||||
buildDispatchPayload,
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
shapeEventForAdapter,
|
||||
} from '../src/onebot/event-filter';
|
||||
import type {
|
||||
FriendMessage,
|
||||
GroupMessage,
|
||||
MessageElement,
|
||||
QQEventVariant,
|
||||
TempMessage,
|
||||
} from '@snowluma/bridge/events';
|
||||
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
const GROUP_ID = 99999;
|
||||
|
||||
/** Minimal ConverterContext with no resolvers (all null). Per-test
|
||||
* helpers override individual fields when they need a stub. */
|
||||
function bareCtx(overrides: Partial<ConverterContext> = {}): ConverterContext {
|
||||
return {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFriendMessage(senderUin: number): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin,
|
||||
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(senderUin: number): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: 99999,
|
||||
senderUin,
|
||||
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeTempMessage(senderUin: number): TempMessage {
|
||||
return {
|
||||
kind: 'temp_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin,
|
||||
groupId: 99999,
|
||||
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||
msgSeq: 1,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
describe('convertEvent — message kinds', () => {
|
||||
it('friend_message peer → post_type "message", sub_type "friend"', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeFriendMessage(PEER_UIN));
|
||||
expect(out).not.toBeNull();
|
||||
expect(out!.post_type).toBe('message');
|
||||
expect(out!.message_type).toBe('private');
|
||||
expect(out!.sub_type).toBe('friend');
|
||||
expect(out!.user_id).toBe(PEER_UIN);
|
||||
expect(out!.self_id).toBe(SELF_ID);
|
||||
expect(out!.raw_message).toBe('hi');
|
||||
});
|
||||
|
||||
it('friend_message self → post_type "message_sent"', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeFriendMessage(SELF_ID));
|
||||
expect(out!.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('group_message peer → post_type "message", sub_type "normal", group_id set', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeGroupMessage(PEER_UIN));
|
||||
expect(out!.post_type).toBe('message');
|
||||
expect(out!.message_type).toBe('group');
|
||||
expect(out!.sub_type).toBe('normal');
|
||||
expect(out!.group_id).toBe(GROUP_ID);
|
||||
});
|
||||
|
||||
it('group_message self → post_type "message_sent"', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeGroupMessage(SELF_ID));
|
||||
expect(out!.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('temp_message peer → post_type "message", sub_type "group"', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeTempMessage(PEER_UIN));
|
||||
expect(out!.post_type).toBe('message');
|
||||
expect(out!.sub_type).toBe('group');
|
||||
});
|
||||
|
||||
it('temp_message self → post_type "message_sent"', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeTempMessage(SELF_ID));
|
||||
expect(out!.post_type).toBe('message_sent');
|
||||
expect(out!.sub_type).toBe('group');
|
||||
});
|
||||
|
||||
it('messageIdResolver overrides the raw msgSeq', async () => {
|
||||
const ctx = bareCtx({ messageIdResolver: (_g, _s, seq) => seq * 10 });
|
||||
const out = await convertEvent(ctx, makeFriendMessage(PEER_UIN));
|
||||
expect(out!.message_id).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertEvent — notice kinds', () => {
|
||||
it('group_member_join: same-actor approve, else invite', async () => {
|
||||
const approve = await convertEvent(bareCtx(), {
|
||||
kind: 'group_member_join',
|
||||
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, operatorUin: PEER_UIN,
|
||||
} as QQEventVariant);
|
||||
expect(approve!.notice_type).toBe('group_increase');
|
||||
expect(approve!.sub_type).toBe('approve');
|
||||
|
||||
const invite = await convertEvent(bareCtx(), {
|
||||
kind: 'group_member_join',
|
||||
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, operatorUin: 33333,
|
||||
} as QQEventVariant);
|
||||
expect(invite!.sub_type).toBe('invite');
|
||||
});
|
||||
|
||||
it('group_member_leave: leave / kick / kick_me', async () => {
|
||||
const leave = await convertEvent(bareCtx(), {
|
||||
kind: 'group_member_leave',
|
||||
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, operatorUin: 0, isKick: false,
|
||||
} as QQEventVariant);
|
||||
expect(leave!.sub_type).toBe('leave');
|
||||
|
||||
const kick = await convertEvent(bareCtx(), {
|
||||
kind: 'group_member_leave',
|
||||
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, operatorUin: 33333, isKick: true,
|
||||
} as QQEventVariant);
|
||||
expect(kick!.sub_type).toBe('kick');
|
||||
|
||||
const kickMe = await convertEvent(bareCtx(), {
|
||||
kind: 'group_member_leave',
|
||||
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: SELF_ID, operatorUin: 33333, isKick: true,
|
||||
} as QQEventVariant);
|
||||
expect(kickMe!.sub_type).toBe('kick_me');
|
||||
});
|
||||
|
||||
it('group_mute: ban vs lift_ban driven by duration', async () => {
|
||||
const ban = await convertEvent(bareCtx(), {
|
||||
kind: 'group_mute', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, operatorUin: 33333, duration: 600,
|
||||
} as QQEventVariant);
|
||||
expect(ban!.sub_type).toBe('ban');
|
||||
expect(ban!.duration).toBe(600);
|
||||
|
||||
const lift = await convertEvent(bareCtx(), {
|
||||
kind: 'group_mute', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, operatorUin: 33333, duration: 0,
|
||||
} as QQEventVariant);
|
||||
expect(lift!.sub_type).toBe('lift_ban');
|
||||
});
|
||||
|
||||
it('group_admin: set vs unset', async () => {
|
||||
const set = await convertEvent(bareCtx(), {
|
||||
kind: 'group_admin', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, set: true,
|
||||
} as QQEventVariant);
|
||||
expect(set!.notice_type).toBe('group_admin');
|
||||
expect(set!.sub_type).toBe('set');
|
||||
|
||||
const unset = await convertEvent(bareCtx(), {
|
||||
kind: 'group_admin', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, set: false,
|
||||
} as QQEventVariant);
|
||||
expect(unset!.sub_type).toBe('unset');
|
||||
});
|
||||
|
||||
it('friend_recall: passes through user + sequence-as-message_id', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'friend_recall', time: 1, selfUin: SELF_ID,
|
||||
userUin: PEER_UIN, msgSeq: 77,
|
||||
} as QQEventVariant);
|
||||
expect(out!.notice_type).toBe('friend_recall');
|
||||
expect(out!.user_id).toBe(PEER_UIN);
|
||||
expect(out!.message_id).toBe(77);
|
||||
});
|
||||
|
||||
it('group_recall: carries operator, author, message_id', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'group_recall', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
operatorUin: 33333, authorUin: PEER_UIN, msgSeq: 99,
|
||||
} as QQEventVariant);
|
||||
expect(out!.notice_type).toBe('group_recall');
|
||||
expect(out!.operator_id).toBe(33333);
|
||||
expect(out!.user_id).toBe(PEER_UIN);
|
||||
expect(out!.message_id).toBe(99);
|
||||
});
|
||||
|
||||
it('friend_poke: notice/notify/poke with target_id + action fields', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'friend_poke', time: 1, selfUin: SELF_ID,
|
||||
userUin: PEER_UIN, targetUin: SELF_ID,
|
||||
action: '戳了戳', suffix: '一下', actionImgUrl: 'http://x',
|
||||
} as QQEventVariant);
|
||||
expect(out!.notice_type).toBe('notify');
|
||||
expect(out!.sub_type).toBe('poke');
|
||||
expect(out!.target_id).toBe(SELF_ID);
|
||||
expect(out!.action).toBe('戳了戳');
|
||||
});
|
||||
|
||||
it('group_poke: same shape as friend_poke + group_id', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'group_poke', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, targetUin: SELF_ID,
|
||||
action: '戳', suffix: '', actionImgUrl: '',
|
||||
} as QQEventVariant);
|
||||
expect(out!.notice_type).toBe('notify');
|
||||
expect(out!.sub_type).toBe('poke');
|
||||
expect(out!.group_id).toBe(GROUP_ID);
|
||||
});
|
||||
|
||||
it('group_essence: add vs delete + carries random + sequence', async () => {
|
||||
const add = await convertEvent(bareCtx(), {
|
||||
kind: 'group_essence', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
senderUin: PEER_UIN, operatorUin: 33333, msgSeq: 50, random: 123,
|
||||
set: true,
|
||||
} as QQEventVariant);
|
||||
expect(add!.notice_type).toBe('essence');
|
||||
expect(add!.sub_type).toBe('add');
|
||||
expect(add!.random).toBe(123);
|
||||
expect(add!.message_seq).toBe(50);
|
||||
|
||||
const del = await convertEvent(bareCtx(), {
|
||||
kind: 'group_essence', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
senderUin: PEER_UIN, operatorUin: 33333, msgSeq: 50, random: 123,
|
||||
set: false,
|
||||
} as QQEventVariant);
|
||||
expect(del!.sub_type).toBe('delete');
|
||||
});
|
||||
|
||||
it('group_file_upload: emits group_upload with file metadata', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'group_file_upload', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
userUin: PEER_UIN, fileId: 'f1', fileName: 'doc.txt',
|
||||
fileSize: 1024, busId: 102,
|
||||
} as QQEventVariant);
|
||||
expect(out!.notice_type).toBe('group_upload');
|
||||
expect((out!.file as Record<string, unknown>).id).toBe('f1');
|
||||
expect((out!.file as Record<string, unknown>).size).toBe(1024);
|
||||
});
|
||||
|
||||
it('friend_add: emits friend_add notice', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'friend_add', time: 1, selfUin: SELF_ID, userUin: PEER_UIN,
|
||||
} as QQEventVariant);
|
||||
expect(out!.notice_type).toBe('friend_add');
|
||||
expect(out!.user_id).toBe(PEER_UIN);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertEvent — request kinds', () => {
|
||||
it('friend_request: request/friend with comment + flag', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'friend_request', time: 1, selfUin: SELF_ID,
|
||||
fromUin: PEER_UIN, message: '加个好友', flag: 'flag-abc',
|
||||
} as QQEventVariant);
|
||||
expect(out!.post_type).toBe('request');
|
||||
expect(out!.request_type).toBe('friend');
|
||||
expect(out!.comment).toBe('加个好友');
|
||||
expect(out!.flag).toBe('flag-abc');
|
||||
});
|
||||
|
||||
it('group_invite: request/group with sub_type defaulting to "invite"', async () => {
|
||||
const out = await convertEvent(bareCtx(), {
|
||||
kind: 'group_invite', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
fromUin: PEER_UIN, message: '邀请', flag: 'gflag', subType: '',
|
||||
} as QQEventVariant);
|
||||
expect(out!.post_type).toBe('request');
|
||||
expect(out!.request_type).toBe('group');
|
||||
expect(out!.sub_type).toBe('invite');
|
||||
|
||||
const withSubType = await convertEvent(bareCtx(), {
|
||||
kind: 'group_invite', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
|
||||
fromUin: PEER_UIN, message: '', flag: 'gflag', subType: 'add',
|
||||
} as QQEventVariant);
|
||||
expect(withSubType!.sub_type).toBe('add');
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertEvent — message elements (13 segment types)', () => {
|
||||
// Round-trips one element through elementsToOneBotSegments and
|
||||
// asserts the OneBot segment shape. Resolvers are wired only when
|
||||
// the element type needs them. JsonArray's index type is JsonValue
|
||||
// (a union); cast back to the segment shape so test bodies can read
|
||||
// `.type` and `.data` without typeguarding every line.
|
||||
type Segment = { type: string; data: Record<string, unknown> };
|
||||
async function segment(element: MessageElement, opts: Partial<ConverterContext> = {}): Promise<Segment> {
|
||||
const ctx = bareCtx(opts);
|
||||
const segments = await elementsToOneBotSegments(
|
||||
[element], false, PEER_UIN,
|
||||
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
|
||||
);
|
||||
return segments[0] as unknown as Segment;
|
||||
}
|
||||
|
||||
it('text -> { type:"text", data:{ text } }', async () => {
|
||||
const seg = await segment({ type: 'text', text: 'hello' });
|
||||
expect(seg).toEqual({ type: 'text', data: { text: 'hello' } });
|
||||
});
|
||||
|
||||
it('face -> { type:"face", data:{ id: stringified } }', async () => {
|
||||
const seg = await segment({ type: 'face', faceId: 12 });
|
||||
expect(seg).toEqual({ type: 'face', data: { id: '12' } });
|
||||
});
|
||||
|
||||
it('image: uses imageUrlResolver when wired, falls back to element.imageUrl', async () => {
|
||||
const seg = await segment(
|
||||
{ type: 'image', fileId: 'fid', imageUrl: 'http://fallback' },
|
||||
{ imageUrlResolver: () => 'http://resolved' },
|
||||
);
|
||||
expect(seg.type).toBe('image');
|
||||
expect((seg.data as Record<string, unknown>).url).toBe('http://resolved');
|
||||
expect((seg.data as Record<string, unknown>).file).toBe('fid');
|
||||
expect((seg.data as Record<string, unknown>).sub_type).toBe(0);
|
||||
expect((seg.data as Record<string, unknown>).summary).toBe('');
|
||||
});
|
||||
|
||||
it('image without resolver uses element.imageUrl', async () => {
|
||||
const seg = await segment({ type: 'image', fileId: 'fid', imageUrl: 'http://x' });
|
||||
expect((seg.data as Record<string, unknown>).url).toBe('http://x');
|
||||
});
|
||||
|
||||
it('image: forwards optional sub_type and summary for custom emoji/stickers', async () => {
|
||||
const seg = await segment({
|
||||
type: 'image',
|
||||
fileId: 'fid',
|
||||
imageUrl: 'http://x',
|
||||
subType: 1,
|
||||
summary: '[动画表情]',
|
||||
});
|
||||
expect(seg).toEqual({
|
||||
type: 'image',
|
||||
data: {
|
||||
url: 'http://x',
|
||||
file: 'fid',
|
||||
sub_type: 1,
|
||||
summary: '[动画表情]',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('at: targetUin -> qq string', async () => {
|
||||
const seg = await segment({ type: 'at', targetUin: PEER_UIN });
|
||||
expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } });
|
||||
});
|
||||
|
||||
it('at all: uid="all" -> qq:"all"', async () => {
|
||||
const seg = await segment({ type: 'at', uid: 'all', targetUin: 0 });
|
||||
expect((seg.data as Record<string, unknown>).qq).toBe('all');
|
||||
});
|
||||
|
||||
it('reply: replySeq is resolved through messageIdResolver when wired', async () => {
|
||||
const seg = await segment(
|
||||
{ type: 'reply', replySeq: 5 },
|
||||
{ messageIdResolver: () => 9999 },
|
||||
);
|
||||
expect(seg).toEqual({ type: 'reply', data: { id: '9999' } });
|
||||
});
|
||||
|
||||
it('reply: replySeq=0 -> id "0", no resolver call', async () => {
|
||||
let resolverCalls = 0;
|
||||
const seg = await segment(
|
||||
{ type: 'reply', replySeq: 0 },
|
||||
{ messageIdResolver: () => { resolverCalls++; return 1; } },
|
||||
);
|
||||
expect((seg.data as Record<string, unknown>).id).toBe('0');
|
||||
expect(resolverCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('record: uses mediaUrlResolver for url', async () => {
|
||||
const seg = await segment(
|
||||
{ type: 'record', fileName: 'a.silk', fileId: 'fid', url: 'fallback' },
|
||||
{ mediaUrlResolver: async () => 'resolved' },
|
||||
);
|
||||
expect(seg.type).toBe('record');
|
||||
expect((seg.data as Record<string, unknown>).url).toBe('resolved');
|
||||
expect((seg.data as Record<string, unknown>).file).toBe('a.silk');
|
||||
});
|
||||
|
||||
it('video: same shape as record', async () => {
|
||||
const seg = await segment(
|
||||
{ type: 'video', fileName: 'a.mp4', fileId: 'fid', url: 'fallback' },
|
||||
{ mediaUrlResolver: async () => 'resolved' },
|
||||
);
|
||||
expect(seg.type).toBe('video');
|
||||
expect((seg.data as Record<string, unknown>).url).toBe('resolved');
|
||||
});
|
||||
|
||||
it('json: text is forwarded as data.data', async () => {
|
||||
const seg = await segment({ type: 'json', text: '{"a":1}' });
|
||||
expect(seg).toEqual({ type: 'json', data: { data: '{"a":1}' } });
|
||||
});
|
||||
|
||||
it('xml: text + resid (defaults to 35)', async () => {
|
||||
const seg = await segment({ type: 'xml', text: '<x/>' });
|
||||
expect((seg.data as Record<string, unknown>).resid).toBe(35);
|
||||
|
||||
const seg2 = await segment({ type: 'xml', text: '<x/>', subType: 50 });
|
||||
expect((seg2.data as Record<string, unknown>).resid).toBe(50);
|
||||
});
|
||||
|
||||
it('file: name + size + id + url + file_hash, url via mediaUrlResolver', async () => {
|
||||
const seg = await segment(
|
||||
{ type: 'file', fileName: 'doc.pdf', fileSize: 7, fileId: 'fid', fileHash: 'h' },
|
||||
{ mediaUrlResolver: async () => 'http://download' },
|
||||
);
|
||||
expect(seg.type).toBe('file');
|
||||
expect(seg.data).toEqual({
|
||||
name: 'doc.pdf', size: 7, id: 'fid', url: 'http://download', file_hash: 'h',
|
||||
});
|
||||
});
|
||||
|
||||
it('mface: text + tab_id + sub_type', async () => {
|
||||
const seg = await segment({ type: 'mface', text: 'sticker', faceId: 7, subType: 2 });
|
||||
expect(seg).toEqual({ type: 'mface', data: { name: 'sticker', tab_id: 7, sub_type: 2 } });
|
||||
});
|
||||
|
||||
it('poke: subType forwarded as data.type', async () => {
|
||||
const seg = await segment({ type: 'poke', subType: 3 });
|
||||
expect(seg).toEqual({ type: 'poke', data: { type: 3 } });
|
||||
});
|
||||
|
||||
it('mediaSegmentSink fires once per image/record/video segment', async () => {
|
||||
const calls: string[] = [];
|
||||
const sink = (mediaType: string) => { calls.push(mediaType); };
|
||||
const ctx = bareCtx({
|
||||
mediaSegmentSink: sink as ConverterContext['mediaSegmentSink'],
|
||||
mediaUrlResolver: async () => '',
|
||||
});
|
||||
await elementsToOneBotSegments(
|
||||
[
|
||||
{ type: 'image', fileId: 'i', imageUrl: '' },
|
||||
{ type: 'record', fileName: 'r.silk', fileId: 'r' },
|
||||
{ type: 'video', fileName: 'v.mp4', fileId: 'v' },
|
||||
{ type: 'text', text: 'not media' },
|
||||
],
|
||||
true, GROUP_ID,
|
||||
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
|
||||
);
|
||||
expect(calls).toEqual(['image', 'record', 'video']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shapeEventForAdapter', () => {
|
||||
const baseEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message_sent' as const,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 7,
|
||||
user_id: SELF_ID,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
font: 0,
|
||||
sender: { user_id: SELF_ID, nickname: 'me', sex: 'unknown', age: 0 },
|
||||
};
|
||||
|
||||
it('drops self message_sent when adapter has reportSelfMessage=false', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||
expect(shapeEventForAdapter(baseEvent, opts)).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps self message_sent when adapter has reportSelfMessage=true', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||
expect(shaped).not.toBeNull();
|
||||
expect(shaped!.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('rewrites message to CQ string when format=string', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: true });
|
||||
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||
expect(shaped).not.toBeNull();
|
||||
expect(shaped!.message).toBe('hello');
|
||||
// raw_message is preserved untouched.
|
||||
expect(shaped!.raw_message).toBe('hello');
|
||||
});
|
||||
|
||||
it('keeps message as array when format=array (default)', () => {
|
||||
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||
expect(Array.isArray(shaped!.message)).toBe(true);
|
||||
});
|
||||
|
||||
it('defaults partially-deserialized adapters to array format and no self report', () => {
|
||||
const opts = resolveReportOptions({});
|
||||
expect(opts.messageFormat).toBe('array');
|
||||
expect(opts.reportSelfMessage).toBe(false);
|
||||
});
|
||||
|
||||
it('passes through non-message events unchanged', () => {
|
||||
const noticeEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
group_id: 1,
|
||||
user_id: 2,
|
||||
};
|
||||
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
|
||||
expect(shapeEventForAdapter(noticeEvent, opts)).toBe(noticeEvent);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildDispatchPayload + pickDispatchJson', () => {
|
||||
const messageEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 7,
|
||||
user_id: PEER_UIN,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
font: 0,
|
||||
sender: { user_id: PEER_UIN, nickname: 'peer', sex: 'unknown', age: 0 },
|
||||
};
|
||||
|
||||
const selfMessageEvent = { ...messageEvent, post_type: 'message_sent', user_id: SELF_ID };
|
||||
|
||||
const noticeEvent = {
|
||||
time: 1,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
group_id: 1,
|
||||
user_id: 2,
|
||||
};
|
||||
|
||||
it('builds at most two distinct JSON variants for a message event', () => {
|
||||
const payload = buildDispatchPayload(messageEvent);
|
||||
expect(payload.isSelfMessage).toBe(false);
|
||||
|
||||
const arr = JSON.parse(payload.arrayJson);
|
||||
const str = JSON.parse(payload.stringJson);
|
||||
expect(Array.isArray(arr.message)).toBe(true);
|
||||
expect(typeof str.message).toBe('string');
|
||||
expect(str.message).toBe('hello');
|
||||
expect(str.raw_message).toBe('hello');
|
||||
// every other field should be byte-identical
|
||||
const { message: _arrMsg, ...arrRest } = arr;
|
||||
const { message: _strMsg, ...strRest } = str;
|
||||
expect(arrRest).toEqual(strRest);
|
||||
});
|
||||
|
||||
it('flags self messages and uses identical JSON for non-message events', () => {
|
||||
const selfPayload = buildDispatchPayload(selfMessageEvent);
|
||||
expect(selfPayload.isSelfMessage).toBe(true);
|
||||
|
||||
const noticePayload = buildDispatchPayload(noticeEvent);
|
||||
expect(noticePayload.isSelfMessage).toBe(false);
|
||||
// Non-message events do not need a separate string variant.
|
||||
expect(noticePayload.arrayJson).toBe(noticePayload.stringJson);
|
||||
});
|
||||
|
||||
it('routes connections to the right pre-serialized variant in O(1)', () => {
|
||||
const payload = buildDispatchPayload(messageEvent);
|
||||
const arrayOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||
const stringOpt = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
|
||||
|
||||
expect(pickDispatchJson(payload, arrayOpt)).toBe(payload.arrayJson);
|
||||
expect(pickDispatchJson(payload, stringOpt)).toBe(payload.stringJson);
|
||||
});
|
||||
|
||||
it('drops self-message dispatches for adapters that opt out', () => {
|
||||
const payload = buildDispatchPayload(selfMessageEvent);
|
||||
const offOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||
expect(pickDispatchJson(payload, offOpt)).toBeNull();
|
||||
|
||||
const onOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||
const json = pickDispatchJson(payload, onOpt);
|
||||
expect(json).not.toBeNull();
|
||||
expect(JSON.parse(json!).post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('serializes only twice regardless of fan-out size', () => {
|
||||
const payload = buildDispatchPayload(messageEvent);
|
||||
// Mixed fleet of adapters with different formats / self-report options.
|
||||
const adapters = Array.from({ length: 50 }, (_, i) => i % 2 === 0
|
||||
? { messageFormat: 'array' as const, reportSelfMessage: false }
|
||||
: { messageFormat: 'string' as const, reportSelfMessage: true },
|
||||
);
|
||||
const seen = new Set(
|
||||
adapters
|
||||
.map((opts) => pickDispatchJson(payload, opts))
|
||||
.filter((j): j is string => j !== null),
|
||||
);
|
||||
// No matter the fan-out, only at most the two prebuilt strings appear.
|
||||
expect(seen.size).toBeLessThanOrEqual(2);
|
||||
expect(seen.has(payload.arrayJson)).toBe(true);
|
||||
expect(seen.has(payload.stringJson)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,206 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
|
||||
|
||||
// Wrap convertEvent in a vi.fn that delegates to the real impl by
|
||||
// default, so one test can override it to return null without making
|
||||
// the others lose the real conversion behavior.
|
||||
vi.mock('../src/onebot/event-converter', async () => {
|
||||
const actual = await vi.importActual<typeof import('../src/onebot/event-converter')>('../src/onebot/event-converter');
|
||||
return { ...actual, convertEvent: vi.fn(actual.convertEvent) };
|
||||
});
|
||||
|
||||
import { convertEvent, type ConverterContext } from '../src/onebot/event-converter';
|
||||
import { registerEventPipeline } from '../src/onebot/event-pipeline';
|
||||
import type { OneBotInstanceContext } from '../src/onebot/instance-context';
|
||||
import type {
|
||||
FriendMessage,
|
||||
GroupMessage,
|
||||
GroupMemberJoin,
|
||||
TempMessage,
|
||||
QQEventVariant,
|
||||
} from '@snowluma/bridge/events';
|
||||
import type { JsonObject, MessageMeta } from '../src/onebot/types';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
const GROUP_ID = 99999;
|
||||
|
||||
interface FakeBridge {
|
||||
events: BridgeEventBus;
|
||||
}
|
||||
|
||||
function makeFriendMessage(): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 11,
|
||||
msgId: 555,
|
||||
elements: [{ type: 'text', text: 'hi' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 22,
|
||||
msgId: 777,
|
||||
elements: [{ type: 'text', text: 'group' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeTempMessage(): TempMessage {
|
||||
return {
|
||||
kind: 'temp_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin: PEER_UIN,
|
||||
groupId: GROUP_ID,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 33,
|
||||
elements: [{ type: 'text', text: 'temp' }],
|
||||
};
|
||||
}
|
||||
|
||||
function makeMemberJoin(): GroupMemberJoin {
|
||||
return {
|
||||
kind: 'group_member_join',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
userUin: PEER_UIN,
|
||||
operatorUin: PEER_UIN,
|
||||
};
|
||||
}
|
||||
|
||||
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
ctx: OneBotInstanceContext;
|
||||
bus: BridgeEventBus;
|
||||
metaCalls: Array<{ id: number; meta: MessageMeta }>;
|
||||
dispatchCalls: JsonObject[];
|
||||
} {
|
||||
const bus = new BridgeEventBus();
|
||||
const fakeBridge: FakeBridge = { events: bus };
|
||||
const converterCtx: ConverterContext = {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
};
|
||||
const metaCalls: Array<{ id: number; meta: MessageMeta }> = [];
|
||||
const dispatchCalls: JsonObject[] = [];
|
||||
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: SELF_UIN,
|
||||
selfId: SELF_ID,
|
||||
bridge: fakeBridge as never,
|
||||
messageStore: {} as never,
|
||||
mediaStore: {} as never,
|
||||
converterCtx,
|
||||
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
|
||||
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
|
||||
dispatchEvent: (event) => { dispatchCalls.push(event); },
|
||||
...extra,
|
||||
};
|
||||
|
||||
return { ctx, bus, metaCalls, dispatchCalls };
|
||||
}
|
||||
|
||||
describe('registerEventPipeline', () => {
|
||||
it('caches meta and dispatches a converted event for friend_message', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
|
||||
expect(metaCalls).toHaveLength(1);
|
||||
expect(metaCalls[0].meta.isGroup).toBe(false);
|
||||
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
|
||||
expect(metaCalls[0].meta.sequence).toBe(11);
|
||||
expect(metaCalls[0].meta.random).toBe(555);
|
||||
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
expect(dispatchCalls[0].post_type).toBe('message');
|
||||
expect(dispatchCalls[0].message_type).toBe('private');
|
||||
});
|
||||
|
||||
it('caches meta and dispatches for group_message', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeGroupMessage());
|
||||
|
||||
expect(metaCalls[0].meta.isGroup).toBe(true);
|
||||
expect(metaCalls[0].meta.targetId).toBe(GROUP_ID);
|
||||
expect(dispatchCalls[0].message_type).toBe('group');
|
||||
});
|
||||
|
||||
it('caches meta with random=0 for temp_message and dispatches as private+sub_type=group', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeTempMessage());
|
||||
|
||||
expect(metaCalls[0].meta.isGroup).toBe(false);
|
||||
expect(metaCalls[0].meta.random).toBe(0);
|
||||
expect(dispatchCalls[0].message_type).toBe('private');
|
||||
expect(dispatchCalls[0].sub_type).toBe('group');
|
||||
});
|
||||
|
||||
it('dispatches notice events without seeding meta', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeMemberJoin());
|
||||
|
||||
expect(metaCalls).toHaveLength(0);
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
expect(dispatchCalls[0].notice_type).toBe('group_increase');
|
||||
});
|
||||
|
||||
it('returns a disposer that fully unsubscribes', async () => {
|
||||
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
|
||||
const dispose = registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
|
||||
dispose();
|
||||
await bus.emit(makeFriendMessage());
|
||||
// No new calls after dispose.
|
||||
expect(dispatchCalls).toHaveLength(1);
|
||||
expect(metaCalls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('dispatches a separate event for every kind in parallel', async () => {
|
||||
const { ctx, bus, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
const events: QQEventVariant[] = [makeFriendMessage(), makeGroupMessage(), makeMemberJoin(), makeTempMessage()];
|
||||
await Promise.all(events.map((e) => bus.emit(e)));
|
||||
|
||||
expect(dispatchCalls).toHaveLength(events.length);
|
||||
});
|
||||
|
||||
it('skips dispatch for kinds without a converter mapping (no crash)', async () => {
|
||||
// Force convertEvent to return null for one call; assert the pipeline
|
||||
// honours the `if (!converted) return;` guard.
|
||||
vi.mocked(convertEvent).mockResolvedValueOnce(null);
|
||||
const { ctx, bus, dispatchCalls } = makeContext();
|
||||
registerEventPipeline(ctx);
|
||||
|
||||
await bus.emit(makeFriendMessage());
|
||||
expect(dispatchCalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,213 +0,0 @@
|
||||
// Tests for the Event0x2DC subType=16 (GroupMsgEmojiLike) end-to-end:
|
||||
// - decoder strips the 7-byte prefix and decodes GroupReactNotify
|
||||
// - field13==35 yields a GroupMsgEmojiLikeEvent
|
||||
// - field13!=35 surfaces under MsgPush.Unknown and emits nothing
|
||||
// - converter shape matches the gocqhttp / NapCat extension layout
|
||||
// - formatEvent prints something readable in the [Event] log
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { GroupReactNotify } from '@snowluma/proto-defs/notify';
|
||||
import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc';
|
||||
import type { MsgPushContext } from '@snowluma/bridge/msg-push/context';
|
||||
import { IdentityService } from '@snowluma/bridge/identity-service';
|
||||
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/bridge/events';
|
||||
import { convertGroupMsgEmojiLike } from '../src/onebot/event-converter/to-notice';
|
||||
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/onebot/message-id';
|
||||
import { formatEvent } from '@snowluma/bridge/format';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
|
||||
function makeIdentity(): IdentityService {
|
||||
return IdentityService.memory(SELF_UIN);
|
||||
}
|
||||
|
||||
/** Build the raw bytes QQ would push into ctx.content for subType=16:
|
||||
* a 7-byte magic prefix followed by an encoded GroupReactNotify. */
|
||||
function buildReactContent(notify: Record<string, unknown>): Uint8Array {
|
||||
const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]);
|
||||
const body = protobuf_encode<GroupReactNotify>(notify as GroupReactNotify);
|
||||
const out = new Uint8Array(prefix.length + body.length);
|
||||
out.set(prefix, 0);
|
||||
out.set(body, prefix.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
|
||||
return {
|
||||
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
|
||||
fromUin: 0,
|
||||
fromUid: '',
|
||||
selfUin: Number(SELF_UIN),
|
||||
content,
|
||||
body: undefined,
|
||||
responseHead: undefined,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
|
||||
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
|
||||
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 35,
|
||||
groupReactionData: {
|
||||
data: {
|
||||
data: {
|
||||
groupReactionTarget: { seq: 4242n },
|
||||
groupReactionDataContent: {
|
||||
code: '76',
|
||||
count: 1,
|
||||
operatorUid: 'u_operator_xxx',
|
||||
type: 1, // add
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
|
||||
expect(event).toBeDefined();
|
||||
expect(event.kind).toBe('group_msg_emoji_like');
|
||||
expect(event.groupId).toBe(GROUP_ID);
|
||||
expect(event.operatorUid).toBe('u_operator_xxx');
|
||||
expect(event.emojiId).toBe('76');
|
||||
expect(event.msgSeq).toBe(4242);
|
||||
expect(event.count).toBe(1);
|
||||
expect(event.isAdd).toBe(true);
|
||||
});
|
||||
|
||||
it('decodes type=2 as react remove (isAdd=false)', () => {
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 35,
|
||||
groupReactionData: {
|
||||
data: {
|
||||
data: {
|
||||
groupReactionTarget: { seq: 1n },
|
||||
groupReactionDataContent: {
|
||||
code: '⭐',
|
||||
count: 1,
|
||||
operatorUid: 'u_x',
|
||||
type: 2,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
|
||||
expect(event.isAdd).toBe(false);
|
||||
expect(event.emojiId).toBe('⭐');
|
||||
});
|
||||
|
||||
it('drops the packet and logs to MsgPush.Unknown when field13 is not 35', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 99, // not 35
|
||||
groupReactionData: {
|
||||
data: { data: { groupReactionDataContent: { code: 'x', operatorUid: 'u_y' } } },
|
||||
},
|
||||
});
|
||||
|
||||
const result = decodeEvent0x2DC(makeCtx(content));
|
||||
unsub();
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
const unknown = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && /field13=99/.test(e.message));
|
||||
expect(unknown).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns empty when content is shorter than the prefix length', () => {
|
||||
const tooShort = new Uint8Array([1, 2, 3]); // < 7 bytes
|
||||
expect(decodeEvent0x2DC(makeCtx(tooShort))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
|
||||
const baseEvent: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: 1735000000,
|
||||
selfUin: 10001,
|
||||
groupId: 123456789,
|
||||
operatorUin: 99999,
|
||||
operatorUid: 'u_x',
|
||||
msgSeq: 4242,
|
||||
emojiId: '76',
|
||||
count: 1,
|
||||
isAdd: true,
|
||||
};
|
||||
|
||||
// Real production wiring puts a hashMessageIdInt32-based resolver
|
||||
// on the ctx; mirror that so message_id is the same value the
|
||||
// bot would have minted for the original message.
|
||||
const ctx = {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: (_isGroup: boolean, sessionId: number, sequence: number, eventName: string) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName),
|
||||
mediaSegmentSink: null,
|
||||
} as never;
|
||||
|
||||
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
|
||||
expect(out.post_type).toBe('notice');
|
||||
expect(out.notice_type).toBe('group_msg_emoji_like');
|
||||
expect(out.sub_type).toBe('add');
|
||||
expect(out.group_id).toBe(123456789);
|
||||
expect(out.user_id).toBe(99999);
|
||||
expect(out.operator_id).toBe(99999);
|
||||
expect(out.message_seq).toBe(4242);
|
||||
expect(out.message_id).toBe(hashMessageIdInt32(4242, 123456789, GROUP_MESSAGE_EVENT));
|
||||
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
|
||||
});
|
||||
|
||||
it('flips sub_type to remove when isAdd is false', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
|
||||
expect(out.sub_type).toBe('remove');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatEvent — group_msg_emoji_like', () => {
|
||||
let savedLevel: string | undefined;
|
||||
beforeEach(() => { savedLevel = process.env.SNOWLUMA_LOG_LEVEL; });
|
||||
afterEach(() => {
|
||||
if (savedLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = savedLevel;
|
||||
});
|
||||
|
||||
it('renders a one-line summary with group, operator and emoji id', () => {
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([{
|
||||
groupId: GROUP_ID, groupName: 'TestGroup', remark: '',
|
||||
memberCount: 1, memberMax: 500, members: new Map(),
|
||||
}]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [{
|
||||
uin: 99999, uid: 'u_x', nickname: 'Alice', card: '',
|
||||
role: 'member', level: 0, title: '',
|
||||
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
|
||||
}]);
|
||||
|
||||
const event: QQEventVariant = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: 0, selfUin: Number(SELF_UIN),
|
||||
groupId: GROUP_ID,
|
||||
operatorUin: 99999, operatorUid: 'u_x',
|
||||
msgSeq: 100, emojiId: '76', count: 1, isAdd: true,
|
||||
};
|
||||
|
||||
const line = formatEvent(identity, event);
|
||||
expect(line).toBeDefined();
|
||||
expect(line).toContain('TestGroup');
|
||||
expect(line).toContain('Alice');
|
||||
expect(line).toContain('[76]');
|
||||
expect(line).toContain('msgSeq=100');
|
||||
});
|
||||
});
|
||||
@@ -1,149 +0,0 @@
|
||||
// Tests for HTTP server adapter content-type parsing (POST body).
|
||||
// Covers: application/x-www-form-urlencoded, application/json,
|
||||
// no content-type fallback, and unsupported content-type rejection.
|
||||
|
||||
import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest';
|
||||
import http from 'http';
|
||||
import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter';
|
||||
import type { NetworkAdapterContext } from '../src/onebot/network/adapter';
|
||||
import type { HttpServerNetwork } from '../src/onebot/types';
|
||||
|
||||
// ─── Helpers ───
|
||||
|
||||
function fakeCtx(handleFn: (action: string, params: Record<string, unknown>) => unknown): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: {
|
||||
handle: vi.fn(async (action: string, params: Record<string, unknown>) => {
|
||||
const data = handleFn(action, params);
|
||||
return { status: 'ok', retcode: 0, data };
|
||||
}),
|
||||
} as any,
|
||||
buildLifecycleEvent: vi.fn(() => ({})),
|
||||
buildHeartbeatEvent: vi.fn(() => ({})),
|
||||
};
|
||||
}
|
||||
|
||||
function post(port: number, path: string, body: string, headers: Record<string, string> = {}): Promise<{ status: number; body: any }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () => {
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
try {
|
||||
resolve({ status: res.statusCode!, body: JSON.parse(raw) });
|
||||
} catch {
|
||||
resolve({ status: res.statusCode!, body: raw });
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Tests ───
|
||||
|
||||
describe('HttpServerAdapter content-type parsing', () => {
|
||||
let adapter: HttpServerAdapter;
|
||||
let handleFn: ReturnType<typeof vi.fn<(action: string, params: Record<string, unknown>) => unknown>>;
|
||||
const PORT = 19876;
|
||||
|
||||
beforeAll(async () => {
|
||||
handleFn = vi.fn((_action: string, params: Record<string, unknown>) => params);
|
||||
const ctx = fakeCtx(handleFn);
|
||||
const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false };
|
||||
adapter = new HttpServerAdapter('test-http', config, ctx);
|
||||
adapter.open();
|
||||
// Wait for server to be listening
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
adapter.close();
|
||||
});
|
||||
|
||||
it('should parse application/json body', async () => {
|
||||
const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), {
|
||||
'content-type': 'application/json',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('ok');
|
||||
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' });
|
||||
});
|
||||
|
||||
it('should parse application/x-www-form-urlencoded body', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'group_id=456&message=hello';
|
||||
const res = await post(PORT, '/send_message', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('ok');
|
||||
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' });
|
||||
});
|
||||
|
||||
it('should JSON-parse values in urlencoded body', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'user_id=789&data={"nested":true}';
|
||||
const res = await post(PORT, '/get_info', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } });
|
||||
});
|
||||
|
||||
it('should extract action from urlencoded body when path has no action', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'action=get_status&key=value';
|
||||
const res = await post(PORT, '/', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' });
|
||||
});
|
||||
|
||||
it('should extract echo from urlencoded body', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'action=test_action&echo=12345&foo=bar';
|
||||
const res = await post(PORT, '/', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.echo).toBe(12345);
|
||||
expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' });
|
||||
});
|
||||
|
||||
it('should reject unsupported content-type with 400', async () => {
|
||||
const res = await post(PORT, '/send_message', '<xml></xml>', {
|
||||
'content-type': 'application/xml',
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.wording).toContain('unsupported content-type');
|
||||
});
|
||||
|
||||
it('should reject invalid JSON with explicit application/json content-type', async () => {
|
||||
const res = await post(PORT, '/send_message', 'not-json{{{', {
|
||||
'content-type': 'application/json',
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.wording).toContain('invalid json');
|
||||
});
|
||||
|
||||
it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'action=fallback_action¶m1=value1';
|
||||
const res = await post(PORT, '/', body, {});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' });
|
||||
});
|
||||
|
||||
it('should parse JSON when no content-type and body is valid JSON', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = JSON.stringify({ action: 'json_action', params: { x: 1 } });
|
||||
const res = await post(PORT, '/', body, {});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 });
|
||||
});
|
||||
});
|
||||
@@ -1,141 +0,0 @@
|
||||
// Hot-reload tests for HttpServerAdapter — pins the contract that
|
||||
// `reload({ accessToken: <new> })` must take effect on the very next
|
||||
// request without the listener being torn down. Earlier the adapter
|
||||
// captured `accessToken` into a `startServer()` closure and relied on
|
||||
// `bindingSignature` to trigger a `close()` + `open()` round-trip on
|
||||
// token change; that race-prone path is gone and `handleRequest` now
|
||||
// reads `this.config.accessToken` per request.
|
||||
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest';
|
||||
import http from 'http';
|
||||
import type { AddressInfo } from 'net';
|
||||
import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter';
|
||||
import { NetworkReloadType, type NetworkAdapterContext } from '../src/onebot/network/adapter';
|
||||
import type { HttpServerNetwork } from '../src/onebot/types';
|
||||
|
||||
function fakeCtx(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: {
|
||||
handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { online: true } })),
|
||||
} as any,
|
||||
buildLifecycleEvent: vi.fn(() => ({})),
|
||||
buildHeartbeatEvent: vi.fn(() => ({})),
|
||||
};
|
||||
}
|
||||
|
||||
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<{ status: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
{ hostname: '127.0.0.1', port, path, method: 'GET', headers },
|
||||
(res) => {
|
||||
res.on('data', () => { /* drain */ });
|
||||
res.on('end', () => resolve({ status: res.statusCode! }));
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// Wait until the underlying http.Server has bound its port; tests that
|
||||
// hit the socket too early get ECONNREFUSED on slow CI hosts.
|
||||
async function waitForListen(adapter: HttpServerAdapter): Promise<number> {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const server = (adapter as any).server as http.Server | null;
|
||||
const addr = server?.address() as AddressInfo | null | undefined;
|
||||
if (addr && typeof addr === 'object') return addr.port;
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
throw new Error('http server never started listening');
|
||||
}
|
||||
|
||||
describe('HttpServerAdapter — accessToken hot reload', () => {
|
||||
let adapter: HttpServerAdapter | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
adapter?.close();
|
||||
adapter = null;
|
||||
});
|
||||
|
||||
it('a swapped accessToken authorizes the new token on the next request — no listener re-bind', async () => {
|
||||
const ctx = fakeCtx();
|
||||
// port=0 → OS-assigned; the swap proves no re-bind happens because
|
||||
// a re-bind would land on a different port and `waitForListen`
|
||||
// would diverge from the original.
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'hot', port: 0, enabled: true, accessToken: 'tok-1',
|
||||
messageFormat: 'array', reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter('hot', config, ctx);
|
||||
adapter.open();
|
||||
const portBefore = await waitForListen(adapter);
|
||||
|
||||
// Sanity: old token authorizes, anything else 401s.
|
||||
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(200);
|
||||
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(401);
|
||||
|
||||
// Hot-swap the token.
|
||||
await adapter.reload({ ...config, accessToken: 'tok-2' });
|
||||
|
||||
// Same port (no re-bind) — and the new token must take effect on
|
||||
// the very next request.
|
||||
const portAfter = ((adapter as any).server as http.Server).address() as AddressInfo;
|
||||
expect(portAfter.port).toBe(portBefore);
|
||||
|
||||
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(401);
|
||||
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(200);
|
||||
});
|
||||
|
||||
it('clearing accessToken to empty disables auth on the next request', async () => {
|
||||
const ctx = fakeCtx();
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'hot-clear', port: 0, enabled: true, accessToken: 'tok-1',
|
||||
messageFormat: 'array', reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter('hot-clear', config, ctx);
|
||||
adapter.open();
|
||||
const port = await waitForListen(adapter);
|
||||
|
||||
expect((await get(port, '/')).status).toBe(401); // no token header → 401
|
||||
|
||||
await adapter.reload({ ...config, accessToken: '' });
|
||||
|
||||
expect((await get(port, '/')).status).toBe(200); // auth disabled
|
||||
});
|
||||
|
||||
it('setting accessToken from empty enforces auth on the next request', async () => {
|
||||
const ctx = fakeCtx();
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'hot-add', port: 0, enabled: true,
|
||||
messageFormat: 'array', reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter('hot-add', config, ctx);
|
||||
adapter.open();
|
||||
const port = await waitForListen(adapter);
|
||||
|
||||
expect((await get(port, '/')).status).toBe(200); // no auth configured
|
||||
|
||||
await adapter.reload({ ...config, accessToken: 'tok-new' });
|
||||
|
||||
expect((await get(port, '/')).status).toBe(401); // auth now required
|
||||
expect((await get(port, '/', { authorization: 'Bearer tok-new' })).status).toBe(200);
|
||||
});
|
||||
|
||||
it('changing only accessToken returns NetworkReloadType.Normal — no Reopened/Closed', async () => {
|
||||
const ctx = fakeCtx();
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'hot-type', port: 0, enabled: true, accessToken: 'a',
|
||||
messageFormat: 'array', reportSelfMessage: false,
|
||||
};
|
||||
adapter = new HttpServerAdapter('hot-type', config, ctx);
|
||||
adapter.open();
|
||||
await waitForListen(adapter);
|
||||
|
||||
const reloadType = await adapter.reload({ ...config, accessToken: 'b' });
|
||||
// Without re-binding, the adapter reports `Normal` — anything but
|
||||
// `Reopened` / `Closed` is acceptable; we mostly care that nothing
|
||||
// touched the listener.
|
||||
expect(reloadType).toBe(NetworkReloadType.Normal);
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { MediaIndexer } from '../src/onebot/media-indexer';
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
|
||||
function makeMediaStore() {
|
||||
return {
|
||||
rememberImage: vi.fn(),
|
||||
rememberRecord: vi.fn(),
|
||||
rememberVideo: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('MediaIndexer', () => {
|
||||
it('image: maps element fields into rememberImage with file fallback to fileId', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
type: 'image',
|
||||
fileId: 'img-fid',
|
||||
fileSize: 1024,
|
||||
subType: 1,
|
||||
summary: '[image]',
|
||||
imageUrl: 'http://orig',
|
||||
md5Hex: 'abcd',
|
||||
sha1Hex: 'efgh',
|
||||
width: 800,
|
||||
height: 600,
|
||||
picFormat: 1000,
|
||||
};
|
||||
indexer.remember('image', element, { url: 'http://x', file: '' }, true, 99999);
|
||||
|
||||
expect(store.rememberImage).toHaveBeenCalledOnce();
|
||||
const arg = store.rememberImage.mock.calls[0]![0];
|
||||
expect(arg).toMatchObject({
|
||||
file: 'img-fid', // data.file was '', fell back to element.fileId
|
||||
url: 'http://x',
|
||||
fileSize: 1024,
|
||||
subType: 1,
|
||||
summary: '[image]',
|
||||
imageUrl: 'http://orig',
|
||||
isGroup: true,
|
||||
sessionId: 99999,
|
||||
md5Hex: 'abcd',
|
||||
sha1Hex: 'efgh',
|
||||
width: 800,
|
||||
height: 600,
|
||||
picFormat: 1000,
|
||||
});
|
||||
});
|
||||
|
||||
it('record: maps element fields into rememberRecord with file fallback chain', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
type: 'record',
|
||||
fileId: 'rec-fid',
|
||||
fileName: 'voice.amr',
|
||||
fileSize: 2048,
|
||||
duration: 5,
|
||||
fileHash: 'h',
|
||||
mediaNode: { fileUuid: 'uuid' },
|
||||
md5Hex: 'm',
|
||||
sha1Hex: 's',
|
||||
voiceFormat: 1,
|
||||
};
|
||||
indexer.remember('record', element, { url: 'http://r', file: '' }, false, 12345);
|
||||
|
||||
const arg = store.rememberRecord.mock.calls[0]![0];
|
||||
expect(arg.file).toBe('voice.amr'); // data.file '' → element.fileName
|
||||
expect(arg.fileId).toBe('rec-fid');
|
||||
expect(arg.duration).toBe(5);
|
||||
expect(arg.isGroup).toBe(false);
|
||||
expect(arg.sessionId).toBe(12345);
|
||||
expect(arg.voiceFormat).toBe(1);
|
||||
});
|
||||
|
||||
it('video: maps element fields into rememberVideo', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
type: 'video',
|
||||
fileId: 'vid-fid',
|
||||
fileName: 'clip.mp4',
|
||||
fileSize: 99999,
|
||||
duration: 30,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
videoFormat: 2,
|
||||
};
|
||||
indexer.remember('video', element, { url: 'http://v', file: 'override.mp4' }, true, 11111);
|
||||
|
||||
const arg = store.rememberVideo.mock.calls[0]![0];
|
||||
expect(arg.file).toBe('override.mp4'); // data.file used when non-empty
|
||||
expect(arg.fileId).toBe('vid-fid');
|
||||
expect(arg.duration).toBe(30);
|
||||
expect(arg.width).toBe(1920);
|
||||
expect(arg.videoFormat).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = { type: 'record', fileId: 'only-fid' };
|
||||
indexer.remember('record', element, { url: '', file: '' }, false, 1);
|
||||
expect(store.rememberRecord.mock.calls[0]![0].file).toBe('only-fid');
|
||||
});
|
||||
|
||||
it('defaults missing numeric fields to 0 / missing strings to ""', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
|
||||
const arg = store.rememberImage.mock.calls[0]![0];
|
||||
expect(arg.fileSize).toBe(0);
|
||||
expect(arg.subType).toBe(0);
|
||||
expect(arg.summary).toBe('');
|
||||
expect(arg.imageUrl).toBe('');
|
||||
});
|
||||
|
||||
it('only the matching rememberX is called', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
|
||||
expect(store.rememberImage).toHaveBeenCalledOnce();
|
||||
expect(store.rememberRecord).not.toHaveBeenCalled();
|
||||
expect(store.rememberVideo).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,318 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { MediaStore } from '../src/onebot/media-store';
|
||||
import { convertEvent, type ConverterContext } from '../src/onebot/event-converter';
|
||||
import type { GroupMessage, FriendMessage, MessageElement } from '@snowluma/bridge/events';
|
||||
|
||||
const SELF_ID = 10001;
|
||||
const PEER_UIN = 22222;
|
||||
const GROUP_ID = 99999;
|
||||
|
||||
function imageElement(overrides: Partial<MessageElement> = {}): MessageElement {
|
||||
return {
|
||||
type: 'image',
|
||||
fileId: 'abc.png',
|
||||
fileSize: 4242,
|
||||
imageUrl: 'https://example.com/abc.png',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function recordElement(overrides: Partial<MessageElement> = {}): MessageElement {
|
||||
return {
|
||||
type: 'record',
|
||||
fileId: 'uuid-base64-fake',
|
||||
fileName: 'silk_test.amr',
|
||||
fileSize: 1024,
|
||||
duration: 3,
|
||||
fileHash: 'deadbeef',
|
||||
mediaNode: { fileUuid: 'uuid-base64-fake', storeId: 1 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroupMessage(elements: MessageElement[]): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
senderCard: '',
|
||||
senderRole: 'member',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFriendMessage(elements: MessageElement[]): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
senderUin: PEER_UIN,
|
||||
senderNick: 'peer',
|
||||
msgSeq: 1,
|
||||
msgId: 1,
|
||||
elements,
|
||||
};
|
||||
}
|
||||
|
||||
function tempDbPath(label: string): string {
|
||||
return path.join('data', 'test', `media-${label}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
}
|
||||
|
||||
describe('MediaStore basic semantics', () => {
|
||||
const dbs: string[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
dbs.length = 0;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const dbPath of dbs) {
|
||||
for (const ext of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function open(label: string, max?: number): MediaStore {
|
||||
const dbPath = tempDbPath(label);
|
||||
dbs.push(dbPath);
|
||||
return max !== undefined ? new MediaStore(dbPath, max) : new MediaStore(dbPath);
|
||||
}
|
||||
|
||||
it('indexes images by file, fileName, and url', () => {
|
||||
const store = open('img-keys');
|
||||
store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 4242,
|
||||
fileName: 'abc.png',
|
||||
subType: 0,
|
||||
summary: '',
|
||||
imageUrl: 'https://example.com/abc.png',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
|
||||
expect(store.findImage('abc.png')?.fileSize).toBe(4242);
|
||||
expect(store.findImage('https://example.com/abc.png')?.url).toBe('https://example.com/abc.png');
|
||||
expect(store.findImage('missing.png')).toBeNull();
|
||||
expect(store.findImage('')).toBeNull();
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('indexes records by file, fileName, fileId, and url', () => {
|
||||
const store = open('rec-keys');
|
||||
store.rememberRecord({
|
||||
file: 'silk_test.amr',
|
||||
fileId: 'uuid-base64-fake',
|
||||
url: 'https://example.com/voice.amr',
|
||||
fileSize: 1024,
|
||||
fileName: 'silk_test.amr',
|
||||
duration: 3,
|
||||
fileHash: 'deadbeef',
|
||||
mediaNode: { fileUuid: 'uuid-base64-fake' },
|
||||
isGroup: false,
|
||||
sessionId: PEER_UIN,
|
||||
});
|
||||
|
||||
expect(store.findRecord('silk_test.amr')?.duration).toBe(3);
|
||||
expect(store.findRecord('uuid-base64-fake')?.fileId).toBe('uuid-base64-fake');
|
||||
expect(store.findRecord('https://example.com/voice.amr')?.url).toBe('https://example.com/voice.amr');
|
||||
expect(store.findRecord('nope')).toBeNull();
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('updates URLs in place across all alias keys', () => {
|
||||
const store = open('url-update');
|
||||
store.rememberRecord({
|
||||
file: 'silk_test.amr',
|
||||
fileId: 'uuid-base64-fake',
|
||||
url: '',
|
||||
fileSize: 1024,
|
||||
fileName: 'silk_test.amr',
|
||||
duration: 3,
|
||||
fileHash: '',
|
||||
mediaNode: { fileUuid: 'uuid-base64-fake' },
|
||||
isGroup: false,
|
||||
sessionId: PEER_UIN,
|
||||
});
|
||||
store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
|
||||
|
||||
expect(store.findRecord('silk_test.amr')?.url).toBe('https://refreshed.example.com/voice.amr');
|
||||
expect(store.findRecord('uuid-base64-fake')?.url).toBe('https://refreshed.example.com/voice.amr');
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('survives close+reopen against the same db path', () => {
|
||||
const dbPath = tempDbPath('persist');
|
||||
dbs.push(dbPath);
|
||||
|
||||
{
|
||||
const store = new MediaStore(dbPath);
|
||||
store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 99,
|
||||
fileName: 'abc.png',
|
||||
subType: 0,
|
||||
summary: '',
|
||||
imageUrl: 'https://example.com/abc.png',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
store.close();
|
||||
}
|
||||
|
||||
{
|
||||
const store = new MediaStore(dbPath);
|
||||
const found = store.findImage('abc.png');
|
||||
expect(found).not.toBeNull();
|
||||
expect(found!.fileSize).toBe(99);
|
||||
// Alias index must also persist.
|
||||
expect(store.findImage('https://example.com/abc.png')?.fileSize).toBe(99);
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('evicts old entries beyond the configured cap', () => {
|
||||
// EVICT_EVERY_N_REMEMBERS = 64 inside the store; we exercise the eviction
|
||||
// path by writing well past the cap so it triggers at least once.
|
||||
const cap = 80;
|
||||
const store = open('evict', cap);
|
||||
for (let i = 0; i < 200; i++) {
|
||||
store.rememberImage({
|
||||
file: `file-${i}.png`,
|
||||
url: `https://example.com/${i}.png`,
|
||||
fileSize: i,
|
||||
fileName: `file-${i}.png`,
|
||||
subType: 0,
|
||||
summary: '',
|
||||
imageUrl: '',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
}
|
||||
const { images } = store.size();
|
||||
expect(images).toBeLessThanOrEqual(cap);
|
||||
// Most recent entries should still be present.
|
||||
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertEvent media segment sink → MediaStore wiring', () => {
|
||||
const dbs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dbPath of dbs) {
|
||||
for (const ext of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
dbs.length = 0;
|
||||
});
|
||||
|
||||
it('emits sink invocations for image segments with the right context', async () => {
|
||||
const sinkCalls: Array<{ type: string; isGroup: boolean; sessionId: number; file: string }> = [];
|
||||
const ctx: ConverterContext = {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: (type, _element, data, isGroup, sessionId) => {
|
||||
sinkCalls.push({ type, isGroup, sessionId, file: String(data.file ?? '') });
|
||||
},
|
||||
};
|
||||
|
||||
await convertEvent(ctx, makeGroupMessage([imageElement()]));
|
||||
await convertEvent(ctx, makeFriendMessage([recordElement()]));
|
||||
|
||||
expect(sinkCalls).toEqual([
|
||||
{ type: 'image', isGroup: true, sessionId: GROUP_ID, file: 'abc.png' },
|
||||
{ type: 'record', isGroup: false, sessionId: PEER_UIN, file: 'silk_test.amr' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets the sink populate a MediaStore that get_image-style lookups can use', async () => {
|
||||
const dbPath = tempDbPath('sink');
|
||||
dbs.push(dbPath);
|
||||
|
||||
const store = new MediaStore(dbPath);
|
||||
const ctx: ConverterContext = {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: (element) => element.imageUrl ?? '',
|
||||
mediaUrlResolver: async (element) => element.url ?? '',
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: (type, element, data, isGroup, sessionId) => {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
if (type === 'image') {
|
||||
store.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
isGroup,
|
||||
sessionId,
|
||||
});
|
||||
} else {
|
||||
store.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
await convertEvent(ctx, makeGroupMessage([imageElement()]));
|
||||
await convertEvent(ctx, makeFriendMessage([recordElement()]));
|
||||
|
||||
const img = store.findImage('abc.png');
|
||||
expect(img).not.toBeNull();
|
||||
expect(img!.url).toBe('https://example.com/abc.png');
|
||||
expect(img!.fileSize).toBe(4242);
|
||||
expect(img!.isGroup).toBe(true);
|
||||
expect(img!.sessionId).toBe(GROUP_ID);
|
||||
|
||||
const rec = store.findRecord('silk_test.amr');
|
||||
expect(rec).not.toBeNull();
|
||||
expect(rec!.fileId).toBe('uuid-base64-fake');
|
||||
expect(rec!.duration).toBe(3);
|
||||
expect(rec!.isGroup).toBe(false);
|
||||
expect(rec!.sessionId).toBe(PEER_UIN);
|
||||
// Alias lookup by fileUuid still works.
|
||||
expect(store.findRecord('uuid-base64-fake')?.fileName).toBe('silk_test.amr');
|
||||
store.close();
|
||||
});
|
||||
|
||||
it('does not invoke the sink when no media segments are present', async () => {
|
||||
let calls = 0;
|
||||
const ctx: ConverterContext = {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: () => { calls++; },
|
||||
};
|
||||
await convertEvent(ctx, makeGroupMessage([{ type: 'text', text: 'hello' }]));
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,147 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { MediaUrlResolver } from '../src/onebot/media-url-resolver';
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
|
||||
// Minimal stand-ins for the two collaborators. Each test wires whatever
|
||||
// subset of Bridge methods the element type exercises.
|
||||
//
|
||||
// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl,
|
||||
// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl,
|
||||
// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here
|
||||
// builds an `apis.groupFile` stub directly so tests can keep asserting
|
||||
// "which file/url helper got called" without going through the
|
||||
// `mockBridge` shared fixture.
|
||||
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
|
||||
return {
|
||||
apis: {
|
||||
groupFile: {
|
||||
getUrl: overrides.getUrl ?? vi.fn(async () => 'http://group/file'),
|
||||
getPrivateUrl: overrides.getPrivateUrl ?? vi.fn(async () => 'http://private/file'),
|
||||
getPttUrl: overrides.getPttUrl ?? vi.fn(async () => 'http://group/ptt'),
|
||||
getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => 'http://private/ptt'),
|
||||
getVideoUrl: overrides.getVideoUrl ?? vi.fn(async () => 'http://group/video'),
|
||||
getPrivateVideoUrl: overrides.getPrivateVideoUrl ?? vi.fn(async () => 'http://private/video'),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeRkey(overrides: { resolveMediaUrl?: ReturnType<typeof vi.fn> } = {}) {
|
||||
return {
|
||||
resolveMediaUrl: overrides.resolveMediaUrl ?? vi.fn(async (_bridge, el: MessageElement) => el.url ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
const MEDIA_NODE = { fileUuid: 'uuid-1' };
|
||||
|
||||
describe('MediaUrlResolver — file element', () => {
|
||||
let bridge: ReturnType<typeof makeBridge>;
|
||||
let rkey: ReturnType<typeof makeRkey>;
|
||||
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
|
||||
|
||||
it('group + fileId: uses fetchGroupFileUrl, then applies rkey', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.apis.groupFile.getUrl).toHaveBeenCalledWith(12345, 'fid-x');
|
||||
expect(element.url).toBe('http://group/file');
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
expect(out).toBe('http://group/file');
|
||||
});
|
||||
|
||||
it('c2c + fileId + fileHash: uses fetchPrivateFileUrl', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.apis.groupFile.getPrivateUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y');
|
||||
expect(element.url).toBe('http://private/file');
|
||||
});
|
||||
|
||||
it('c2c + fileId but no fileHash: sets url to empty string (no bridge call)', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.apis.groupFile.getPrivateUrl).not.toHaveBeenCalled();
|
||||
expect(element.url).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MediaUrlResolver — record / video element', () => {
|
||||
let bridge: ReturnType<typeof makeBridge>;
|
||||
let rkey: ReturnType<typeof makeRkey>;
|
||||
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
|
||||
|
||||
it('group record: uses fetchGroupPttUrlByNode', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.apis.groupFile.getPttUrl).toHaveBeenCalledWith(12345, MEDIA_NODE);
|
||||
expect(element.url).toBe('http://group/ptt');
|
||||
});
|
||||
|
||||
it('c2c record: uses fetchPrivatePttUrlByNode (no sessionId argument)', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.apis.groupFile.getPrivatePttUrl).toHaveBeenCalledWith(MEDIA_NODE);
|
||||
expect(element.url).toBe('http://private/ptt');
|
||||
});
|
||||
|
||||
it('group video: uses fetchGroupVideoUrlByNode', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.apis.groupFile.getVideoUrl).toHaveBeenCalledWith(12345, MEDIA_NODE);
|
||||
expect(element.url).toBe('http://group/video');
|
||||
});
|
||||
|
||||
it('c2c video: uses fetchPrivateVideoUrlByNode', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.apis.groupFile.getPrivateVideoUrl).toHaveBeenCalledWith(MEDIA_NODE);
|
||||
expect(element.url).toBe('http://private/video');
|
||||
});
|
||||
|
||||
it('record without mediaNode: no bridge call, url untouched', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'record' };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.apis.groupFile.getPttUrl).not.toHaveBeenCalled();
|
||||
expect(element.url).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MediaUrlResolver — short-circuits and resilience', () => {
|
||||
it('element.url already set: no bridge call, just rkey pass', async () => {
|
||||
const bridge = makeBridge();
|
||||
const rkey = makeRkey();
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.apis.groupFile.getUrl).not.toHaveBeenCalled();
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('bridge throws: swallowed, rkey still applied', async () => {
|
||||
const bridge = makeBridge({
|
||||
getUrl: vi.fn(async () => { throw new Error('network down'); }),
|
||||
});
|
||||
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(out).toBe('rkey-fallback');
|
||||
expect(element.url).toBeUndefined(); // bridge threw before assignment
|
||||
});
|
||||
|
||||
it('always calls rkey.resolveMediaUrl at the end', async () => {
|
||||
const bridge = makeBridge();
|
||||
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'http://signed') });
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'image' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
expect(out).toBe('http://signed');
|
||||
});
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
|
||||
|
||||
describe('hashMessageIdInt32', () => {
|
||||
it('returns consistent hash for same inputs', () => {
|
||||
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
|
||||
const id2 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
|
||||
expect(id1).toBe(id2);
|
||||
});
|
||||
|
||||
it('returns non-zero', () => {
|
||||
// The function ensures id !== 0 by setting it to 1
|
||||
const id = hashMessageIdInt32(0, 0, '');
|
||||
expect(id).not.toBe(0);
|
||||
});
|
||||
|
||||
it('returns different values for different sequences', () => {
|
||||
const id1 = hashMessageIdInt32(1, 12345, GROUP_MESSAGE_EVENT);
|
||||
const id2 = hashMessageIdInt32(2, 12345, GROUP_MESSAGE_EVENT);
|
||||
expect(id1).not.toBe(id2);
|
||||
});
|
||||
|
||||
it('returns different values for different sessions', () => {
|
||||
const id1 = hashMessageIdInt32(100, 11111, GROUP_MESSAGE_EVENT);
|
||||
const id2 = hashMessageIdInt32(100, 22222, GROUP_MESSAGE_EVENT);
|
||||
expect(id1).not.toBe(id2);
|
||||
});
|
||||
|
||||
it('returns different values for different event names', () => {
|
||||
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
|
||||
const id2 = hashMessageIdInt32(100, 12345, PRIVATE_MESSAGE_EVENT);
|
||||
expect(id1).not.toBe(id2);
|
||||
});
|
||||
|
||||
it('returns 32-bit integer', () => {
|
||||
const id = hashMessageIdInt32(999999, 123456789, GROUP_MESSAGE_EVENT);
|
||||
expect(id).toBeGreaterThanOrEqual(-2147483648);
|
||||
expect(id).toBeLessThanOrEqual(2147483647);
|
||||
});
|
||||
|
||||
it('handles non-finite inputs gracefully', () => {
|
||||
const id1 = hashMessageIdInt32(NaN, 0, 'test');
|
||||
const id2 = hashMessageIdInt32(Infinity, 0, 'test');
|
||||
expect(typeof id1).toBe('number');
|
||||
expect(typeof id2).toBe('number');
|
||||
// Both should map to sequence=0
|
||||
expect(id1).toBe(id2);
|
||||
});
|
||||
});
|
||||
@@ -1,483 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { parseMessage } from '../src/onebot/message-parser';
|
||||
import { buildSendElems } from '@snowluma/bridge/element-builder';
|
||||
import type { MentionExtraSend } from '@snowluma/proto-defs/action';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
|
||||
|
||||
describe('parseMessage', () => {
|
||||
describe('plain text', () => {
|
||||
it('parses simple text', async () => {
|
||||
const result = await parseMessage('hello world', false);
|
||||
expect(result).toEqual([{ type: 'text', text: 'hello world' }]);
|
||||
});
|
||||
|
||||
it('returns empty for empty string', async () => {
|
||||
const result = await parseMessage('', false);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('autoEscape treats CQ codes as text', async () => {
|
||||
const result = await parseMessage('[CQ:face,id=123]', true);
|
||||
expect(result).toEqual([{ type: 'text', text: '[CQ:face,id=123]' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CQ code parsing', () => {
|
||||
it('parses face CQ code', async () => {
|
||||
const result = await parseMessage('[CQ:face,id=123]', false);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('face');
|
||||
expect(result[0].faceId).toBe(123);
|
||||
});
|
||||
|
||||
it('parses at CQ code', async () => {
|
||||
const result = await parseMessage('[CQ:at,qq=12345]', false);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('at');
|
||||
expect(result[0].targetUin).toBe(12345);
|
||||
});
|
||||
|
||||
it('parses at all', async () => {
|
||||
const result = await parseMessage('[CQ:at,qq=all]', false);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('at');
|
||||
expect(result[0].targetUin).toBe(0);
|
||||
});
|
||||
|
||||
it('parses mixed text and CQ codes', async () => {
|
||||
const result = await parseMessage('Hello [CQ:face,id=1] World', false);
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[0]).toEqual({ type: 'text', text: 'Hello ' });
|
||||
expect(result[1].type).toBe('face');
|
||||
expect(result[2]).toEqual({ type: 'text', text: ' World' });
|
||||
});
|
||||
|
||||
it('unescapes CQ special chars', async () => {
|
||||
const result = await parseMessage('a&b[c]d', false);
|
||||
expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('JSON segment array', () => {
|
||||
it('parses text segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'text', data: { text: 'hello' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'text', text: 'hello' }]);
|
||||
});
|
||||
|
||||
it('parses face segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'face', data: { id: 123 } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('face');
|
||||
expect(result[0].faceId).toBe(123);
|
||||
});
|
||||
|
||||
it('parses image segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('image');
|
||||
expect(result[0].url).toBe('https://example.com/img.png');
|
||||
});
|
||||
|
||||
it('parses record segment from data.file', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'record', data: { file: 'file:///tmp/voice.amr' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'record', url: 'file:///tmp/voice.amr' }]);
|
||||
});
|
||||
|
||||
it('parses video segment from data.path and preserves thumb', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'video', data: { path: '/tmp/clip.mp4', thumb: '/tmp/clip.png' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]);
|
||||
});
|
||||
|
||||
it('parses AstrBot-style Video segment with top-level media', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'Video', media: 'file:////AstrBot/data/cache/BV-test.mp4' }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]);
|
||||
});
|
||||
|
||||
it('drops video segment with empty source', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'video', data: {} }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('parses record segment from data.path (NapCat parity)', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'record', data: { path: 'C:\\voices\\hi.silk' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'record', url: 'C:\\voices\\hi.silk' }]);
|
||||
});
|
||||
|
||||
it('drops record segment with empty source', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'record', data: {} }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('parses at segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'at', data: { qq: 12345 } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('at');
|
||||
expect(result[0].targetUin).toBe(12345);
|
||||
});
|
||||
|
||||
it('uses at segment name for display text and preserves uid', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'at', data: { qq: '123456', name: 'User', uid: 'u_test_uid' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
type: 'at',
|
||||
targetUin: 123456,
|
||||
uid: 'u_test_uid',
|
||||
text: '@User ',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves missing at uid through parse options', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
|
||||
false,
|
||||
{ resolveMentionUid: async (targetUin) => targetUin === 123456 ? 'u_resolved_uid' : null },
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
type: 'at',
|
||||
targetUin: 123456,
|
||||
uid: 'u_resolved_uid',
|
||||
text: '@User ',
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes mention extra with resolved uid for QQ notification', async () => {
|
||||
const elements = await parseMessage(
|
||||
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
|
||||
false,
|
||||
{ resolveMentionUid: () => 'u_resolved_uid' },
|
||||
);
|
||||
const protoElems = await buildSendElems(elements);
|
||||
const reserve = protoElems[0].text?.pbReserve;
|
||||
expect(reserve).toBeInstanceOf(Uint8Array);
|
||||
const extra = protobuf_decode<MentionExtraSend>(reserve as Uint8Array);
|
||||
expect(extra).toMatchObject({
|
||||
type: 2,
|
||||
uin: 123456,
|
||||
uid: 'u_resolved_uid',
|
||||
});
|
||||
expect(protoElems[0].text?.str).toBe('@User ');
|
||||
});
|
||||
|
||||
it('skips record send when SendContext is absent (graceful no-bridge path)', async () => {
|
||||
// Without a SendContext, buildSendElems can't run highway upload —
|
||||
// it should warn and drop the element instead of throwing into the
|
||||
// ffmpegAddon (which would explode for callers that don't actually
|
||||
// need to send).
|
||||
const elements = await parseMessage(
|
||||
[
|
||||
{ type: 'text', data: { text: 'hi ' } },
|
||||
{ type: 'record', data: { file: '/tmp/x.silk' } },
|
||||
] as any,
|
||||
false,
|
||||
);
|
||||
const protoElems = await buildSendElems(elements);
|
||||
// Only the leading text should make it through.
|
||||
expect(protoElems).toHaveLength(1);
|
||||
expect(protoElems[0].text?.str).toBe('hi ');
|
||||
});
|
||||
|
||||
it('skips video send when SendContext is absent (graceful no-bridge path)', async () => {
|
||||
const elements = await parseMessage(
|
||||
[
|
||||
{ type: 'text', data: { text: 'hi ' } },
|
||||
{ type: 'video', data: { file: '/tmp/x.mp4' } },
|
||||
] as any,
|
||||
false,
|
||||
);
|
||||
const protoElems = await buildSendElems(elements);
|
||||
expect(protoElems).toHaveLength(1);
|
||||
expect(protoElems[0].text?.str).toBe('hi ');
|
||||
});
|
||||
|
||||
it('builds video commonElem through NTV2 fast-upload response', async () => {
|
||||
const videoPath = path.join(os.tmpdir(), `snowluma-video-test-${process.pid}-${Date.now()}.mp4`);
|
||||
fs.writeFileSync(videoPath, Buffer.from([0, 1, 2, 3]));
|
||||
|
||||
const responseData = protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
|
||||
command: 0x11EA,
|
||||
subCommand: 100,
|
||||
errorCode: 0,
|
||||
body: {
|
||||
respHead: { retCode: 0, message: '' },
|
||||
upload: {
|
||||
uKey: '',
|
||||
msgInfo: {
|
||||
msgInfoBody: [
|
||||
{ index: { fileUuid: 'video-uuid' }, fileExist: true },
|
||||
{ index: { fileUuid: 'thumb-uuid' }, fileExist: true },
|
||||
],
|
||||
extBizInfo: {
|
||||
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
|
||||
},
|
||||
},
|
||||
subFileInfos: [{ uKey: '' }],
|
||||
},
|
||||
},
|
||||
errorMsg: '',
|
||||
reserved: 1,
|
||||
});
|
||||
|
||||
const bridge = {
|
||||
identity: { uin: '10000' },
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData,
|
||||
})),
|
||||
} as any;
|
||||
|
||||
try {
|
||||
const protoElems = await buildSendElems([{
|
||||
type: 'video',
|
||||
url: videoPath,
|
||||
thumbUrl: 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
|
||||
}], { bridge, groupId: 123456 });
|
||||
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledWith('OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
|
||||
expect(protoElems).toHaveLength(1);
|
||||
expect(protoElems[0].commonElem?.serviceType).toBe(48);
|
||||
expect(protoElems[0].commonElem?.businessType).toBe(21);
|
||||
expect(protoElems[0].commonElem?.pbElem).toBeInstanceOf(Uint8Array);
|
||||
} finally {
|
||||
try { fs.unlinkSync(videoPath); } catch { /* ignore */ }
|
||||
}
|
||||
});
|
||||
|
||||
it('parses multiple segments', async () => {
|
||||
const result = await parseMessage(
|
||||
[
|
||||
{ type: 'text', data: { text: 'hi ' } },
|
||||
{ type: 'at', data: { qq: 999 } },
|
||||
{ type: 'text', data: { text: ' there' } },
|
||||
] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[0].type).toBe('text');
|
||||
expect(result[1].type).toBe('at');
|
||||
expect(result[2].type).toBe('text');
|
||||
});
|
||||
|
||||
it('skips unknown segment types', async () => {
|
||||
const result = await parseMessage(
|
||||
[
|
||||
{ type: 'text', data: { text: 'ok' } },
|
||||
{ type: 'unknown_type_xyz', data: {} },
|
||||
] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('text');
|
||||
});
|
||||
});
|
||||
|
||||
describe('special segments', () => {
|
||||
it('parses json segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'json', data: { data: '{"app":"test"}' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
expect(result[0].text).toBe('{"app":"test"}');
|
||||
});
|
||||
|
||||
it('parses reply segment with resolveReplySequence', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'reply', data: { id: 42 } }] as any,
|
||||
false,
|
||||
{ resolveReplySequence: (id) => id === 42 ? 100 : null },
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('reply');
|
||||
expect(result[0].replySeq).toBe(100);
|
||||
});
|
||||
|
||||
it('parses share as json card', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'share', data: { url: 'https://example.com', title: 'Test' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
expect(result[0].text).toBeDefined();
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.app).toBe('com.tencent.structmsg');
|
||||
expect(parsed.meta.news.title).toBe('Test');
|
||||
});
|
||||
|
||||
it('parses rps as face', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'rps', data: {} }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('face');
|
||||
expect(result[0].faceId).toBe(359);
|
||||
});
|
||||
|
||||
it('parses dice as face', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'dice', data: {} }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('face');
|
||||
expect(result[0].faceId).toBe(358);
|
||||
});
|
||||
|
||||
it('parses shake as poke', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'shake', data: {} }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('poke');
|
||||
});
|
||||
|
||||
it('ignores anonymous segment', async () => {
|
||||
const result = await parseMessage(
|
||||
[
|
||||
{ type: 'anonymous', data: {} },
|
||||
{ type: 'text', data: { text: 'hi' } },
|
||||
] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('text');
|
||||
});
|
||||
|
||||
it('parses location as json card', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'location', data: { lat: '39.9', lon: '116.3', title: 'Beijing' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
expect(result[0].text).toBeDefined();
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.app).toBe('com.tencent.map');
|
||||
expect(parsed.meta.Location.lat).toBe('39.9');
|
||||
});
|
||||
|
||||
it('parses contact as json card', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'contact', data: { type: 'group', id: '12345' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].type).toBe('json');
|
||||
expect(result[0].text).toBeDefined();
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.meta.contact.type).toBe('group');
|
||||
});
|
||||
});
|
||||
|
||||
describe('single segment object', () => {
|
||||
it('parses single segment object', async () => {
|
||||
const result = await parseMessage(
|
||||
{ type: 'text', data: { text: 'single' } } as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'text', text: 'single' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('returns empty for null', async () => {
|
||||
const result = await parseMessage(null as any, false);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns empty for number', async () => {
|
||||
const result = await parseMessage(42 as any, false);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('file segment', () => {
|
||||
// Closes the parser-side of the "upload says ok but message is
|
||||
// empty" bug. Before this, `{type:'file', file_id:'…'}` segments
|
||||
// fell through to the default warn-and-drop branch — which made
|
||||
// `send_msg([{type:'file', file_id:'<uploaded>'}])` produce either
|
||||
// a "message is empty" error or, when mixed with text, a message
|
||||
// with the file segment quietly missing.
|
||||
it('parses {type:"file", file_id:"x"} into a file MessageElement', async () => {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'file', data: { file_id: 'fid-1', name: 'a.zip', size: 123 } } as any],
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([
|
||||
{ type: 'file', fileId: 'fid-1', fileName: 'a.zip', fileSize: 123 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops a file segment with no file_id (upload-first contract)', async () => {
|
||||
// Path-only segments aren't supported here — callers must
|
||||
// upload via `upload_group_file` / `upload_private_file` first
|
||||
// to obtain a file_id. Dropping with a warning is preferable
|
||||
// to silently kicking off an upload from inside the message
|
||||
// parser, which can't fail loudly without changing call sites.
|
||||
const result = await parseMessage(
|
||||
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts fileId / filename / fileName / md5 / sha1 aliases', async () => {
|
||||
const result = await parseMessage(
|
||||
[{
|
||||
type: 'file',
|
||||
data: { fileId: 'fid-2', filename: 'b.zip', fileSize: 456, md5: 'AB', sha1: 'CD' },
|
||||
} as any],
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([
|
||||
{ type: 'file', fileId: 'fid-2', fileName: 'b.zip', fileSize: 456, md5Hex: 'AB', sha1Hex: 'CD' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { MessageStore } from '../src/onebot/message-store';
|
||||
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
describe('MessageStore', () => {
|
||||
const testDbPath = path.join('data', 'test', 'messages-test.db');
|
||||
let store: MessageStore;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clean up any existing test database
|
||||
try {
|
||||
fs.unlinkSync(testDbPath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
store = new MessageStore(testDbPath);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
store.close();
|
||||
// Clean up test database
|
||||
try {
|
||||
fs.unlinkSync(testDbPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
});
|
||||
|
||||
describe('resolveReplySequence', () => {
|
||||
it('resolves group message reply sequence', () => {
|
||||
const groupId = 123456;
|
||||
const sequence = 100;
|
||||
const messageId = hashMessageIdInt32(sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
// Store a group message
|
||||
store.storeMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: groupId,
|
||||
sequence,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// Resolve the reply sequence
|
||||
const resolved = store.resolveReplySequence(true, groupId, messageId);
|
||||
expect(resolved).toBe(sequence);
|
||||
});
|
||||
|
||||
it('resolves private message reply sequence without session_id matching', () => {
|
||||
// Simulate receiving a private message from user 111111
|
||||
const senderUin = 111111;
|
||||
const sequence = 200;
|
||||
const messageId = hashMessageIdInt32(sequence, senderUin, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
// Store the received message (session_id is sender's UIN)
|
||||
store.storeMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: senderUin,
|
||||
sequence,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// When replying to this message, we send to the sender (who becomes the recipient)
|
||||
// The key fix: resolveReplySequence should work even when sessionId doesn't match
|
||||
const resolved = store.resolveReplySequence(false, senderUin, messageId);
|
||||
expect(resolved).toBe(sequence);
|
||||
|
||||
// More importantly: it should also work when we pass a different sessionId
|
||||
// (which was the bug - we were passing recipient UIN instead of sender UIN)
|
||||
const differentUin = 999999;
|
||||
const resolvedWithDifferentSession = store.resolveReplySequence(false, differentUin, messageId);
|
||||
expect(resolvedWithDifferentSession).toBe(sequence);
|
||||
});
|
||||
|
||||
it('returns null for non-existent message', () => {
|
||||
const resolved = store.resolveReplySequence(true, 123456, 999999);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for invalid messageId', () => {
|
||||
const resolved = store.resolveReplySequence(true, 123456, 0);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for invalid sessionId', () => {
|
||||
const messageId = hashMessageIdInt32(100, 123456, GROUP_MESSAGE_EVENT);
|
||||
const resolved = store.resolveReplySequence(true, 0, messageId);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it('distinguishes between group and private messages', () => {
|
||||
const sessionId = 123456;
|
||||
const sequence = 300;
|
||||
|
||||
// Store a group message
|
||||
const groupMessageId = hashMessageIdInt32(sequence, sessionId, GROUP_MESSAGE_EVENT);
|
||||
store.storeMeta(groupMessageId, {
|
||||
isGroup: true,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// Store a private message with same sequence but different hash
|
||||
const privateMessageId = hashMessageIdInt32(sequence, sessionId, PRIVATE_MESSAGE_EVENT);
|
||||
store.storeMeta(privateMessageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
eventName: PRIVATE_MESSAGE_EVENT,
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// Should resolve correctly based on isGroup flag
|
||||
const groupResolved = store.resolveReplySequence(true, sessionId, groupMessageId);
|
||||
expect(groupResolved).toBe(sequence);
|
||||
|
||||
const privateResolved = store.resolveReplySequence(false, sessionId, privateMessageId);
|
||||
expect(privateResolved).toBe(sequence);
|
||||
|
||||
// Should not cross-resolve
|
||||
const wrongGroupResolve = store.resolveReplySequence(true, sessionId, privateMessageId);
|
||||
expect(wrongGroupResolve).toBeNull();
|
||||
|
||||
const wrongPrivateResolve = store.resolveReplySequence(false, sessionId, groupMessageId);
|
||||
expect(wrongPrivateResolve).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('storeEvent and findEvent', () => {
|
||||
it('stores and retrieves event data', () => {
|
||||
const messageId = 12345;
|
||||
const event = {
|
||||
post_type: 'message',
|
||||
message_type: 'group',
|
||||
message_id: messageId,
|
||||
group_id: 123456,
|
||||
message: 'test message',
|
||||
time: Date.now(),
|
||||
};
|
||||
|
||||
store.storeEvent(messageId, true, 123456, 100, GROUP_MESSAGE_EVENT, event);
|
||||
|
||||
const retrieved = store.findEvent(messageId);
|
||||
expect(retrieved).toEqual(event);
|
||||
});
|
||||
|
||||
it('returns null for non-existent event', () => {
|
||||
const retrieved = store.findEvent(999999);
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('storeMeta and findMeta', () => {
|
||||
it('stores and retrieves message meta', () => {
|
||||
const messageId = 54321;
|
||||
const meta = {
|
||||
isGroup: true,
|
||||
targetId: 123456,
|
||||
sequence: 100,
|
||||
eventName: GROUP_MESSAGE_EVENT,
|
||||
clientSequence: 1,
|
||||
random: 12345,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
store.storeMeta(messageId, meta);
|
||||
|
||||
const retrieved = store.findMeta(messageId);
|
||||
expect(retrieved).toEqual(meta);
|
||||
});
|
||||
|
||||
it('returns null for non-existent meta', () => {
|
||||
const retrieved = store.findMeta(999999);
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,180 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/onebot/network';
|
||||
import type { NetworkAdapterContext } from '../src/onebot/network';
|
||||
import type { JsonObject, NetworkBase } from '../src/onebot/types';
|
||||
import type { DispatchPayload } from '../src/onebot/event-filter';
|
||||
|
||||
interface FakeNetworkConfig extends NetworkBase {
|
||||
// Allows tests to influence behavior via config:
|
||||
failOnEvent?: boolean;
|
||||
}
|
||||
|
||||
class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
|
||||
events: JsonObject[] = [];
|
||||
opens = 0;
|
||||
closes = 0;
|
||||
reloads = 0;
|
||||
// Last dispatch payload object identity, to assert it was reused per emit.
|
||||
lastPayloads: DispatchPayload[] = [];
|
||||
|
||||
open(): void {
|
||||
this.opens++;
|
||||
if (this.config.enabled !== false) this.isEnabled = true;
|
||||
}
|
||||
close(): void {
|
||||
this.closes++;
|
||||
this.isEnabled = false;
|
||||
}
|
||||
reload(next: FakeNetworkConfig): NetworkReloadType {
|
||||
this.reloads++;
|
||||
this.config = structuredClone(next);
|
||||
if (next.enabled === false && this.isEnabled) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (next.enabled !== false && !this.isEnabled) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
this.events.push(event);
|
||||
this.lastPayloads.push(payload);
|
||||
if (this.config.failOnEvent) throw new Error('boom');
|
||||
}
|
||||
}
|
||||
|
||||
const NULL_CTX: NetworkAdapterContext = {
|
||||
uin: '10001',
|
||||
api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processRequest: async () => '' } as never,
|
||||
buildLifecycleEvent: () => ({}),
|
||||
buildHeartbeatEvent: () => ({}),
|
||||
};
|
||||
|
||||
function makeAdapter(name: string, partial: Partial<FakeNetworkConfig> = {}): FakeAdapter {
|
||||
const config: FakeNetworkConfig = {
|
||||
name,
|
||||
enabled: true,
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
...partial,
|
||||
};
|
||||
return new FakeAdapter(name, config, NULL_CTX);
|
||||
}
|
||||
|
||||
const SAMPLE_EVENT: JsonObject = {
|
||||
time: 1,
|
||||
self_id: 10001,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 1,
|
||||
user_id: 22222,
|
||||
message: [{ type: 'text', data: { text: 'hi' } }],
|
||||
raw_message: 'hi',
|
||||
font: 0,
|
||||
sender: { user_id: 22222, nickname: 'peer', sex: 'unknown', age: 0 },
|
||||
};
|
||||
|
||||
describe('OneBotNetworkManager', () => {
|
||||
it('opens and emits to every active adapter in parallel', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
mgr.register(a);
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
expect(a.opens).toBe(1);
|
||||
expect(b.opens).toBe(1);
|
||||
|
||||
await mgr.emitEvent(SAMPLE_EVENT);
|
||||
expect(a.events).toEqual([SAMPLE_EVENT]);
|
||||
expect(b.events).toEqual([SAMPLE_EVENT]);
|
||||
// Both adapters should receive the same payload reference (built once).
|
||||
expect(a.lastPayloads[0]).toBe(b.lastPayloads[0]);
|
||||
});
|
||||
|
||||
it('skips inactive adapters during emit', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const active = makeAdapter('active');
|
||||
const idle = makeAdapter('idle', { enabled: false });
|
||||
mgr.register(active);
|
||||
mgr.register(idle);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.emitEvent(SAMPLE_EVENT);
|
||||
expect(active.events).toHaveLength(1);
|
||||
expect(idle.events).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('isolates adapter errors so one bad adapter does not block others', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const ok = makeAdapter('ok');
|
||||
const bad = makeAdapter('bad', { failOnEvent: true });
|
||||
mgr.register(ok);
|
||||
mgr.register(bad);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.emitEvent(SAMPLE_EVENT);
|
||||
// The good adapter still saw the event.
|
||||
expect(ok.events).toHaveLength(1);
|
||||
// The bad adapter logged the throw but didn't crash the manager.
|
||||
expect(bad.events).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('replaces an existing adapter under the same name and closes the old one', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const first = makeAdapter('dup');
|
||||
mgr.register(first);
|
||||
await mgr.openAll();
|
||||
|
||||
const second = makeAdapter('dup');
|
||||
mgr.register(second);
|
||||
|
||||
expect(mgr.get('dup')).toBe(second);
|
||||
expect(first.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('closeOne shuts down a single adapter and removes it', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
mgr.register(a);
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.closeOne('a');
|
||||
expect(mgr.has('a')).toBe(false);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(b.closes).toBe(0);
|
||||
expect(mgr.hasActiveAdapters()).toBe(true);
|
||||
});
|
||||
|
||||
it('closeAll clears every adapter', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
mgr.register(a);
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.closeAll();
|
||||
expect(mgr.list()).toHaveLength(0);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(b.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('hasActiveAdapters reflects current state', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
const a = makeAdapter('a');
|
||||
mgr.register(a);
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
await mgr.openAll();
|
||||
expect(mgr.hasActiveAdapters()).toBe(true);
|
||||
await mgr.closeAll();
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,316 +0,0 @@
|
||||
// First real OneBot unit test that exercises a module purely through
|
||||
// BridgeInterface — no concrete Bridge, no SQLite, no native packet
|
||||
// sender, no BridgeManager. This is the testability win that PR4 + PR5
|
||||
// were supposed to unlock; the file exists to prove it.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo,
|
||||
} from '@snowluma/bridge/qq-info';
|
||||
import {
|
||||
getFriendList,
|
||||
getGroupInfo,
|
||||
getGroupList,
|
||||
getGroupMemberInfo,
|
||||
getGroupMemberList,
|
||||
getLoginInfo,
|
||||
getStrangerInfo,
|
||||
} from '../../src/onebot/modules/contact-actions';
|
||||
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
|
||||
|
||||
/**
|
||||
* A typed BridgeInterface where every property is undefined by default;
|
||||
* accessing an un-stubbed property throws with a clear message so tests
|
||||
* fail loudly if they exercise a code path the fake hasn't been told
|
||||
* about. Tests just spread the methods they care about.
|
||||
*/
|
||||
// `apisAutoPromote` lets tests written before #6 (which stubbed flat
|
||||
// methods like `fetchFriendList: vi.fn()` on bridge directly) keep
|
||||
// working without restructuring — the helper rewrites flat stubs into
|
||||
// the new `apis.<area>.method` shape automatically. New code can also
|
||||
// pass `apis: { contacts: { … } }` explicitly; the two merge.
|
||||
const APIS_ROUTING: Record<string, string> = {
|
||||
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
|
||||
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
|
||||
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
|
||||
};
|
||||
|
||||
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
|
||||
const apisSynth: Record<string, Record<string, any>> = {};
|
||||
for (const [k, v] of Object.entries(overrides)) {
|
||||
const area = APIS_ROUTING[k];
|
||||
if (area) {
|
||||
if (!apisSynth[area]) apisSynth[area] = {};
|
||||
apisSynth[area][k] = v;
|
||||
}
|
||||
}
|
||||
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
|
||||
return new Proxy(merged as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Same Proxy trick for the IdentityService surface that contact-actions touches. */
|
||||
function fakeIdentity(overrides: Record<string, unknown> = {}): BridgeInterface['identity'] {
|
||||
return new Proxy(overrides as any, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return target[prop];
|
||||
throw new Error(`fakeIdentity: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Fixture builders ───
|
||||
|
||||
function makeFriend(uin: number, nickname: string, remark = ''): FriendInfo {
|
||||
return { uin, uid: `u_${uin}`, nickname, remark };
|
||||
}
|
||||
|
||||
function makeGroup(groupId: number, groupName: string, members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
return {
|
||||
groupId, groupName, remark: '',
|
||||
memberCount: members.length, memberMax: 500,
|
||||
members: new Map(members.map((m) => [m.uin, m])),
|
||||
};
|
||||
}
|
||||
|
||||
function makeMember(uin: number, nickname: string, card = ''): GroupMemberInfo {
|
||||
return {
|
||||
uin, uid: `u_${uin}`, nickname, card,
|
||||
role: 'member', level: 1, title: '',
|
||||
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function makeProfile(uin: number, nickname: string, sex: 'male' | 'female' | 'unknown' = 'unknown', age = 0): UserProfileInfo {
|
||||
return {
|
||||
uin, uid: `u_${uin}`, nickname, remark: '', qid: '', sex, age, sign: '', avatar: '',
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Tests ───
|
||||
|
||||
describe('onebot/contact-actions / getLoginInfo', () => {
|
||||
it('returns user_id parsed from uin and nickname from identity', () => {
|
||||
const ref = {
|
||||
uin: '10001',
|
||||
bridge: fakeBridge({ identity: fakeIdentity({ nickname: 'self-nick' }) }),
|
||||
} as unknown as OneBotInstanceContext;
|
||||
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: 'self-nick' });
|
||||
});
|
||||
|
||||
it('falls back to the uin string when identity nickname is empty', () => {
|
||||
const ref = {
|
||||
uin: '10001',
|
||||
bridge: fakeBridge({ identity: fakeIdentity({ nickname: '' }) }),
|
||||
} as unknown as OneBotInstanceContext;
|
||||
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: '10001' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getFriendList', () => {
|
||||
it('returns the fetched list mapped to OneBot shape', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchFriendList: vi.fn(async () => [makeFriend(22222, 'alice', 'best-friend')]),
|
||||
});
|
||||
const out = await getFriendList(bridge);
|
||||
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
|
||||
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('falls back to identity.friends on fetch failure', async () => {
|
||||
const cached = [makeFriend(33333, 'bob')];
|
||||
const bridge = fakeBridge({
|
||||
fetchFriendList: vi.fn(async () => { throw new Error('network down'); }),
|
||||
identity: fakeIdentity({ friends: cached }),
|
||||
});
|
||||
const out = await getFriendList(bridge);
|
||||
expect(out).toEqual([{ user_id: 33333, nickname: 'bob', remark: '' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupList', () => {
|
||||
it('triggers fetch when the in-memory roster is empty', async () => {
|
||||
const fetched = [makeGroup(100, 'Group A')];
|
||||
// `groups` starts empty; the fetch callback flips it to mimic
|
||||
// bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups.
|
||||
let groups: QQGroupInfo[] = [];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }),
|
||||
identity: fakeIdentity({
|
||||
get groups() { return groups; },
|
||||
}),
|
||||
});
|
||||
const out = await getGroupList(bridge);
|
||||
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
|
||||
expect(out).toEqual([{
|
||||
group_id: 100, group_name: 'Group A',
|
||||
member_count: 0, max_member_count: 500,
|
||||
}]);
|
||||
});
|
||||
|
||||
it('skips fetch when cache is populated and noCache is omitted', async () => {
|
||||
const cached = [makeGroup(200, 'Group B')];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
identity: fakeIdentity({ groups: cached }),
|
||||
});
|
||||
await getGroupList(bridge);
|
||||
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forces fetch when noCache=true even with a populated cache', async () => {
|
||||
const cached = [makeGroup(300, 'Group C')];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => cached),
|
||||
identity: fakeIdentity({ groups: cached }),
|
||||
});
|
||||
await getGroupList(bridge, true);
|
||||
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('serves the stale cache when the fetch path throws', async () => {
|
||||
const cached = [makeGroup(400, 'Group D')];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => { throw new Error('boom'); }),
|
||||
identity: fakeIdentity({ groups: cached }),
|
||||
});
|
||||
const out = await getGroupList(bridge, true);
|
||||
expect(out[0]).toMatchObject({ group_id: 400, group_name: 'Group D' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupInfo', () => {
|
||||
it('returns the cached group without refreshing when group is known and noCache is false', async () => {
|
||||
const cached = makeGroup(500, 'Group E');
|
||||
const findGroup = vi.fn((groupId: number) => groupId === 500 ? cached : null);
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
identity: fakeIdentity({ findGroup }),
|
||||
});
|
||||
const out = await getGroupInfo(bridge, 500);
|
||||
expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' });
|
||||
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers fetch when the group is unknown to the cache', async () => {
|
||||
const cached = makeGroup(600, 'Group F');
|
||||
let known = false;
|
||||
const findGroup = vi.fn((groupId: number) => (known && groupId === 600) ? cached : null);
|
||||
const fetchGroupList = vi.fn(async () => { known = true; return [cached]; });
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList,
|
||||
identity: fakeIdentity({ findGroup }),
|
||||
});
|
||||
const out = await getGroupInfo(bridge, 600);
|
||||
expect(fetchGroupList).toHaveBeenCalledOnce();
|
||||
expect(out).toMatchObject({ group_id: 600, group_name: 'Group F' });
|
||||
});
|
||||
|
||||
it('returns null when the group remains unknown after fetch', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupList: vi.fn(async () => []),
|
||||
identity: fakeIdentity({ findGroup: () => null }),
|
||||
});
|
||||
expect(await getGroupInfo(bridge, 700)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupMemberList', () => {
|
||||
it('returns the fetched roster mapped to OneBot shape', async () => {
|
||||
const members = [makeMember(11, 'alice', 'A'), makeMember(22, 'bob', 'B')];
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList: vi.fn(async () => members),
|
||||
});
|
||||
const out = await getGroupMemberList(bridge, 800);
|
||||
expect(out).toHaveLength(2);
|
||||
expect(out[0]).toMatchObject({ group_id: 800, user_id: 11, nickname: 'alice', card: 'A' });
|
||||
});
|
||||
|
||||
it('falls back to the cached roster when fetch fails', async () => {
|
||||
const cached = makeGroup(900, '', [makeMember(33, 'cached')]);
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
|
||||
identity: fakeIdentity({
|
||||
findGroup: (gid: number) => gid === 900 ? cached : null,
|
||||
}),
|
||||
});
|
||||
const out = await getGroupMemberList(bridge, 900);
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]).toMatchObject({ user_id: 33, nickname: 'cached' });
|
||||
});
|
||||
|
||||
it('returns [] when no roster is known and fetch fails', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
|
||||
identity: fakeIdentity({ findGroup: () => null }),
|
||||
});
|
||||
expect(await getGroupMemberList(bridge, 999)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getGroupMemberInfo', () => {
|
||||
it('returns the cached member when present and noCache is false', async () => {
|
||||
const member = makeMember(44, 'dave', 'D');
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList: vi.fn(async () => []),
|
||||
identity: fakeIdentity({
|
||||
findGroupMember: (gid: number, uin: number) =>
|
||||
gid === 1000 && uin === 44 ? member : null,
|
||||
}),
|
||||
});
|
||||
const out = await getGroupMemberInfo(bridge, 1000, 44);
|
||||
expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' });
|
||||
expect(bridge.apis.contacts.fetchGroupMemberList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers fetch when member is unknown and re-queries the cache', async () => {
|
||||
const member = makeMember(55, 'eve');
|
||||
let known = false;
|
||||
const findGroupMember = vi.fn((gid: number, uin: number) =>
|
||||
(known && gid === 1100 && uin === 55) ? member : null,
|
||||
);
|
||||
const fetchGroupMemberList = vi.fn(async () => { known = true; return [member]; });
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupMemberList,
|
||||
identity: fakeIdentity({ findGroupMember }),
|
||||
});
|
||||
const out = await getGroupMemberInfo(bridge, 1100, 55);
|
||||
expect(fetchGroupMemberList).toHaveBeenCalledOnce();
|
||||
expect(out).toMatchObject({ user_id: 55, nickname: 'eve' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('onebot/contact-actions / getStrangerInfo', () => {
|
||||
it('returns a fetched profile', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchUserProfile: vi.fn(async () => makeProfile(55555, 'Eve', 'female', 25)),
|
||||
});
|
||||
const out = await getStrangerInfo(bridge, 55555);
|
||||
expect(out).toMatchObject({ user_id: 55555, nickname: 'Eve', sex: 'female', age: 25 });
|
||||
});
|
||||
|
||||
it('falls back to identity.findUserProfile when fetch fails but the profile is cached', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
|
||||
identity: fakeIdentity({
|
||||
findUserProfile: (uin: number) =>
|
||||
uin === 66666 ? makeProfile(66666, 'Frank', 'male', 30) : null,
|
||||
}),
|
||||
});
|
||||
const out = await getStrangerInfo(bridge, 66666);
|
||||
expect(out).toMatchObject({ user_id: 66666, nickname: 'Frank' });
|
||||
});
|
||||
|
||||
it('returns null when neither fetch nor cache produces a profile', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
|
||||
identity: fakeIdentity({ findUserProfile: () => null }),
|
||||
});
|
||||
expect(await getStrangerInfo(bridge, 99999)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,586 +0,0 @@
|
||||
// End-to-end OneBot action tests for the napcat-parity surface added in
|
||||
// Tier 1 + Tier 2: send_packet, bot_exit, nc_*, group-todo, AI voice,
|
||||
// and the rewired ignored-notifies family. We drive everything through
|
||||
// the public `ApiHandler.handle()` entry point so the wiring (including
|
||||
// param coercion, retcode shape) is part of what's under test.
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { ApiHandler, type ApiActionContext } from '../../src/onebot/api-handler';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { GroupRequestInfo } from '@snowluma/bridge/qq-info';
|
||||
import type { MessageMeta } from '../../src/onebot/types';
|
||||
|
||||
function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
|
||||
return {
|
||||
isGroup: true,
|
||||
targetId: 100,
|
||||
sequence: 555,
|
||||
eventName: 'group_message',
|
||||
clientSequence: 0,
|
||||
random: 0,
|
||||
timestamp: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a BridgeInterface stub that throws on any method we haven't
|
||||
* pre-stubbed for the test. Same pattern as contact-actions.test.ts —
|
||||
* keeps tests honest about which surface they actually need.
|
||||
*/
|
||||
// Maps flat method names → [area, newMethodName] on the ApiHub under
|
||||
// the #6 refactor. Auto-promotion lets tests written against the
|
||||
// pre-refactor flat surface (`fetchGroupRequests: vi.fn()`) keep
|
||||
// working without per-test restructure, even when the new method name
|
||||
// drops the redundant `Group`/`File` prefix.
|
||||
const APIS_ROUTING: Record<string, [string, string]> = {
|
||||
fetchFriendList: ['contacts', 'fetchFriendList'],
|
||||
fetchGroupList: ['contacts', 'fetchGroupList'],
|
||||
fetchGroupMemberList: ['contacts', 'fetchGroupMemberList'],
|
||||
fetchUserProfile: ['contacts', 'fetchUserProfile'],
|
||||
fetchGroupRequests: ['contacts', 'fetchGroupRequests'],
|
||||
fetchDownloadRKeys: ['contacts', 'fetchDownloadRKeys'],
|
||||
// GroupFileApi: methods drop `Group`/`File`/`Folder` suffix where
|
||||
// the area name already says it.
|
||||
deleteGroupFileFolder: ['groupFile', 'deleteFolder'],
|
||||
fetchGroupPttUrlByNode: ['groupFile', 'getPttUrl'],
|
||||
// InteractionApi: methods drop the redundant `Group` prefix.
|
||||
sendLike: ['interaction', 'sendLike'],
|
||||
setGroupReaction: ['interaction', 'setReaction'],
|
||||
// ProfileApi: a few methods rename (getProfileLike → getLike).
|
||||
setOnlineStatus: ['profile', 'setOnlineStatus'],
|
||||
setDiyOnlineStatus: ['profile', 'setDiyOnlineStatus'],
|
||||
setProfile: ['profile', 'setProfile'],
|
||||
setSelfLongNick: ['profile', 'setSelfLongNick'],
|
||||
setInputStatus: ['profile', 'setInputStatus'],
|
||||
setAvatar: ['profile', 'setAvatar'],
|
||||
setGroupAvatar: ['profile', 'setGroupAvatar'],
|
||||
fetchCustomFace: ['profile', 'fetchCustomFace'],
|
||||
getProfileLike: ['profile', 'getLike'],
|
||||
getUnidirectionalFriendList: ['profile', 'getUnidirectionalFriendList'],
|
||||
// FriendApi: handleRequest/delete/setRemark.
|
||||
setFriendRemark: ['friend', 'setRemark'],
|
||||
deleteFriend: ['friend', 'delete'],
|
||||
setFriendAddRequest: ['friend', 'handleRequest'],
|
||||
// ExtrasApi: group todo / stranger status / AI voice.
|
||||
setGroupTodo: ['extras', 'setGroupTodo'],
|
||||
completeGroupTodo: ['extras', 'completeGroupTodo'],
|
||||
cancelGroupTodo: ['extras', 'cancelGroupTodo'],
|
||||
getStrangerStatus: ['extras', 'getStrangerStatus'],
|
||||
fetchAiVoiceList: ['extras', 'fetchAiVoiceList'],
|
||||
fetchAiVoice: ['extras', 'fetchAiVoice'],
|
||||
};
|
||||
|
||||
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
|
||||
const apisSynth: Record<string, Record<string, any>> = {};
|
||||
for (const [k, v] of Object.entries(overrides)) {
|
||||
const route = APIS_ROUTING[k];
|
||||
if (route) {
|
||||
const [area, newName] = route;
|
||||
if (!apisSynth[area]) apisSynth[area] = {};
|
||||
apisSynth[area][newName] = v;
|
||||
}
|
||||
}
|
||||
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
|
||||
return new Proxy(merged as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the minimum ApiActionContext needed for the tested actions.
|
||||
* Anything not stubbed throws on access — keeps the dependency surface
|
||||
* explicit. Only fields the tested actions read are populated.
|
||||
*/
|
||||
function fakeCtx(bridge: BridgeInterface, overrides: Partial<ApiActionContext> = {}): ApiActionContext {
|
||||
const base = {
|
||||
bridge,
|
||||
getMessageMeta: () => null,
|
||||
getMessage: () => null,
|
||||
getLoginInfo: () => ({ userId: 1, nickname: '' }),
|
||||
isOnline: () => true,
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
getDownloadRKeys: async () => [],
|
||||
...overrides,
|
||||
};
|
||||
return new Proxy(base as ApiActionContext, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeCtx: '${String(prop)}' was not stubbed`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeHandler(ctx: ApiActionContext): ApiHandler {
|
||||
return new ApiHandler(ctx);
|
||||
}
|
||||
|
||||
// ─── Tier 1: send_packet / .send_packet ───
|
||||
|
||||
describe('extended-actions / send_packet', () => {
|
||||
it('hex-decodes data, calls Bridge.sendRawPacket, hex-encodes the response', async () => {
|
||||
const sendRawPacket: BridgeInterface['sendRawPacket'] = vi.fn(async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from([0xDE, 0xAD, 0xBE, 0xEF]),
|
||||
}));
|
||||
const bridge = fakeBridge({ sendRawPacket });
|
||||
const h = makeHandler(fakeCtx(bridge));
|
||||
const res = await h.handle('send_packet', { cmd: 'Some.Cmd', data: 'cafebabe', rsp: true });
|
||||
const spy = vi.mocked(sendRawPacket);
|
||||
expect(spy).toHaveBeenCalledOnce();
|
||||
const sentBody = spy.mock.calls[0]![1];
|
||||
expect(Buffer.from(sentBody).toString('hex')).toBe('cafebabe');
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: 'deadbeef' });
|
||||
});
|
||||
|
||||
it('.send_packet shares the same handler', async () => {
|
||||
const sendRawPacket = vi.fn(async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0),
|
||||
}));
|
||||
const h = makeHandler(fakeCtx(fakeBridge({ sendRawPacket: sendRawPacket as any })));
|
||||
const res = await h.handle('.send_packet', { cmd: 'C', data: '' });
|
||||
expect(res.status).toBe('ok');
|
||||
expect(sendRawPacket).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('with rsp=false returns null and ignores responseData', async () => {
|
||||
const bridge = fakeBridge({
|
||||
sendRawPacket: (async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from('00ff', 'hex'),
|
||||
})) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '', rsp: false });
|
||||
expect(res).toMatchObject({ status: 'ok', data: null });
|
||||
});
|
||||
|
||||
it('rejects missing cmd', async () => {
|
||||
const bridge = fakeBridge({ sendRawPacket: vi.fn() as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: '', data: '' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
|
||||
it('rejects malformed hex', async () => {
|
||||
const sendRawPacket = vi.fn();
|
||||
const bridge = fakeBridge({ sendRawPacket: sendRawPacket as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'ZZZZ' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects odd-length hex', async () => {
|
||||
const bridge = fakeBridge({ sendRawPacket: vi.fn() as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'abc' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
|
||||
it('propagates wire-level failure as action_failed', async () => {
|
||||
const bridge = fakeBridge({
|
||||
sendRawPacket: (async () => ({
|
||||
success: false, gotResponse: false, errorCode: -1, errorMessage: 'no sender', responseData: null,
|
||||
})) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'no sender' });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 1: bot_exit ───
|
||||
|
||||
describe('extended-actions / bot_exit', () => {
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
exitSpy = vi.spyOn(process, 'exit').mockImplementation(((_code?: number) => undefined) as any);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('returns ok immediately, then exits on the deferred timer', async () => {
|
||||
const h = makeHandler(fakeCtx(fakeBridge()));
|
||||
const res = await h.handle('bot_exit', {});
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
expect(exitSpy).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(exitSpy).toHaveBeenCalledWith(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 1: nc_get_packet_status / nc_get_rkey ───
|
||||
|
||||
describe('extended-actions / nc_get_packet_status', () => {
|
||||
it('reports healthy with no dependency on bridge', async () => {
|
||||
const h = makeHandler(fakeCtx(fakeBridge()));
|
||||
const res = await h.handle('nc_get_packet_status', {});
|
||||
expect(res).toEqual({ status: 'ok', retcode: 0, data: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / nc_get_rkey', () => {
|
||||
it('reuses the same data the get_rkey handler returns', async () => {
|
||||
const ctx = fakeCtx(fakeBridge(), {
|
||||
getDownloadRKeys: async () => [{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }],
|
||||
});
|
||||
const h = makeHandler(ctx);
|
||||
const a = await h.handle('get_rkey', {});
|
||||
const b = await h.handle('nc_get_rkey', {});
|
||||
expect(b).toEqual(a);
|
||||
expect(b.data).toEqual([{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }]);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 1: group-request ignored / shut list / ignore-add ───
|
||||
|
||||
function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
|
||||
return {
|
||||
groupId: 999,
|
||||
groupName: 'g',
|
||||
targetUid: 'u_t',
|
||||
targetUin: 5555,
|
||||
targetName: 'target',
|
||||
invitorUid: 'u_i',
|
||||
invitorUin: 7777,
|
||||
invitorName: 'inviter',
|
||||
operatorUid: 'u_o',
|
||||
operatorUin: 8888,
|
||||
operatorName: 'op',
|
||||
sequence: 42,
|
||||
state: 1,
|
||||
eventType: 7,
|
||||
comment: 'pls',
|
||||
filtered: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('extended-actions / get_group_ignored_notifies', () => {
|
||||
it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => {
|
||||
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
|
||||
filtered ? [fakeFilteredRequest()] : []
|
||||
);
|
||||
const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any });
|
||||
const h = makeHandler(fakeCtx(bridge));
|
||||
const res = await h.handle('get_group_ignored_notifies', {});
|
||||
expect(fetchGroupRequests).toHaveBeenCalledWith(true);
|
||||
expect(res.status).toBe('ok');
|
||||
expect(res.data).toEqual([{
|
||||
group_id: 999,
|
||||
group_name: 'g',
|
||||
request_id: 42,
|
||||
requester_uin: 5555,
|
||||
requester_nick: 'target',
|
||||
message: 'pls',
|
||||
checked: false, // state == 1 → un-checked
|
||||
actor: 8888,
|
||||
invitor_uin: 7777,
|
||||
invitor_nick: 'inviter',
|
||||
flag: '7:999:u_t:filtered',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('returns [] when the fetch throws', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: (async () => { throw new Error('boom'); }) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignored_notifies', {});
|
||||
expect(res).toMatchObject({ status: 'ok', data: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / get_group_ignore_add_request', () => {
|
||||
it('projects the same filtered list into napcat\'s ignore-add-request shape', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: (async () => [fakeFilteredRequest({ state: 2 })]) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignore_add_request', {});
|
||||
expect(res.status).toBe('ok');
|
||||
expect(res.data).toEqual([{
|
||||
request_id: 42,
|
||||
invitor_uin: 7777,
|
||||
invitor_nick: 'inviter',
|
||||
group_id: 999,
|
||||
message: 'pls',
|
||||
group_name: 'g',
|
||||
checked: true, // state == 2 → checked
|
||||
actor: 8888,
|
||||
requester_nick: 'target',
|
||||
}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / get_group_shut_list', () => {
|
||||
it('returns empty list (oidb not yet wrapped)', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {});
|
||||
expect(res).toEqual({ status: 'ok', retcode: 0, data: [] });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 1: delete_group_folder alias ───
|
||||
|
||||
describe('extended-actions / delete_group_folder', () => {
|
||||
it('forwards to bridge.deleteGroupFileFolder', async () => {
|
||||
const deleteGroupFileFolder = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ deleteGroupFileFolder: deleteGroupFileFolder as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', {
|
||||
group_id: 100, folder_id: 'fid-1',
|
||||
});
|
||||
expect(deleteGroupFileFolder).toHaveBeenCalledWith(100, 'fid-1');
|
||||
expect(res.status).toBe('ok');
|
||||
});
|
||||
|
||||
it('rejects missing fields', async () => {
|
||||
const bridge = fakeBridge({ deleteGroupFileFolder: vi.fn() as any });
|
||||
const r1 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { folder_id: 'x' });
|
||||
const r2 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { group_id: 1 });
|
||||
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 2: group todo ───
|
||||
|
||||
describe('extended-actions / set_/complete_/cancel_group_todo', () => {
|
||||
it.each([
|
||||
['set_group_todo', 'setGroupTodo'],
|
||||
['complete_group_todo', 'completeGroupTodo'],
|
||||
['cancel_group_todo', 'cancelGroupTodo'],
|
||||
] as const)('%s resolves message meta then calls bridge.%s with the sequence', async (action, method) => {
|
||||
const bridgeMethod = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ [method]: bridgeMethod } as any);
|
||||
const ctx = fakeCtx(bridge, {
|
||||
getMessageMeta: (id: number) => id === 7 ? fakeMeta({ targetId: 100, sequence: 555 }) : null,
|
||||
});
|
||||
const res = await makeHandler(ctx).handle(action, { group_id: 100, message_id: 7 });
|
||||
expect(res.status).toBe('ok');
|
||||
expect(bridgeMethod).toHaveBeenCalledWith(100, 555n);
|
||||
});
|
||||
|
||||
it('rejects when message meta is missing', async () => {
|
||||
const ctx = fakeCtx(fakeBridge(), { getMessageMeta: () => null });
|
||||
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 1, message_id: 9999 });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'message not found' });
|
||||
});
|
||||
|
||||
it('rejects when message belongs to a different chat', async () => {
|
||||
const ctx = fakeCtx(fakeBridge(), {
|
||||
getMessageMeta: () => fakeMeta({ targetId: 222 }),
|
||||
});
|
||||
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
});
|
||||
|
||||
it('rejects when message is a private message', async () => {
|
||||
const ctx = fakeCtx(fakeBridge(), {
|
||||
getMessageMeta: () => fakeMeta({ isGroup: false }),
|
||||
});
|
||||
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
});
|
||||
|
||||
it('rejects missing params', async () => {
|
||||
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 });
|
||||
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { group_id: 1 });
|
||||
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 2: nc_get_user_status ───
|
||||
|
||||
describe('extended-actions / nc_get_user_status', () => {
|
||||
it('returns whatever bridge.getStrangerStatus reports', async () => {
|
||||
const getStrangerStatus = vi.fn(async () => ({ status: 10, ext_status: 0x1234 }));
|
||||
const bridge = fakeBridge({ getStrangerStatus: getStrangerStatus as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 999 });
|
||||
expect(getStrangerStatus).toHaveBeenCalledWith(999);
|
||||
expect(res).toMatchObject({ status: 'ok', data: { status: 10, ext_status: 0x1234 } });
|
||||
});
|
||||
|
||||
it('reports action_failed when bridge returns null', async () => {
|
||||
const bridge = fakeBridge({ getStrangerStatus: (async () => null) as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 1 });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
});
|
||||
|
||||
it('rejects missing user_id', async () => {
|
||||
const bridge = fakeBridge({ getStrangerStatus: vi.fn() as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', {});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 2: AI voice trio ───
|
||||
|
||||
describe('extended-actions / get_ai_characters', () => {
|
||||
it('flattens server categories into {type, characters[]}', async () => {
|
||||
const fetchAiVoiceList = vi.fn(async () => [{
|
||||
category: 'cute',
|
||||
voices: [
|
||||
{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://a' },
|
||||
{ voiceId: 'v2', voiceDisplayName: 'V2', voiceExampleUrl: 'http://b' },
|
||||
],
|
||||
}]);
|
||||
const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', {
|
||||
group_id: 100, chat_type: 1,
|
||||
});
|
||||
expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1);
|
||||
expect(res.data).toEqual([{
|
||||
type: 'cute',
|
||||
characters: [
|
||||
{ character_id: 'v1', character_name: 'V1', preview_url: 'http://a' },
|
||||
{ character_id: 'v2', character_name: 'V2', preview_url: 'http://b' },
|
||||
],
|
||||
}]);
|
||||
});
|
||||
|
||||
it('defaults chat_type to 1 (Sound) when unspecified', async () => {
|
||||
const fetchAiVoiceList = vi.fn(async () => []);
|
||||
const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any });
|
||||
await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 });
|
||||
expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1);
|
||||
});
|
||||
|
||||
it('surfaces bridge errors as action_failed', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchAiVoiceList: (async () => { throw new Error('rate limited'); }) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'rate limited' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / get_ai_record', () => {
|
||||
it('feeds IndexNode from fetchAiVoice into fetchGroupPttUrlByNode and returns the URL', async () => {
|
||||
const node = { fileUuid: 'voice-uuid' };
|
||||
const fetchAiVoice = vi.fn(async () => node);
|
||||
const fetchGroupPttUrlByNode = vi.fn(async () => 'http://voice.silk');
|
||||
const bridge = fakeBridge({
|
||||
fetchAiVoice: fetchAiVoice as any,
|
||||
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', {
|
||||
group_id: 100, character: 'v1', text: 'hello',
|
||||
});
|
||||
expect(fetchAiVoice).toHaveBeenCalledWith(100, 'v1', 'hello', 1);
|
||||
expect(fetchGroupPttUrlByNode).toHaveBeenCalledWith(100, node);
|
||||
expect(res).toMatchObject({ status: 'ok', data: 'http://voice.silk' });
|
||||
});
|
||||
|
||||
it('rejects missing fields', async () => {
|
||||
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { character: 'v', text: 't' });
|
||||
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, text: 't' });
|
||||
const r3 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, character: 'v' });
|
||||
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(r3).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
|
||||
it('reports action_failed when synthesis exhausts retries', async () => {
|
||||
const bridge = fakeBridge({
|
||||
fetchAiVoice: (async () => { throw new Error('AI voice synthesis did not complete'); }) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', {
|
||||
group_id: 1, character: 'v', text: 't',
|
||||
});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / send_group_ai_record', () => {
|
||||
it('side-effects fetchAiVoice (no URL fetch) and returns message_id=0', async () => {
|
||||
const fetchAiVoice = vi.fn(async () => ({ fileUuid: 'uuid' }));
|
||||
const fetchGroupPttUrlByNode = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
fetchAiVoice: fetchAiVoice as any,
|
||||
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('send_group_ai_record', {
|
||||
group_id: 100, character: 'v', text: 'hi',
|
||||
});
|
||||
expect(fetchAiVoice).toHaveBeenCalledOnce();
|
||||
expect(fetchGroupPttUrlByNode).not.toHaveBeenCalled();
|
||||
expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 3: set_diy_online_status ───
|
||||
|
||||
describe('extended-actions / set_diy_online_status', () => {
|
||||
it('coerces face_id / face_type from string-or-number and forwards to bridge.setDiyOnlineStatus', async () => {
|
||||
const setDiyOnlineStatus = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', {
|
||||
face_id: '1234',
|
||||
face_type: '2',
|
||||
wording: '摸鱼中',
|
||||
});
|
||||
expect(res.status).toBe('ok');
|
||||
expect(setDiyOnlineStatus).toHaveBeenCalledWith(1234, '摸鱼中', 2);
|
||||
});
|
||||
|
||||
it('defaults face_type to 1 when omitted, wording to empty string', async () => {
|
||||
const setDiyOnlineStatus = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
|
||||
await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', { face_id: 99 });
|
||||
expect(setDiyOnlineStatus).toHaveBeenCalledWith(99, '', 1);
|
||||
});
|
||||
|
||||
it('rejects missing face_id', async () => {
|
||||
const setDiyOnlineStatus = vi.fn();
|
||||
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', { wording: 'x' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(setDiyOnlineStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces bridge errors as action_failed with the original message', async () => {
|
||||
const bridge = fakeBridge({
|
||||
setDiyOnlineStatus: (async () => { throw new Error('denied'); }) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', {
|
||||
face_id: 1, wording: 'x',
|
||||
});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'denied' });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── set_group_portrait (Lagrange-protocol highway upload, cmdId 3000) ───
|
||||
|
||||
describe('extended-actions / set_group_portrait', () => {
|
||||
it('forwards group_id + file to bridge.setGroupAvatar', async () => {
|
||||
const setGroupAvatar = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({ setGroupAvatar: setGroupAvatar as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', {
|
||||
group_id: 12345, file: '/tmp/avatar.png',
|
||||
});
|
||||
expect(res.status).toBe('ok');
|
||||
expect(setGroupAvatar).toHaveBeenCalledWith(12345, '/tmp/avatar.png');
|
||||
});
|
||||
|
||||
it('rejects missing group_id or file', async () => {
|
||||
const setGroupAvatar = vi.fn();
|
||||
const bridge = fakeBridge({ setGroupAvatar: setGroupAvatar as any });
|
||||
const r1 = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', { file: 'x' });
|
||||
const r2 = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', { group_id: 1 });
|
||||
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(setGroupAvatar).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces highway / decode errors as action_failed', async () => {
|
||||
const bridge = fakeBridge({
|
||||
setGroupAvatar: (async () => { throw new Error('highway 500'); }) as any,
|
||||
});
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', {
|
||||
group_id: 1, file: 'x.png',
|
||||
});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'highway 500' });
|
||||
});
|
||||
});
|
||||
@@ -1,220 +0,0 @@
|
||||
// Regression coverage for nested forward (forward-inside-forward).
|
||||
//
|
||||
// `parseForwardNodes` detects an all-`{type:'node'}` content array,
|
||||
// recursively builds the inner `ForwardNodePayload[]`, and attaches it
|
||||
// to the outer node as `innerForward`. `uploadForwardNodes` then drives
|
||||
// the recursive long-msg upload + ARK-preview generation + msgBody
|
||||
// piggyback in one pass over the tree — modelled on NapCat's
|
||||
// `uploadForwardedNodesPacket` (`dev/NapCatQQ/.../SendMsg.ts:208`).
|
||||
//
|
||||
// These tests stub `bridge.uploadForwardNodes` so we can inspect the
|
||||
// payload that the upload pipeline receives: outer nodes carry an
|
||||
// `innerForward` field holding the parsed inner chain, and the
|
||||
// upload helper is invoked exactly ONCE (the recursive walk happens
|
||||
// inside the real implementation; mocks see only the top call).
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
|
||||
import {
|
||||
sendGroupForwardMessage,
|
||||
sendPrivateForwardMessage,
|
||||
} from '../../src/onebot/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
bridge,
|
||||
messageStore: { findEvent: () => null } as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
describe('forward — nested {type:"node"} content', () => {
|
||||
it('group: nested forward attaches inner chain to outer node via `innerForward`', async () => {
|
||||
// Single upload call, but the outer payload now carries an
|
||||
// `innerForward` field with the recursively-parsed inner chain.
|
||||
// The real `uploadForwardNodes` (the production module) walks
|
||||
// that tree and does the recursive long-msg uploads with NapCat
|
||||
// piggyback — we're just testing the parse-side handoff here.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'OUTER_RESID');
|
||||
const sendGroupMessage = vi.fn(async () => ({
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
|
||||
}));
|
||||
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
const messages = [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 111, nickname: 'outer',
|
||||
content: [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 222, nickname: 'inner',
|
||||
content: [{ type: 'text', data: { text: 'hello from inner' } }],
|
||||
},
|
||||
}],
|
||||
},
|
||||
}];
|
||||
|
||||
const result = await sendGroupForwardMessage(ctx, 12345, messages as any);
|
||||
|
||||
// Exactly one upload call: the production-side recursive walker
|
||||
// owns the inner upload, the OneBot parser just hands off the tree.
|
||||
expect(uploadForwardNodes).toHaveBeenCalledOnce();
|
||||
|
||||
const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[0]!;
|
||||
expect(outerGroupId).toBe(12345);
|
||||
const outerNode = (outerNodes as any[])[0]!;
|
||||
expect(outerNode.userUin).toBe(111);
|
||||
// Outer node's `elements` is empty — the upload pipeline replaces
|
||||
// it with the real ARK preview once it has the inner res_id.
|
||||
expect(outerNode.elements).toEqual([]);
|
||||
// The inner chain rides along as `innerForward`.
|
||||
expect(Array.isArray(outerNode.innerForward)).toBe(true);
|
||||
expect(outerNode.innerForward).toHaveLength(1);
|
||||
expect(outerNode.innerForward[0]).toMatchObject({
|
||||
userUin: 222,
|
||||
nickname: 'inner',
|
||||
elements: [{ type: 'text', text: 'hello from inner' }],
|
||||
});
|
||||
|
||||
expect(result.forwardId).toBe('OUTER_RESID');
|
||||
expect(sendGroupMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('private: nested forward threads userId into uploadForwardNodes', async () => {
|
||||
// Same shape but routed via sendPrivateForwardMessage. The c2c path
|
||||
// passes `userId` instead of `groupId` so the upload pipeline can
|
||||
// pick up the recipient's UID scene for any inner media element.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID');
|
||||
const sendPrivateMessage = vi.fn(async () => ({
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
|
||||
}));
|
||||
|
||||
const bridge = fakeBridge({ apis: { message: { sendPrivate: sendPrivateMessage }, forward: { upload: uploadForwardNodes } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
const messages = [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 111, nickname: 'outer',
|
||||
content: [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 222, nickname: 'inner',
|
||||
content: [{ type: 'text', data: { text: 'hi' } }],
|
||||
},
|
||||
}],
|
||||
},
|
||||
}];
|
||||
|
||||
await sendPrivateForwardMessage(ctx, 67890, messages as any);
|
||||
|
||||
// Single call, c2c-scoped (groupId undefined, userId = recipient).
|
||||
expect(uploadForwardNodes).toHaveBeenCalledOnce();
|
||||
const call = uploadForwardNodes.mock.calls[0]!;
|
||||
expect(call[1]).toBeUndefined();
|
||||
expect(call[2]).toBe(67890);
|
||||
// Inner chain attached via `innerForward`.
|
||||
const outerNode = (call[0] as any[])[0]!;
|
||||
expect(outerNode.innerForward).toHaveLength(1);
|
||||
expect(outerNode.innerForward[0]!.userUin).toBe(222);
|
||||
});
|
||||
|
||||
it('rejects nesting deeper than 3 levels', async () => {
|
||||
// Build a 4-level nested chain. NapCat caps at 3 too, going further
|
||||
// wastes long-msg uploads and risks one inner upload timing out
|
||||
// and aborting the whole tree. Better to fail loud here.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'X');
|
||||
const sendGroupMessage = vi.fn(async () => ({
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
|
||||
}));
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
function wrap(content: any, depth: number): any {
|
||||
if (depth === 0) return [{ type: 'text', data: { text: 'leaf' } }];
|
||||
return [{
|
||||
type: 'node',
|
||||
data: { user_id: 100 + depth, nickname: `lvl-${depth}`, content: wrap(content, depth - 1) },
|
||||
}];
|
||||
}
|
||||
|
||||
await expect(
|
||||
sendGroupForwardMessage(ctx, 12345, wrap(null, 4) as any),
|
||||
).rejects.toThrow(/depth/);
|
||||
});
|
||||
|
||||
it('flat content (no nesting) still goes through the unchanged path', async () => {
|
||||
// Backwards-compat: a single-level forward with plain text nodes
|
||||
// calls uploadForwardNodes exactly once and never touches the
|
||||
// recursive branch.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
|
||||
const sendGroupMessage = vi.fn(async () => ({
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
|
||||
}));
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
const messages = [
|
||||
{ type: 'node', data: { user_id: 111, nickname: 'a', content: [{ type: 'text', data: { text: 'one' } }] } },
|
||||
{ type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'two' } }] } },
|
||||
];
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, messages as any);
|
||||
expect(uploadForwardNodes).toHaveBeenCalledOnce();
|
||||
const [nodes] = uploadForwardNodes.mock.calls[0]!;
|
||||
expect((nodes as any[])).toHaveLength(2);
|
||||
expect((nodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'one' }]);
|
||||
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
|
||||
});
|
||||
|
||||
it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => {
|
||||
// Recursion only kicks in when *all* content entries are nodes —
|
||||
// mixed content is ambiguous (do the non-node parts belong to the
|
||||
// outer node or are they parallel siblings?), so we keep the legacy
|
||||
// behaviour and let parseMessage handle it. Non-node parts come
|
||||
// through, node parts get parsed via `case 'node':` and then
|
||||
// dropped by element-builder. A user who wants nested forward
|
||||
// should pass a pure node list.
|
||||
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
|
||||
const sendGroupMessage = vi.fn(async () => ({
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
|
||||
}));
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
const messages = [{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 111, nickname: 'mixed',
|
||||
content: [
|
||||
{ type: 'text', data: { text: 'a sibling' } },
|
||||
{ type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'lost' } }] } },
|
||||
],
|
||||
},
|
||||
}];
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, messages as any);
|
||||
expect(uploadForwardNodes).toHaveBeenCalledOnce();
|
||||
// Only the text element survives — the legacy "node MessageElement"
|
||||
// that parseMessage produces is opaque to the element-builder.
|
||||
const [nodes] = uploadForwardNodes.mock.calls[0]!;
|
||||
const elements = (nodes as any[])[0]!.elements;
|
||||
expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,83 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { GroupRequestInfo } from '@snowluma/bridge/qq-info';
|
||||
|
||||
// See `contact-actions.test.ts` for the auto-promotion rationale.
|
||||
const APIS_ROUTING: Record<string, string> = {
|
||||
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
|
||||
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
|
||||
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
|
||||
};
|
||||
|
||||
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
|
||||
const apisSynth: Record<string, Record<string, any>> = {};
|
||||
for (const [k, v] of Object.entries(overrides)) {
|
||||
const area = APIS_ROUTING[k];
|
||||
if (area) {
|
||||
if (!apisSynth[area]) apisSynth[area] = {};
|
||||
apisSynth[area][k] = v;
|
||||
}
|
||||
}
|
||||
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
|
||||
return new Proxy(merged as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
|
||||
return {
|
||||
groupId: 999,
|
||||
groupName: 'g',
|
||||
targetUid: 'u_t',
|
||||
targetUin: 5555,
|
||||
targetName: 'target',
|
||||
invitorUid: 'u_i',
|
||||
invitorUin: 7777,
|
||||
invitorName: 'inviter',
|
||||
operatorUid: 'u_o',
|
||||
operatorUin: 8888,
|
||||
operatorName: 'op',
|
||||
sequence: 42,
|
||||
state: 1,
|
||||
eventType: 7,
|
||||
comment: 'pls',
|
||||
filtered: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
it('matches add requests by groupId and targetUid', async () => {
|
||||
const setAddRequest = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }),
|
||||
]),
|
||||
apis: { groupAdmin: { setAddRequest } } as any,
|
||||
});
|
||||
|
||||
await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok');
|
||||
|
||||
expect(setAddRequest).toHaveBeenCalledOnce();
|
||||
expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false);
|
||||
});
|
||||
|
||||
it('matches invite requests by groupId and invitorUid', async () => {
|
||||
const setAddRequest = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }),
|
||||
]),
|
||||
apis: { groupAdmin: { setAddRequest } } as any,
|
||||
});
|
||||
|
||||
await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no');
|
||||
|
||||
expect(setAddRequest).toHaveBeenCalledOnce();
|
||||
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false);
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
// Regression coverage for the group-file-in-send_group_msg bug.
|
||||
//
|
||||
// Symptom in the wild: bot uploaded a group file via `upload_group_file`,
|
||||
// then sent `{type:'file', file_id}` through `send_group_msg`; the
|
||||
// element-builder wrapped it as `transElem(elemType=24, ...)` inside
|
||||
// `richText.elems` and shipped a regular `MessageSvc.PbSendMsg`. The
|
||||
// QQ-NT server rejected the message with `result=79` because that wire
|
||||
// shape is RECEIVE-side only (rich-body-decoder unpacks it into a
|
||||
// FileEntity for inbound messages, but the server's intake validator
|
||||
// flags it on the send side).
|
||||
//
|
||||
// Fix: split file segments off at the OneBot layer (same pattern as
|
||||
// the c2c-file split for private messages) and dispatch through
|
||||
// `bridge.apis.groupFile.publish`, which calls dedicated OIDB
|
||||
// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's
|
||||
// `GroupSendFileService.cs`.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
|
||||
import { sendGroupMessage } from '../../src/onebot/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
bridge,
|
||||
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
const goodReceipt = {
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
|
||||
};
|
||||
|
||||
describe('send_group_msg with {type:"file"} segment', () => {
|
||||
it('file-only message routes through apis.groupFile.publish (not apis.message.sendGroup)', async () => {
|
||||
// Pure-file case — the elems[] path used to ship a transElem(24)
|
||||
// and got result=79. The dedicated OIDB-0x6d9_4 route must take
|
||||
// over for group file publishing.
|
||||
const sendGroupMessage_bridge = vi.fn();
|
||||
// Declare params on the fn so `mock.calls[0]` infers a tuple of
|
||||
// [groupId, fileId] instead of `[]` (which makes the destructuring
|
||||
// a tsc error under noUncheckedIndexedAccess).
|
||||
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
|
||||
const bridge = fakeBridge({
|
||||
apis: {
|
||||
message: { sendGroup: sendGroupMessage_bridge },
|
||||
groupFile: { publish },
|
||||
} as any,
|
||||
resolveUserUid: vi.fn(),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendGroupMessage(ctx, 12345, [{
|
||||
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
|
||||
}] as any, false);
|
||||
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
|
||||
|
||||
const [groupId, fileId] = publish.mock.calls[0]!;
|
||||
expect(groupId).toBe(12345);
|
||||
expect(fileId).toBe('gfid-abc');
|
||||
});
|
||||
|
||||
it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => {
|
||||
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
|
||||
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
|
||||
const bridge = fakeBridge({
|
||||
apis: {
|
||||
message: { sendGroup: sendGroupMessage_bridge },
|
||||
groupFile: { publish },
|
||||
} as any,
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendGroupMessage(ctx, 12345, [
|
||||
{ type: 'text', data: { text: 'here is the file:' } },
|
||||
{ type: 'file', data: { file_id: 'gfid-xyz', name: 'pkg.zip' } },
|
||||
] as any, false);
|
||||
|
||||
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
|
||||
const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!;
|
||||
expect(textGid).toBe(12345);
|
||||
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
|
||||
|
||||
const [fileGid, fileFileId] = publish.mock.calls[0]!;
|
||||
expect(fileGid).toBe(12345);
|
||||
expect(fileFileId).toBe('gfid-xyz');
|
||||
});
|
||||
|
||||
it('file segment without file_id is skipped (with a warn-level log)', async () => {
|
||||
// Same upload-by-reference contract as the c2c file path —
|
||||
// missing file_id means there's nothing to publish.
|
||||
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
|
||||
const publish = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: {
|
||||
message: { sendGroup: sendGroupMessage_bridge },
|
||||
groupFile: { publish },
|
||||
} as any,
|
||||
resolveUserUid: vi.fn(),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendGroupMessage(ctx, 12345, [
|
||||
{ type: 'text', data: { text: 'with bad file segment' } },
|
||||
{ type: 'file', data: {} }, // no file_id
|
||||
] as any, false);
|
||||
|
||||
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,230 +0,0 @@
|
||||
// Regression coverage for the c2c-file-in-send_private_msg bug.
|
||||
//
|
||||
// Symptom in the wild: bot called `send_private_msg` with a
|
||||
// `{type:'file', file_id}` segment; the OneBot module passed it
|
||||
// straight to `bridge.sendPrivateMessage(userId, [fileElement])`;
|
||||
// `buildSendElems` warned ("file send via elems[] is group-only")
|
||||
// and dropped it; the resulting wire send had 0 elems and the chat
|
||||
// rendered "[空消息]".
|
||||
//
|
||||
// Fix: c2c file segments are split out at the OneBot layer in
|
||||
// `sendPrivateMessage` and dispatched through `bridge.sendC2cFileMessage`
|
||||
// (which writes `RichText.notOnlineFile`, the correct wire slot for
|
||||
// c2c files). Matches NapCat's `SendMsg.ts:404-415` which splits
|
||||
// FILE / VIDEO / ARK / PTT into their own sendMsg calls and never
|
||||
// mixes them with the regular elems[] batch.
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
|
||||
import { sendPrivateMessage } from '../../src/onebot/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
bridge,
|
||||
messageStore: { findEvent: () => null } as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
const goodReceipt = {
|
||||
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
|
||||
};
|
||||
|
||||
describe('send_private_msg with {type:"file"} segment', () => {
|
||||
it('file-only message routes through sendC2cFileMessage (not sendPrivateMessage)', async () => {
|
||||
// Pure-file case — the elems[] path would have dropped this entirely
|
||||
// and shipped "[空消息]". The c2c file route must take over.
|
||||
const sendPrivateMessage_bridge = vi.fn();
|
||||
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||
const resolveUserUid = vi.fn(async () => 'u_peer');
|
||||
const recallUploadedFile = vi.fn(() => undefined);
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
|
||||
resolveUserUid,
|
||||
recallUploadedFile,
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [{
|
||||
type: 'file',
|
||||
data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233' },
|
||||
}] as any, false);
|
||||
|
||||
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
|
||||
expect(sendPrivateMessage_bridge).not.toHaveBeenCalled();
|
||||
|
||||
const [uin, uid, info] = sendC2cFileMessage.mock.calls[0]!;
|
||||
expect(uin).toBe(67890);
|
||||
expect(uid).toBe('u_peer');
|
||||
expect(info).toMatchObject({
|
||||
fileId: 'uuid-abc',
|
||||
fileName: 'doc.txt',
|
||||
fileSize: 123,
|
||||
});
|
||||
// md5 decoded from hex (4 bytes for '00112233')
|
||||
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
|
||||
});
|
||||
|
||||
it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => {
|
||||
// Reproduces the "0 B file" bug: a caller passes only `file_id` from
|
||||
// a previous upload_private_file, with no size/md5/name. Without
|
||||
// the cache lookup the wire packet ships fileSize=0/md5=empty and
|
||||
// the recipient sees a 0-byte file. With the cache we recover the
|
||||
// real tuple.
|
||||
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||
const recallUploadedFile = vi.fn((id: string) => id === 'uuid-cached' ? {
|
||||
fileId: 'uuid-cached',
|
||||
scope: 'private' as const,
|
||||
userId: 67890,
|
||||
fileName: 'real-doc.pdf',
|
||||
fileSize: 4096,
|
||||
fileMd5: Buffer.from('aabbccddeeff', 'hex'),
|
||||
fileSha1: new Uint8Array(20),
|
||||
fileHash: 'srv-hash',
|
||||
rememberedAt: 0,
|
||||
} : undefined);
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any,
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
recallUploadedFile,
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [{
|
||||
type: 'file', data: { file_id: 'uuid-cached' },
|
||||
}] as any, false);
|
||||
|
||||
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
|
||||
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
|
||||
expect(info).toMatchObject({
|
||||
fileId: 'uuid-cached',
|
||||
fileName: 'real-doc.pdf',
|
||||
fileSize: 4096,
|
||||
fileHash: 'srv-hash',
|
||||
});
|
||||
expect(info.fileMd5).toEqual(Buffer.from('aabbccddeeff', 'hex'));
|
||||
});
|
||||
|
||||
it('inline segment fields take precedence over the upload cache', async () => {
|
||||
// If the caller threads the metadata inline (e.g. they tracked the
|
||||
// upload response themselves), honour that over the cache so a
|
||||
// refresh of an evicted file still works.
|
||||
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||
const recallUploadedFile = vi.fn(() => ({
|
||||
fileId: 'uuid-x',
|
||||
scope: 'private' as const,
|
||||
userId: 67890,
|
||||
fileName: 'stale-cache-name.txt',
|
||||
fileSize: 99,
|
||||
fileMd5: new Uint8Array(16),
|
||||
fileSha1: new Uint8Array(20),
|
||||
fileHash: 'stale-hash',
|
||||
rememberedAt: 0,
|
||||
}));
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any,
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
recallUploadedFile,
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [{
|
||||
type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' },
|
||||
}] as any, false);
|
||||
|
||||
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
|
||||
expect(info).toMatchObject({
|
||||
fileName: 'inline.txt',
|
||||
fileSize: 200,
|
||||
fileHash: 'inline-hash',
|
||||
});
|
||||
expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex'));
|
||||
});
|
||||
|
||||
it('mixed file + text splits across two sends (text first, file second)', async () => {
|
||||
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
|
||||
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
|
||||
const resolveUserUid = vi.fn(async () => 'u_peer');
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
|
||||
resolveUserUid,
|
||||
recallUploadedFile: vi.fn(() => undefined),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'text', data: { text: 'here is the file:' } },
|
||||
{ type: 'file', data: { file_id: 'uuid-xyz', name: 'pkg.zip' } },
|
||||
] as any, false);
|
||||
|
||||
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
|
||||
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
|
||||
|
||||
// Text goes via the elems[] pipeline.
|
||||
const [textUin, textElements] = sendPrivateMessage_bridge.mock.calls[0]!;
|
||||
expect(textUin).toBe(67890);
|
||||
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
|
||||
|
||||
// File goes via the dedicated c2c-file API.
|
||||
const [fileUin, fileUid, fileInfo] = sendC2cFileMessage.mock.calls[0]!;
|
||||
expect(fileUin).toBe(67890);
|
||||
expect(fileUid).toBe('u_peer');
|
||||
expect(fileInfo).toMatchObject({ fileId: 'uuid-xyz', fileName: 'pkg.zip' });
|
||||
});
|
||||
|
||||
it('file segment without file_id is skipped (with a warn-level log)', async () => {
|
||||
// OneBot11 file segments are upload-by-reference — without a
|
||||
// file_id there's nothing to send. Previously these slipped
|
||||
// through to the elems[] path and shipped empty messages.
|
||||
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
|
||||
const sendC2cFileMessage = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
|
||||
resolveUserUid: vi.fn(),
|
||||
recallUploadedFile: vi.fn(() => undefined),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'text', data: { text: 'with bad file segment' } },
|
||||
{ type: 'file', data: {} }, // no file_id
|
||||
] as any, false);
|
||||
|
||||
// Text still went out, file dropped (no c2c file call).
|
||||
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
|
||||
expect(sendC2cFileMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws when uid cannot be resolved for a file-only message', async () => {
|
||||
// C2C file send requires the recipient's UID for the RichText.
|
||||
// notOnlineFile routing. If lookup fails we can't proceed —
|
||||
// surfacing the error is better than shipping a c2c send with
|
||||
// an empty uid.
|
||||
const sendC2cFileMessage = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any,
|
||||
resolveUserUid: vi.fn(async () => ''), // intentional empty
|
||||
recallUploadedFile: vi.fn(() => undefined),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
|
||||
await expect(sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'file', data: { file_id: 'uuid-orphan', name: 'x.txt' } },
|
||||
] as any, false)).rejects.toThrow(/could not resolve uid/);
|
||||
|
||||
expect(sendC2cFileMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user